This is the function in my blackjack python program for determining the winner of a round. The counts playerScore and dealerScore are supposed to increment with each win, but when running the game multiple times they never increase past 1. I think I need another loop or function to deal with this, but how can I properly increment the wins with multiple plays?
def total(self, dealer):
# determines winner
playerScore=0
dealerScore=0
if self.hand_sum > dealer.hand_sum:
print("\nYou won the hand!")
playerScore+=1
elif self.hand_sum < dealer.hand_sum:
if dealer.hand_sum <= 21:
print("\nYou lost the hand!")
dealerScore+=1
else:
print("\nDealer busted\n")
else:
print("\nYou tied\n")
print("Dealer's hand:", dealer.cards, " Dealer's sum:", dealer.hand_sum)
print("Your hand:", self.cards, "Your sum:", self.hand_sum)
print("\n*******************\n")
print("Number of Wins:\n")
print("Player: %d")%playerScore
print("Dealer: %d")%dealerScore
print("\n*******************\n")
start()
Every time you run the total function, you reset the scores to 0. If you did that at the start of the application instead your counts wouldn't get reset. Best I can say with only this part of the code available.
Related
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.
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.
So I am making a python file that creates a dice game. It holds 5 rounds for the 2 players and accumulates their scores at the end of each round. When the round ends their final scores are printed and the winner declared. I am having trouble when trying to make a bonus roll if the scores are tied, which will repeat until one player wins. I've set a variable player1F and player2F. I have used the if function to print who is the winner depending on who scores higher.
if overallp1==overallp2:
roll=random.randint(1,6)
player1F=(roll)
if player1F>player2F:
print(player1 + ' IS THE WINNER ')
elif player1F<player2F:
print(player2 + ' IS THE WINNER ')
Every time I run the program an error occurs saying that the player1F variable is not defined. Player1F is meant to exclusively be the total for the final round, so just the one score determines the win if there is a tie. However it is saying that it is not defined
If I understand your question, here is a way to accomplish what you want:
if overallp1==overallp2:
player1F = 0
player2F = 0
while player1F == player2F:
player1F=random.randint(1,6)
player2F=random.randint(1,6)
if player1F>player2F:
print(player1 + ' IS THE WINNER ')
elif player1F<player2F:
print(player2 + ' IS THE WINNER ')
Also, the final elif can be just else, since there are no other possibilities at that point.
I'm new to python and I'm trying to make the guess my number game with a limit of only 5 guesses, everything I've tried so far has failed. how can I do it?, I forgot to mention that I wanted the program to display a message when the player uses all their guesses.The code below only prints the "You guessed it" part after the 5 guesses whether they guess it or not.
import random
print ("welcome to the guess my number hardcore edition ")
print ("In this program you only get 5 guesses\n")
print ("good luck")
the_number = random.randint(1, 100)
user = int(input("What's the number?"))
count = 1
while user != the_number:
if user > the_number:
print ("Lower")
elif user < the_number:
print ("Higher")
user = int(input("What's the number?"))
count += 1
if count == 5:
break
print("You guessed it!!, the number is", the_number, "and it only"\
" took you", count , "tries")
input ("\nPress enter to exit")
Your edit says you want to differentiate between whether the loop ended because the user guessed right, or because they ran out of guesses. This amounts to detecting whether you exited the while loop because its condition tested false (they guessed the number), or because you hit a break (which you do if they run out of guesses). You can do that using the else: clause on a loop, which triggers after the loop ends if and only if you didn't hit a break. You can print something only in the case you do break by putting the print logic right before the break, in the same conditional. That gives you this:
while user != the_number:
...
if count == 5:
print("You ran out of guesses")
break
else:
print("You guessed it!!, the number is", the_number, "and it only"\
" took you", count , "tries")
However, this puts code for different things all over the place. It would be better to group the logic for "guessed right" with the logic for warmer/colder, rather than interleaving them with part of the logic for how many guesses. You can do this by swapping where you test for things - put the 'is it right' logic in the same if as the warmer/colder, and put the number of guesses logic in the loop condition (which is then better expressed as a for loop). So you have:
for count in range(5):
user = int(input("What's the number?"))
if user > the_number:
print("Lower")
elif user < the_number:
print("Higher")
else:
print("You guessed it!!, the number is", the_number, "and it only"\
" took you", count , "tries")
break
else:
print("You ran out of guesses")
You have two options: you can either break out of the loop once the counter reaches a certain amount or use or a for loop. The first option is simplest given your code:
count = 0
while user != the_number:
if user > the_number:
print ("Lower")
elif user < the_number:
print ("Higher")
user = int(input("What's the number?"))
count += 1
if count == 5: # change this number to change the number of guesses
break # exit this loop when the above condition is met
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?