Adding a win and loss total - python

I have to create a program for one of my classes that will follow the basic rules of the game "Craps". This involves getting two random dice rolls and checking if the total shows for a win, a loss, or a reroll until a win or loss. That part isn't the issue at hand though. Where I am stuck is introducing a win/loss counter for these rolls. If someone could please guide me on implementing this into my code, or revising the code so it is possible to do so.
#Imports
import random
#Variable declaration
D1 = 0
D2 = 0
DTotal = 0
WinningValues = [7,11]
LosingValues = [2,3,12]
WinTotal = 0
LoseTotal = 0
def gameloop():
D1 = random.randint(1,6)
D2 = random.randint(1,6)
DTotal = D1 + D2
print("You rolled", D1, "and", D2,"for a total of", DTotal)
if DTotal in WinningValues:
print("You win")
Cont = input("Type Y to roll again, X to quit, or S to see your stats: ")
craps(Cont)
elif DTotal in LosingValues:
print("You lose")
Cont = input("Type Y to roll again, X to quit, or S to see your stats: ")
craps(Cont)
else:
print("You roll again")
craps(Cont="Y")
def showstats(WinTotal, LoseTotal):
print("You won a total of",WinTotal,"and lost a total of",LoseTotal,"times.")
def craps(Cont):
if Cont == "Y":
gameloop()
if Cont == "S":
print("Executing")
showstats(WinTotal, LoseTotal)
if Cont == "X":
quit()
#Program running
Cont = input("Would you like to play a game of craps? Type Y to play or X to quit: ")
if Cont == 'Y':
gameloop()
elif Cont == 'X':
quit()
I have tried implementing WinTotal += 1 after print("You win") but it comes back with a local variable referenced before assignment error that I have tried debugging but just haven't had any luck with it, let alone understanding it.

some cases not added like..
if someone pressed wrong key but he/she wanted to play again.
Code:-
import random
win,lose=0,0
asking=input("Would you like to play a game of craps? Type Y to play or any other key to quit: ")
while asking=="Y":
WinningValues = [7,11]
LosingValues = [2,3,12]
while True:
D1 = random.randint(1,6)
D2 = random.randint(1,6)
total=D1+D2
print("You rolled", D1, "and", D2,"for a total of", total)
if total in WinningValues:
print("You win")
win+=1
break
elif total in LosingValues:
print("You lose")
lose+=1
break
else:
print("You roll again")
asking=input("Type Y to roll again, S to see your stats, or any other key to exit: ")
if asking=="S":
print("You won a total of",win,"and lost a total of",lose,"times.")
asking=input("Type Y to roll again or any other key to quit: ")
if win or lose:
print("Your Stats are: ")
print("Win: "+str(win))
print("Lose: "+str(lose))
else:
print("You have not played any game")
Output:-
#Testcase1 When user not played any game..!
Would you like to play a game of craps? Type Y to play or any other key to quit: A
You have not played any game
#Testcase2 User played and wanted to know stats of his/her game and when exit also see his/her stats.
Would you like to play a game of craps? Type Y to play or any other key to quit: Y
You rolled 4 and 3 for a total of 7
You win
Type Y to roll again, S to see your stats, or any other key to exit: Y
You rolled 5 and 5 for a total of 10
You roll again
You rolled 6 and 4 for a total of 10
You roll again
You rolled 3 and 3 for a total of 6
You roll again
You rolled 1 and 4 for a total of 5
You roll again
You rolled 5 and 3 for a total of 8
You roll again
You rolled 1 and 2 for a total of 3
You lose
Type Y to roll again, S to see your stats, or any other key to exit: Y
You rolled 2 and 6 for a total of 8
You roll again
You rolled 6 and 4 for a total of 10
You roll again
You rolled 4 and 1 for a total of 5
You roll again
You rolled 1 and 1 for a total of 2
You lose
Type Y to roll again, S to see your stats, or any other key to exit: S
You won a total of 1 and lost a total of 2 times.
Type Y to roll again or any other key to quit: A
Your Stats are:
Win: 1
Lose: 2

Related

Adding betting function to dice game and number guess game

I have made a dice roll game on Python 3 but want to add a betting function.
I have tried a few things but I can only play one game. I want the game to have multiple rounds.
How do I make it a game where the player(s) can bet on multiple rounds until money ends at 0, or possibly keep playing until they want to stop?
import random
import time
print("this is a dice roll game")
def main():
player1 = 0
player1wins = 0
player2 = 0
player2wins = 0
rounds = 1
while rounds != 5:
print("Round" + str(rounds))
time.sleep(1)
player1 = dice_roll()
player2 = dice_roll()
print("Player 1 rolled " + str(player1))
time.sleep(1)
print("Player 2 rolled " + str(player2))
time.sleep(1)
if player1 == player2:
print("The round is a draw")
elif player1 > player2:
player1wins += 1
print("Player 1 wins the round")
else:
player2wins += 1
print("Player 2 wins the round")
rounds = rounds + 1
if player1wins == player2wins:
print("The game ended in a draw")
elif player1wins > player2wins:
print("Player 1 wins the game, Rounds won: " + str(player1wins))
else:
print("Player 2 wins the game, Rounds won: " + str(player2wins))
def dice_roll():
diceroll = random.randint(1,6)
return diceroll
main()
Adding to the comment by John Coleman, you can modify your while loop so that it does not end when the number of rounds is different to 5, something like:
while True:
// Rest of code...
if moneyP1 <= 0 OR moneyP2 <=0:
print("Someone ran out of money")
// Implement deciding who won
break
user_confirmation = raw_input("Keep playing? (YES/NO): ")
if user_confirmation == "NO":
break

How can I repeat the two defined functions 5 times? Python

I need to have both defined programs repeat 5 times
Here is my success criteria:
The program will allow each player to roll two 6-sided dice
The program will calculate and output the points each round for a players total score
The program will allow the players to play 5 rounds
The program will allow each player to roll 1 die each until someone wins if both players have the same score after 5 rounds
The program will output who has won at the of the 5 rounds
The program will let the player roll an extra die and get the number of points rolled added to their score if they roll a double
The program will not allow the score to go below 0 at any point
import random
def player_one():
global score1
print("Player One is up first")
roll = str(input("Please enter ROLL to roll the dice >")).upper()
num1 = random.randint(1,6)
num2 = random.randint(1,6)
if roll == "ROLL":
showscore1 = print("You rolled a",num1,"and a",num2)
else:
exit()
score1 = num1 + num2
if (score1 % 2) == 0:
score1 = score1 + 10
else:
score1 = score1 - 5
if score1 < 0:
score1 = 0
else:
score1 = score1
print("Your score was",score1)
return score1
player_one()
import time
time.sleep(3)
def player_two():
global score2
print("Player Two is up first")
roll = str(input("Please enter ROLL to roll the dice >")).upper()
num1 = random.randint(1,6)
num2 = random.randint(1,6)
if roll == "ROLL":
showscore1 = print("You rolled a",num1,"and a",num2)
else:
exit()
score2 = num1 + num2
if (score2 % 2) == 0:
score2 = score2 + 10
else:
score2 = score2 - 5
if score2 < 0:
score2 = 0
else:
score2 = score2
print("Your score was",score2)
return score2
player_two()
time.sleep(2)
if score1 > score2:
print("Player One has won the game!")
else:
print("Player Two has won the game!")
Not needed but if you could add some more of my success criteria to my program would be helpful, but for now I'm really looking for the loop. Thanks
The additional success criteria would be:
The program will allow each player to roll 1 die each until someone wins if both players have the same score after 5 rounds
The program will output who has won at the of the 5 rounds
The program will let the player roll an extra die and get the number of points rolled added to their score if they roll a double
If you use
for x in range(0,5):
function()
the function will be run 5 times. Also, using global is bad practice. You should return the values from the function and assign them to variables. I recently did this same challenge, and this is my solution: https://pastebin.com/Zc1nj0Mi

Python - How do you exit a program if a condition is met?

I can't exit the program when the condition at start of the code is met and it also prevents the rest of the code from working when it is not met. However if you remove the conditions from the start the code works fine. How do I get the conditions at the start to work properly? P.S I know the code can be condensed.
import sys
user1 = (input("User 1 type your name " )).lower
user2 = (input("User 2 type your name ")).lower
if user1 != "bob":
sys.exit()
if user2 != "fred":
sys.exit()
from random import randint
total = 1
score1 = 0
score2 = 0
while total <6:
roll = (input("User 1 x press 1 to roll the dice "))
if roll == "x":
dice = randint(1,6)
print("You got",dice)
score1 = score1+dice
print("User 1 your score is",score1)
roll2 = (input("\nUser 2 press x to roll the dice "))
if roll2 == "x":
dice = randint(1,6)
print("You got",dice)
score2 = score2+dice
print("User 2 your score is",score2)
total = total+1
if total == 6:
print("\nUser1 your total score is",score1)
print("User2 your total score is",score2)
while total >= 6:
if score1 == score2:
print("It's a tie! Whoever rolls the highest number wins")
roll = (input("User 1 press x to roll the dice"))
if roll == "x":
dice = randint(1,6)
print("You got",dice)
score1 = score1+dice
print("User 1 your score is",score1)
roll2 = (input("\nUser 2 press x to roll the dice"))
if roll2 == "x":
dice = randint(1,6)
print("You got",dice)
score2 = score2+dice
print("User 2 your score is",score2)
if score1 > score2:
print("\nUser 1 wins")
break
if score1 < score2:
print("\nUser 2 wins")
break
lower is actually a method, and you have to call it. Instead of writing .lower try writing .lower()

How do I make this program more detailed and tell me the winning percentages after I played it?

So far, this craps game works in python but I need to add the winning percentage after you played it. Plus, how do I make it where the players response has to be "yes" or "no" in order to run? It will run no matter what. And is there way to replace "break" in this program?
import random
first_roll = 0
def play():
yesOrno = str(input('Would you like to play? '))
yesOrno = yesOrno[0].lower()
while yesOrno == 'y':
throw_1 = random.randint(1,6)
throw_2 = random.randint(1,6)
total = throw_1 + throw_2
if total == (2,12):
yesOrno = str(input('You lost! Would you like to play again?'))
yesOrno = yesOrno[0].lower()
elif total == (7,11):
yesOrno == str(input('You won! Would you like to play again?'))
yesOrno = yesOrno[0].lower()
else:
first_roll == total
while yesOrno == 'y':
throw_1 = random.randint(1,6)
throw_2 = random.randint(1,6)
finalRoll = throw_1 + throw_2
print('You rolled a',total)
if total == 2 or 3 or 7 or 11 or 12:
yesOrno = str(input('You lost! Would you like to play again?'))
yesOrno = yesOrno[0].lower()
break
elif total == first_roll:
yesOrno = str(input('You won! Would you like to play again?'))
yesOrno = yesOrno[0].lower()
break
else:
yesOrno == 'y'
print('Thanks for playing!')
play()
I fixed and streamlined some of your code. I created 2 helpers for repetetive tasks:
import random
def askPlayAgain(text=""):
"""Ask for y or n, loop until given. Maybe add 'text' before the message."""
t = ""
while t not in {"y","n"}:
t = input("\n" + text + 'Would you like to play? [y/n]').strip()[0].lower()
return t
def getSumDices(n=2,sides=6):
"""Get sum of 'n' random dices with 'sides' sides"""
return sum(random.choices(range(1,sides+1),k=n)) # range(1,7) = 1,2,3,4,5,6
and modified the play logic slightly:
def play():
first_roll = 0
win = 0
lost = 0
yesOrno = askPlayAgain()
while yesOrno == 'y':
# dont need the individual dices - just the sum
# you can get both rolls at once
total = getSumDices()
print('You rolled a', total)
if total in {2,12}:
lost += 1
yesOrno = askPlayAgain("You lost! ")
elif total in {7,11}:
win += 1
yesOrno == askPlayAgain("You won! ")
else:
# remember last rounds result
first_roll = total
while True:
total = getSumDices()
print('You rolled a', total)
# this is kinda unfair, if you had 3 in your first round
# you cant win the second round at all ...
if total in {2,3,7,11,12}:
lost += 1
yesOrno = askPlayAgain("You lost! ")
break
elif total == first_roll:
win += 1
yesOrno = askPlayAgain("You won! ")
break
print('Thanks for playing!')
print('{} wins vs {} lost'.format(win,lost))
play()
Output:
Would you like to play? [y/n]y
You rolled a 10
You rolled a 12
You lost! Would you like to play? [y/n]y
You rolled a 9
You rolled a 7
You lost! Would you like to play? [y/n]y
You rolled a 7
You won! Would you like to play? [y/n]y
You rolled a 6
You rolled a 10
You rolled a 3
You lost! Would you like to play? [y/n]y
You rolled a 8
You rolled a 9
You rolled a 11
You lost! Would you like to play? [y/n]n
Thanks for playing!
1 wins vs 4 lost

Dice-rolling game doesn't change results

Doing a dice Rolling game in python, and whenever I start my second round I still end up getting the same dice results from the previous round.
import random
import time
#gets the dice side
def roll_dice(sides):
dice_results = list()
for side in sides:
roll_result = random.randint(1,side+1)
dice_results.append(roll_result)
return dice_results
#pulls a dice out from the list
def dice_fell(roll_result):
player1_dice = player1_dice_results
player2_dice = player2_dice_results
for item in player1_dice:
if item % 4 == 0:
player1_dice.remove(item)
return player1_dice
for item in player2_dice:
if item % 4 == 0:
player2_dice.remove(item)
return player2_dice
# variables
dice_set1=[4, 6, 8, 10, 12, 20, 100]
dice_set2=[4, 6, 8, 10, 12, 20, 100]
player1_dice_results = roll_dice(dice_set1)
player2_dice_results = roll_dice(dice_set2)
player1_final_results = dice_fell(player1_dice_results)
player2_final_results = dice_fell(player2_dice_results)
player1_total= sum(player1_dice_results)
player2_total= sum(player2_dice_results)
player1_score = 0
player2_score = 0
while player1_score < 3 or player2_score < 3:
# This part just announces what happens
exit= input(str("Press Enter to start! Press 'q' to leave after each round! \n"))
if exit != "q":
print("Let's begin! Be careful for the small table!")
elif exit == "q":
quit()
print("You are rolling...")
time.sleep(2)
print("You have rolled: ",player1_final_results)
if len(player1_final_results) < 7:
print("Sorry player 1, some of your dice have fallen off the table!")
print()
print("Your total is: ",player1_total)
print()
print("Player 2 is rolling...")
time.sleep(2)
print("Player 2 has rolled:" ,player2_final_results)
if len(player2_final_results) < 7:
print("Sorry player 2, some of your dice have fallen off the table!")
print()
print("Player 2's total is: ",player2_total)
print()
if player1_total > player2_total:
print()
print("You have won the round with,",player1_total,"!"),
player1_score += 1
print("Your score is: ",player1_score)
elif player2_total > player1_total:
print()
print("Player 2 has won the round with,",player2_total,"!"),
player2_score += 1
print("Player 2's score is: ",player2_score)
if player1_score == 3:
print("Congratulations, you won!")
elif player2_score == 3:
print("Player 2 wins! Better luck next time champ!")
I believe that I've fixed the indentation problems.
I have reproduced the problem.
As Kevin said, your immediate problem is that you roll the dice only once, before you enter your while loop. Here's what it looks like with the rolls inside the loop, but after the player decides whether to continue.
dice_set1=[4,6,8,10,12,20,100]
dice_set2=[4,6,8,10,12,20,100]
player1_score = 0
player2_score = 0
while player1_score < 3 or player2_score < 3:
# This part just announces what happens
exit = raw_input(str("Press Enter to start! Press 'q' to leave after each round! \n"))
if exit != "q":
print("Let's begin! Be careful for the small table!")
elif exit == "q":
quit()
player1_dice_results = roll_dice(dice_set1)
player2_dice_results = roll_dice(dice_set2)
player1_final_results = dice_fell(player1_dice_results)
player2_final_results = dice_fell(player2_dice_results)
player1_total= sum(player1_dice_results)
player2_total= sum(player2_dice_results)
print("You are rolling...")
... # remainder of code omitted
That said, do note that you have several other problems with the program. You won't terminate until both players have won three times -- use and instead of or in the while condition.
Most of my other comments are more appropriate for the codeReview group; you might post there when you're done debugging.

Categories

Resources