1
\$\begingroup\$

This is my first dice game and I have spent countless hours working on it, yet it is still very basic. I was wondering if anyone could spare the time to suggest improvements.

import time
import random
import sys
Password= 'password'
while True:
    password= input('ENTER PASSWORD:')
    if password == Password:
        time.sleep(0.5)
        print('VERIFYING')
        for i in range(4):
            time.sleep(.3)
            sys.stdout.write(".")
            sys.stdout.flush()
            time.sleep(.8)
        print ('\nWELCOME BACK!')
        break
    print ('TRY AGAIN')
time.sleep(.6)
answer = input('\nDo you want to play a game? : ')
if answer == 'yes' or 'Yes' or 'Y' or 'y' or 'YES':
    print("Let's Start")
    print ('Please type Your name!: ')
    name = input()
    time.sleep(.6)
    print ('Hello ' +str( name))
    time.sleep(.7)   
max = 12
min = 1
x_count=0
y_count=0
def displayIntro():     
    x = random.randint(min,max)
    y = random.randint(min,max)   
    print('\n\n*****NEW ROUND*****')
    time.sleep(.5)
    print("\n\nThe computer's number is... "+str(y))
    time.sleep(1)
    input("\nPress 'Enter' to roll the die...")            
    time.sleep(1.2)
    print('\nYour number is... ' +str(x))    
    if (x > y):
        time.sleep(.5)
        print("\nYOUR NUMBER WAS HIGHER THAN THE COMPUTER'S! YOU WIN!")
        global x_count
        x_count = x_count + 1       
    if (x < y):
        time.sleep(1)
        print ("\nTHE COMPUTER'S NUMBER WAS HIGHER THAN YOURS! YOU LOSE!")
        global y_count
        y_count = y_count + 1   
    print('Your score is... ' +str(x_count))
    print('PC score is... '+str(y_count))
playagain = 'yes'
while playagain == 'yes': 
    displayIntro()
    playagain = input('\n\nDo you want to play again? (yes or no)')
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Just realized, minimum should be 2, not 1. Whenever you roll two dice the minimum is 2. \$\endgroup\$ Commented Feb 17, 2016 at 6:06

2 Answers 2

2
\$\begingroup\$

As someone noted in a comment, the minimum of rolling two dice is actually 2, not 1. But also, when rolling two dice you don't have an equal chance of getting every number. 2 and 12 are the most rare results, while 7 is the most common. This is because of the numbers that can pair to make them. 2 can only be the result of 1 and 1, but 7 could be: [1, 6], [2, 5], [3, 4], [4, 3], [5, 2], [6, 1]. That makes 7 six times more likely to crop up than 2, but you have them at equal chances.

I'm not suggesting you create a weighted system, but I'm trying to highlight why using a flat random generation is counter productive. Instead, you should have a dice rolling function, like this:

def roll():
    return random.randint(1, 6)

Then you could just get two dice rolls with roll() + roll(). It would also be easy to get 3 or more dice. And since it's a function, we could easily change it to be any sided die greater than 1, rather than just 6.

def roll(sides):
    return random.randint(1, sides)

For the sake of robustness, I'd raise an error if sides is less than 1

def roll(sides):
    """Return random roll of dice with `sides` number of sides."""

    if sides < 1:
        raise ValueError("Dice must have at least one side.")

    return random.randint(1, sides)
\$\endgroup\$
0
3
\$\begingroup\$

Your code looks pretty good! Well done. However, there are some some minor points that could be improved.

Variable names

Throughout your code, you use variable names that can be misinterpreted--not terribly, but the possibility is there. For example Password vs password. You may want to consider using password_compare and inputted_password or something along those lines to differentiate the two. Also, this was something I was not previously aware of, but it looks like Password is a python key word. Avoid using these as variable or function names. You can read more about this here. The gist of it is that Python reserves several dozen keywords required for function/method calls that, if used, can result in unusual errors. Examples include list and the logical operators (and, or, if).

Functions

Your function names also could use some work. As a general rule, snake_case is used for functions and variables, and PascalCase for classes.

On top of this, your function is in the wrong place, style wise. Functions should be defined at the top of your program, after any global variables and all imports. You should put the function displayIntro() (which should be display_intro()) before all your code and immediately after your imports.

Nitpicking

Here is a list of nitpicks that will help improve the readability and "pythonic-ness" of your code.

  • Spaces: when defining or using variables, you often have it like var= "value". To avoid confusing it with Bash and keep it consistent, have one space before and after the equals operator, like var = "value".

  • elif vs if: when more than one if statements are used (i.e.--if an operation or function requires two or more conditionals for ONE situation) use elif to describe the other conditionals. This makes your code much more efficient--with if+elif, if one condition is satisfied, the interpreter will not check the other ifs once any of the condition has been satisfied. However, if you use multiple if statements for the same set of conditionals, then it will check the other if statements, even if one has already been satisfied. This can lead to buggy code. See here for a similar question.

  • while True: This could be changed to while inputted_password != password_compare to shorten the code and remove the if statement. Your way is just as efficient, however, so it doesn't really matter if it is changed.

  • As mentioned before, functions should go BEFORE your code.

  • Globalizing: When globalizing variables, the global command goes at the top of the function, before any code.

  • Whitespace: I for one don't really care about tabs vs. spaces, but there are some examples of whitespace that are imperative for readability. Keep space between top level sections of code (like imports, functions, and pre-sections of code) to improve readability.

  • Commenting: This code is fairly pleasant to read. However, a little commenting goes a long way! It is also good practice to describe your functions with docstrings.

Here is your code based off of these suggestions:

import time
import random
import sys

def display_intro():  
    '''Playing the game!'''   
    global x_count, y_count
    x = random.randint(min,max)
    y = random.randint(min,max)

    print('\n\n*****NEW ROUND*****')
    time.sleep(.5)
    print("\n\nThe computer's number is... "+str(y))
    time.sleep(1)

    input("\nPress 'Enter' to roll the die...")

    time.sleep(1.2)
    print('\nYour number is... ' +str(x))

    if (x > y):
        time.sleep(.5)
        print("\nYOUR NUMBER WAS HIGHER THAN THE COMPUTER'S! YOU WIN!")
        x_count = x_count + 1

    elif (x < y):
        time.sleep(1)
        print ("\nTHE COMPUTER'S NUMBER WAS HIGHER THAN YOURS! YOU LOSE!")
        y_count = y_count + 1

    print('Your score is... ' +str(x_count))
    print('PC score is... '+str(y_count))

# Checking login credentials
password_compare = 'password'
while True:
    inputted_password = input('ENTER PASSWORD:')
    if inputted_password == password_compare:
        time.sleep(0.5)
        print('VERIFYING')
        for i in range(4):
            time.sleep(.3)
            sys.stdout.write(".")
            sys.stdout.flush()
            time.sleep(.8)
        print ('\nWELCOME BACK!')
        break
    print ('TRY AGAIN')

time.sleep(.6)

# Does the user want to play?
answer = input('\nDo you want to play a game?: ')
if answer == 'yes' or 'Yes' or 'Y' or 'y' or 'YES':
    print("Let's Start")
    print ('Please type Your name!: ')
    name = input()
    time.sleep(.6)
    print ('Hello ' +str( name))
    time.sleep(.7)

max = 12
min = 1
x_count = 0
y_count = 0


play_again = 'yes'
while play_again == 'yes': 
    displayIntro()
    play_again = input('\n\nDo you want to play again? (yes or no)')
\$\endgroup\$
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.