Beginner Python: Craps Game, while loop implementation - python

I am a beginner programmer and I need help with some parts of my code. I am currently creating a craps game simulator, but it appears that my code wont really run. My code is attached and for a few notes, every time there is a roll of the dice, the user must hit enter which will cause the program to roll the dice.
For a brief overview, here is some of the rules behind craps:
Each round has two phases: "come-out" and "point". To start a round,
the shooter makes one or more "come-out" rolls. A come-out roll of 2,
3 or 12 loses and is called "crap-out". A come-out roll of 7 or 11 (a
"natural") wins. The other possible numbers are the point numbers: 4,
5, 6, 8, 9, and 10. If the shooter rolls one of these numbers on the
come-out roll, this establishes the "point" and continues to the point
phase. At the point-phase, if the user rolls the same number as the
come-out phase, they "Hit" or win the game. If they roll a 7 however,
they "seven-out" or lose the game. If the player doesn't get a 7 or
the same come-out number, they keep rolling until they either hit or
seven-out.
My issue is that when the program runs, i am able to get Please hit enter, but when I hit enter, it wont continue to the next part of the code which will roll the dice. I can't quite figure out why that happens. Also, I may need some help looking at the logic behind my code, I am not entirely sure if when implemented, the desired results would occur. Any help is appreciated!
import random
def playRound():
#This will print out the current phase.
print "The come-out phase:"
print
#This will tell the user to hit enter to roll the dice.
rollDice = raw_input("Hit ENTER to roll the dice...")
#this will ensure that when a user hits enter, the program moves on.
if rollDice == rollDice:
#this will sum up two random integers to simulate two dice being thrown and record the total.
diceTotal = random.randint(1,6) + random.randint(1,6)
#this will see if the numbers are 7 or 11, and if so, will let the user know they won.
if diceTotal in (7,11):
return "You rolled a", diceTotal
return "You Win: Natural!"
#this will see if numbers are 2, 3, or 12, and if so, will let user know they lost.
if diceTotal in (2,3,12):
return "You rolled a", diceTotal
return "You Lose: Crap-Out!"
#let user know what they rolled if conditions above are not met.
return "You Rolled a", diceTotal
#This will now start the point phase.
print "The Point Phase:"
print
#this will ask the user to hit enter to roll the dice.
rollDice = raw_input("Hit ENTER to roll the dice...")
#this will ensure that when the user hits enter, the dice will roll.
if rollDice == rollDice:
#this will add up the sum of two random numbers simulating dice and save to variable.
diceTotalPoint = random.randint(1,6) + random.randint(1,6)
#this will see if the roll is not 7 or the diceTotal from come-out phase.
while diceTotalPoint not in (7, diceTotal):
#This will continue to roll the dice, if 7 or the come-out phase number is not achieved.
rollDice = raw_input("Hit ENTER to roll the dice...")
if rollDice == rollDice:
diceTotalPoint = random.randint(1,6) + random.randint(1,6)
#this will tell the user that if the dice roll is the same as the come-out phase, it will be a hit and they win.
if diceTotalPoint == diceTotal:
return "You Rolled a", diceTotalPoint
return "You Win: Hit!"
#this will tell the user if they get a 7, and tell them they lose.
if diceTotalPoint == 7:
return "You Rolled a", diceTotalPoint
return "You lose: Seven-Out!"

For starters, a return statement bails out of the function it is in. So
return "You rolled a", diceTotal
return "You Lose: Crap-Out!"
Never will get to "You Lose: Crap-Out!" since it skips out on the first return value. Use print instead.
I echo Frederick's comment about the if rollDice == rollDice part, no need to put that into an if statement at all since it will always run.
Overall this is a beast of a function. I would suggest splitting this up into multiple functions, or better yet classes to make things easier to manage. Right now it's a god function (http://iwanttocode.wordpress.com/tag/god-function/), which is just begging for pain wrt maintenance or debugging. Also think about how with the code you posted there is 0 reusable code if you want to write another program for another dice game.

Some error messages might help the readers.
I think your problem is that you should print everywhere that you are currently using return.
See Why would you use the return statement in Python?.
Other notes: if rollDice == rollDice: will always be true - why even include it?

Related

How do I fix my (supposedly while-loop or if-statement) dice-simulator in Python so it prints the amount of tries its taken before landing on a 6?

So, I'm a little stuck on a coding assignment of mine – I'm supposed to write a code in Python simulating the throw of a dice, in which the program randomizes numbers between 1-6 until it "lands" on the number 6; the program is furthermore supposed to count the number of tries it has "thrown the dice" before "landing" on a 6, and print out print("It took", n, "tries to get a six.") in which n = the number of tries it has thrown the dice before landing on a 6.
This is what I've come up with thus far:
import random
dice = random.randint(1,6)
n = 0
while dice == 6:
n = n + 1
print("It took", n, "tries to get a 6.")
break
But, alas, it only prints out "It took 1 try to get a 6." in the result window and shows blank in the result window whenever the "dice" doesn't land on a 6. I guess what my question is, is: how do I get it to count all the tries before landing on a 6, and subsequently print the said amount of tries in combination with the statement print("It took", n, "amount of tries to get a 6.")?
The usual pattern for repeating an action an unknown number of times is to use a while True loop, and then break out of the loop when the exit condition is satisfied.
rolls = 0
while True:
die = random.randint(1, 6)
rolls += 1
if die == 6:
break
print("It took", rolls, "tries to get a 6.")
You need to write your break command into an if-statement.
In your current code it breaks within the first iteration.
As this is an assigment i dont want to tell you everything.
But that while loop condition won't get you there.
Try writing a blank while loop with a break-condition, think about it.

Why is the first part of the code repeating (the introduction) when it should only run once after the variable Round is changed?

import random, time
def main():
AIMoney = 0
AINumGen = '0'
PlayerMoney = 0
Round = 1
PlayerChoice = ""
Result = ""
if Round == 1:
print ("You are in prison for the robbing of a world famous museum. You have the choice of either betraying (by confessing your partner's involvement) your partner, or colluding. (sticking to a story, so you both keep the money as initially intended.) Your goal is to get the most money by the end, keeping your reward from the heist together. You wil play ten rounds against an A.I, attempting to beat them and this tricky game. This means there are four results in total, and you both have two options per instance:")
print ("")
print ("If both of you collude, you both stay out of prison, and you both gain a reward by splitting the amount of money you make in half. If you both collude the entire time throughout every round, it will always end in a tie for both of you. Result: +100 money for each of you.")
print ("")
print("If both of you betray each other, you both receive no penalty, but neither of you get anything out of it. +0 money for both of you. Having 0 or negative points at the end of the game will result in a loss.")
print("")
print ("If you collude, but the other person betrays you, you will be punished severely by the person taking all of the valuables. Since you put in money to even commit the heist initally, you lose money in this situation, and are put into prison for your crimes.")
print("")
if Round == 10:
print("The game has ended. Final Result:")
print("AI's Money:" + AIMoney)
print("Your Money:" + PlayerMoney)
exit
User = input("Type C to collude with your partner, and B to betray your partner.")
if User == 'C':
AINumGen == random.randint(1, 10)
Round = Round + 1
if AINumGen < '4':
Result = Result + "betrayed you."
print ("You chose to collude with your partner and they " + Result)
PlayerMoney = PlayerMoney - 200
elif AINumGen > '4':
Result = Result + "colluded with you."
print("You chose to collude with your partner and they " + Result)
print("Your money after this round: " + str(PlayerMoney))
if User == 'B':
Result = Result
Round = Round + 1
print("You chose to betray your partner and they" + Result)
print("Your money after this round: " + str(PlayerMoney))
if User == 'Debug':
main()
if Round != 10:
User = input("Type C to collude with your partner, and B to betray your partner.")
main()
else:
print("Invalid Input")
main()
I'd also appreciate any help with the rest, as the variable Round never seems to be changed -- Even if the code is run nine or so times to get the end of the game result, it doesn't do anything. I have a feeling it has something to do with the order of the operations.
Since you are calling the main() function again, the variable Round is getting reinitialized and that's why the part is being called there..
Not sure about the other variables but you need to keep a check on what you need to initialize each time when the condition is being called.
try keeping the variables out of the main function
Here is a short breakdown of what is happening:
You call main() and set Round = 1.
You play the game once.
If Round != 10 (which it is now), you print the question again, then call main().
main() sets Round as 1 again, making the loop indefinite.
You have 2 options:
Go for a for loop if you always will have 10 rounds. After 10 rounds are over, you can show the result.
Go for recursion if you can have indefinite amount of rounds. The change you will do here is pass the round number as an argument to the function. If round is 1, print the instructions and if you want to end the game, pass some specific number (eg 10) to the function.

Loop never seems to actually loop

print("Welcome to my dice game.")
print("First enter how many sides you would like your dice to have, 4, 6 or 12")
print("Then this program will randomly roll the dice and show a number")
#Introduction explaing what the game will do. Test 1 to see if it worked.
while True:
#starts a while loop so the user can roll the dice as many times as they find necessary
import random
#Imports the random function so the code will be able to randomly select a number
dice = int(input("Enter which dice you would to use,4, 6, or 12? "))
#set a variable for the amount of dice number
if dice == 12:
x = random.randint(1,12)
print("You picked a 12 sided dice. You rolled a " + str(x) + " well done")
#Test 2 see if it does pick a random number for a 12 sided di
elif dice == 6:
x = random.randint(1,6)
print("You picked a 6 sided dice. You rolled a " + str(x) + " well done")
#Test 3 see if it does pick a random number for a 6 sided di
elif dice == 4:
x = random.randint(1,4)
print("You picked a 4 sided dice. You rolled a " + str(x) + " well done")
#Test 4 see if it does pick a random number for a 4 sided di
else:
print("Sorry, pick either 12, 6 or 4")
#Test 5 tells the user that they can only pick 4, 6 or 12 if anything else is entered this error shows
rollAgain = input ("Roll Again? ")
if rollAgain == "no":
rollAgain = False
if rollAgain == "yes":
rollAgain = True
break
print ("Thank you for playing")
#if the user enters anything apart from yes y or Yes. The code ends here.
That is the code i have so far. However the code will never actually go to the beginning of the loop, no matter what i enter the code just displays "Thanks for playing" and ends. Can anyone please tell me where i have went wrong?
First, you should be using raw_input to get the user's selection. (assuming python 2) If you're using python 3 then input is fine and keep reading.
Anyway, it'll still quit when you type yes because you break out of the loop! You should move the break statement into the "no" case so it breaks out when you say you do not want to roll again.
rollAgain = raw_input ("Roll Again? ")
if rollAgain == "no":
break
You don't need to set rollAgain to true or false at all. With the above code, anything other than "no" is assumed to be "yes" but you can add checks for that easily.
The problem is that you break your loop when the user wants to roll the dice again. The loop should break when the player doesn't want to play again so you have to do :
http://pastebin.com/hzC1UwDM

While loop does not seem to check condition correctly

I'm building a game as part of a tutorial on learning code.
The following class has a while loop that should return either 'finished' or, leave the loop and return 'death' (These are dict entries that run the game) but instead does not even seem to run. I'm looking at the while loop after def guess:
The loop is meant to ask the user to guess a number between 1 and three. If they guess wrong more than three times they "lose" and 'death' is returned, else 'finished'.
But, when I play the game I am not even prompted to enter a number, instead "Too many failed guesses, you lose!" is printed, even if guesses is 0.
class Smaug(Scene):
def enter(self):
print "Smaug is a terrifying huge fire breathing dragon, but you must get the Arkenstone from him for Thorin"
print "In Smaug's cave, the Lonely Mountain, Smaug notices your presence and challenges you to a game"
print "He says \"Guess a number between 1 and 3\""
smaugNum = random.randint(1, 3)
print "Smaugs number cheat:", smaugNum
guesses = 0
def guess():
while guesses < 4:
print "Guess a number between 1 and 3"
numb = raw_input("> ")
if numb == smaugNum:
print "Well done! You win."
Player.BilbosStuff.append('arkenstone')
print "Now Bilbo has", Player.BilbosStuff
return 'finished'
else:
print "You lose!"
guesses += 1
guess()
print "Too many failed guesses, you lose!"
return 'death'
Looking at the nesting of the code blocks, is it that when 'finished' is returned in the while loop, does it also, automatically, get returned as part of the wider class? Put another way, if numb == smaugNum then I need Smaug class to return finished.
The problem is that you are not calling the guess() function at all.. You have guess() as a function and it is not called at all. so, the control directly jumps to the next line after the function. The best way is to remove the function and use the code like this:
guesses = 0
while guesses < 4:
print "Guess a number between 1 and 3"
numb = raw_input("> ")
if numb == smaugNum:
print "Well done! You win."
Player.BilbosStuff.append('arkenstone')
print "Now Bilbo has", Player.BilbosStuff
return 'finished'
else:
print "You lose!"
guesses += 1
print "Too many failed guesses, you lose!"
return 'death'
You are defining guess smack dab in the middle of enter, but you are never calling it.
The blocks are like
class Smaug:
def enter:
#here's what to do when enter() is called
def guess:
#here's what to do when guess() is called
#here's some more stuff to do when enter() is called
The problem here is that you are infinitely recursing down the guess function and never calling guess() in the first place.
After you increase your guesses counter you do not need to call guess() again as the execution will still be inside the while loop due to the number of guesses being less than 4, simply trust the while loop to do the comparison. Avoid calling guess() manually.

How do you convert inputted data to uppercase so that it is recognised by a while loop?

I am trying to create a program that allows the user to keep using the program as long as what they enter is YES or a form of yes. I have created the program and it works and continues to loop providing they enter YES in uppercase.
I have tried to modify my code so that at the end when it asks if they would like to repeat it takes the input and converts it to uppercase I know you can use while repeat is in [" "," "] but is there a better way to write the code so that it will convert the inputted data to uppercase on the final input?
I have tried
repeat = input()
repeat = repeat.upper()
but this does not work. Any suggestions?
#Import the random function - This only needs to be imported once.
import random
#Use a while loop to allow the user to repeat the process
repeat = "YES"
while repeat == "YES":
#User is able to input which sided dice they want to throw.
dice = input("What side dice do you want to use? 4, 6, or 12?\n")
#4 sided
if dice == "4":
#Outputs what sided dice has been chosen and the score thay they rolled.
print(dice, "sided dice chose.\nYou rolled a", random.randint(1,4))
#6 sided
elif dice == "6":
print(dice, "sided dice chose.\nYou rolled a", (random.randint(1,6)))
#12 sided
elif dice == "12":
print(dice, "sided dice chose.\nYou rolled a", (random.randint(1,12)))
#Incorrect value entered
else:
#Informs the user that the number they have chosen is not a valid option.
print(dice, "is not a valid choice")
#Asks user if they want to use the program again.
print("Do you want to use the program again? Yes or No?")
#Links back to the start of the while loop.
repeat = input()
repeat = repeat.upper()
Your issue appears to be indentation. Since Python identifies code blocks using indentation, it's very important that you get this right.
I noticed your lines are indented as follows:
print("Do you want to use the program again? Yes or No?")
#Links back to the start of the while loop.
repeat = input()
repeat = repeat.upper()
Please try indenting them as follows, and it should work:
print("Do you want to use the program again? Yes or No?")
#Links back to the start of the while loop.
repeat = input()
repeat = repeat.upper()
Please look at the Lines and Indentation section here.
You may also have to remove the empty line after your while condition. But maybe not.
Hint: You won't have such problems when using whitespace-ignoring languages such as Java.

Categories

Resources