Python Forum
Guess the dice roll mini-game
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Guess the dice roll mini-game
#1
Hey everyone, I just finished my first program, I've been learning python for about 3 days now.

I am wondering if there are ways I can make my code smaller / optimized more.

import random

userScore = 0
userTries = 7
print ("Welcome to the dice game! where you guess the number thats about to be rolled. Get a score of 3 to win!")
print ("Your score is:", userScore, "\n")

while (userScore <= 3):
	while (userTries >= 0):

		diceNum = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)

		print ("Tries left:", userTries, "\n")
		userGuess = input ("Enter your guess: " )

			# checks if users guess is NOT in the diceNum list
		if (int(userGuess) not in diceNum):
			print (userGuess, "\nis not a valid guess, try again.")
			userTries -= 1

			#if the user guess IS IN the diceNum list it continues with the next statement
		else:
			diceNum = random.choice(diceNum)
			print ("\nThe dice rolled...", diceNum)

			#Checks if the random generated number matches the guess
		if (int(diceNum) == int(userGuess)):
			userScore += 1
			print ("You guessed it right! +1")
			print ("Your score:", userScore)

			# checks if user guessed right if no take away a point
		elif (int(diceNum) != int(userGuess)):
			userTries -= 1
			print ("You guessed wrong try again -1 try")
			print ("Your score: ", userScore)

			#only solution i found to not get stuck in one of the while loops when user tries = 0 or score = 3
		if (userTries == 0):
			break
		elif (userScore == 3):
			break
	if (userTries == 0):
		break
	elif (userScore == 3):
		break


print ("Goodbye!")
Appreciate any feedback!

Thanks
Reply
#2
You have done an excellent job for only a few days worth of experience.

a. I like the way your code looks, however, unfortunately for both you and me, the space before the 'left parenthesis' is not according to Python standards. That is fine if the code is only for yourself, but we have to change our 'evil' ways if we want to share our code with others. Take a look at Python PrettyPrint formatting standards PEP-8: https://www.python.org/dev/peps/pep-0008/

b. What if user enters a non-number as a guess? Since the guess is an 'integer only', your tests don't have to do any casting (i.e. 'int(userGuess)' not required.)
try:
    userGuess = int(input ("Enter your guess: " ))
except:
    print("Guess was NOT a Number.")    
c. You probably want to omit '2' from your tuple of choices if you want a uniform distribution. Your probably want to roll 1..6 twice. You don't want the tuple and the dice roll to be the same variable name in either case.
diceTuple = (1, 2, 3, 4, 5, 6)
# ...
diceNum = random.choice(diceTuple)
diceNum += random.choice(diceTuple)

# or 
diceNum = random.choice(diceTuple) + random.choice(diceTuple)
d. Excellent choice of 'tuple' instead of a 'list', because a 'tuple' can't be changed and is faster. For more info see: https://stackoverflow.com/questions/1708...o-use-each

e. Try changing the while condition to:
while True:
You only need your final test at the bottom of the loop

When you are done, or if you need additional help, please share your code with us.

Lewis
To paraphrase: 'Throw out your dead' code. https://www.youtube.com/watch?v=grbSQ6O6kbs Forward to 1:00
Reply
#3
(May-19-2018, 04:22 PM)ljmetzger Wrote: You have done an excellent job for only a few days worth of experience.

a. I like the way your code looks, however, unfortunately for both you and me, the space before the 'left parenthesis' is not according to Python standards. That is fine if the code is only for yourself, but we have to change our 'evil' ways if we want to share our code with others. Take a look at Python PrettyPrint formatting standards PEP-8: https://www.python.org/dev/peps/pep-0008/

b. What if user enters a non-number as a guess? Since the guess is an 'integer only', your tests don't have to do any casting (i.e. 'int(userGuess)' not required.)
try:
    userGuess = int(input ("Enter your guess: " ))
except:
    print("Guess was NOT a Number.")    
c. You probably want to omit '2' from your tuple of choices if you want a uniform distribution. Your probably want to roll 1..6 twice. You don't want the tuple and the dice roll to be the same variable name in either case.
diceTuple = (1, 2, 3, 4, 5, 6)
# ...
diceNum = random.choice(diceTuple)
diceNum += random.choice(diceTuple)

# or 
diceNum = random.choice(diceTuple) + random.choice(diceTuple)
d. Excellent choice of 'tuple' instead of a 'list', because a 'tuple' can't be changed and is faster. For more info see: https://stackoverflow.com/questions/1708...o-use-each

e. Try changing the while condition to:
while True:
You only need your final test at the bottom of the loop

When you are done, or if you need additional help, please share your code with us.

Lewis

a. Okay, I fixed the spaces in the code, even though this code is only intended for me and not anyone else I will still try to get in a habit of doing so.

b. I have a check for this in the original code, it checks if the users guess is in the tuple, if it is not then it takes away a try and makes the user start from the beginning.
if(userGuess not in diceNum):
			print(userGuess, "\nis not a valid guess, try again.")
			userTries -= 1
c. Okay, I can see what you mean by that, it could cause errors later on. I went ahead and fixed the mistake.
diceTuple = (1, 2, 3, 4, 5, 6) #make dice Tuple a tuple data inside the tuple will never change
diceNum = random.choice(diceTuple) + random.choice(diceTuple) # setting the variable diceNum to random choice and add the 2 choices together
e. I changed the whole loop to while true instead of nesting 2 loops, makes it much easier to read and understand to just have the loop break if a certain condition is met.

Here is the full code:

import random

possibleAnswers = (1,2,3,4,5,6,7,8,9,10,11,12)
userScore = 0
userTries = 7
print ("Welcome to the dice game! where you guess the number thats about to be rolled. Get a score of 3 to win!")
print ("Your score is:", userScore, "\n")

while True:
	diceTuple = (1, 2, 3, 4, 5, 6) #make dice Tuple a tuple data inside the tuple will never change
	diceNum = random.choice(diceTuple) + random.choice(diceTuple) # setting the variable diceNum to random choice and add the 2 choices together
	print("Tries left:", userTries, "\n")
	userGuess = int(input("Enter your guess: " )) # setting the user guess to a int instead of a string
	if(userGuess not in possibleAnswers): # checks if the guess is in the possible answer tuple
		print(userGuess, "\nis not a valid guess, try again.")
		userTries -= 1
	else: # if the user guess is in the possible answers tuple continue to the next block of code
		print("\nThe dice rolled...", diceNum)
	if(diceNum == userGuess): # checks if the users guess is =  to the random dice roll then adds +1 to score
		userScore += 1
		print("You guessed it right! +1")
		print("Your score:", userScore)
	elif(diceNum != userGuess): #if random dice roll doesnt = user guess -1 try
		userTries -= 1
		print("You guessed wrong try again -1 try")
		print("Your score: ", userScore)
	if(userScore == 3): #when user reaches a score of 3 break out of the loop
		break
	if(userTries == 0): #when the user hits 0 tries break out of the loop
		break

print ("Goodbye!")
Reply
#4

  1. Your names are un-Pythonic - Python uses snake-style, your names are camel-style (Java background?) Read PEP-8. Brackets in conditionals expressions are redundant too
  2. There is a better way to define sequence of integers - with range
    possible_answers = list(range(1, 13))
  3. including tuple clarification in name ?!
  4. Actually , the fastest test of belonging is against the set (guess, why I start from 2)
    possible_answers = set(range(2, 13))
  5.         if (userTries == 0):
                break
            elif (userScore == 3):
                break
    shoudl be re-written as
    if user_tries == 0 or user_score == 3:
        break
  6. elif dice_num != user_guess: is absolutely redundant; since you already check equal condition, else will do
  7. Instead of defining dice_tupe Naughty and then random.choice(dice_tuple), I would suggest random.randint(1, 6)

(May-19-2018, 10:28 PM)tawnnx Wrote: even though this code is only intended for me and not anyone else

The moment you asked for help, you intended your code for someone else. For Pythonista, reading you code is somewhat unpleasant experience.
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#5
Sorry to thread-break, but what is snake-style naming? I assume camel-style is capitalizing the first letter in the second word of the variable, i.e. camelStyle? I've seen that in videogame scripts and was wondering why some people named variables that way. Java, you say? Anywho, what's snake-style?
Reply
#6
(May-21-2018, 11:30 PM)malonn Wrote: Sorry to thread-break, but what is snake-style naming? I assume camel-style is capitalizing the first letter in the second word of the variable, i.e. camelStyle? I've seen that in videogame scripts and was wondering why some people named variables that way. Java, you say? Anywho, what's snake-style?

This is snake_style name. RTPEP-8
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#7
Cool, thanks. Sorry to hijack. Back on topic...
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Guess your number joe_momma 0 2,456 Oct-23-2020, 02:53 AM
Last Post: joe_momma
  Guess my number foksikrasa 0 2,394 May-28-2020, 04:12 PM
Last Post: foksikrasa
  SKUNK Dice Game ProntName 9 6,525 Apr-19-2020, 12:15 PM
Last Post: eXcalibur432
  guess my number GAME ronblue77 2 2,775 Nov-24-2019, 04:23 PM
Last Post: CodingStranger
  Mastermind/Guess the Code Game JoeLamond 5 12,289 Jan-14-2019, 06:34 PM
Last Post: steve_shambles
  5 mini programming projects for the python beginner kerzol81 4 36,223 Sep-26-2017, 02:36 PM
Last Post: VeenaReddy
  Mini-Web Framework nilamo 12 9,737 Jun-15-2017, 05:32 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020