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
Related
I am trying to assign value to the variables winsP1 and winsP2 by playing a random number game in my function 'determineWinner'. The values of winsP1 and winsP2 will be the number of times that each player wins the random number game.
The trouble I am running into is I am not able to pull the values from my function and use them outside of the function in my next block of code that tells me which player ultimately won the most rounds.
import random
answer = input("Play the game?")
winsP1 = 0
winsP2 = 0
def determineWinner(winsP1, winsP2):
from random import randint
player1 = randint(1,10)
player2 = randint(1,10)
#time.sleep(1)
print("Player 1:", player1)
#time.sleep(1)
print("Player 2:", player2)
#time.sleep(1)
if player1==player2:
print("This round is a tie!")
winsP1 + 1
winsP2 + 1
elif player1>player2:
winsP1 + 1
print("Player 1 wins this round!")
elif player2>player1:
print("Player 2 wins this round!")
winsP2 + 1
#time.sleep(1)
for i in range(10):
determineWinner(winsP1, winsP2)
if answer == "y" or answer == "Y" or answer == "yes" or answer == "Yes":
if winsP1>winsP2:
print()
print("The score totals are:")
print("Player one: " + str(winsP1))
print("Player two: " + str(winsP2))
print()
print("Player 1 wins with a score of", str(winsP1) + "!")
print()
elif winsP2>winsP1:
print()
print("The score totals are:")
print("Player One: " + str(winsP1))
print("Player two: " + str(winsP2))
print()
print("Player 2 wins with a score of", str(winsP2) + "!")
print()
elif winsP1==winsP2:
print()
print("The score totals are:")
print("Player one: " + str(winsP1))
print("Player two: " + str(winsP2))
print()
print("It's a tie!")
print()
Rather than iterating variables in place, consider using lists to collect results from determineWinner then subset to count by players:
from random import randint
answer = input("Play the game?")
def determineWinner():
player1 = randint(1,10)
player2 = randint(1,10)
print("Player 1:", player1)
print("Player 2:", player2)
if player1 == player2:
print("This round is a tie!")
result = 'T'
elif player1 > player2:
print("Player 1 wins this round!")
result = 'P1'
elif player2 > player1:
print("Player 2 wins this round!")
result = 'P2'
return result
# BUILD LIST OF RESULTS VIA LIST COMPREHENSION
results = [determineWinner() for i in range(10)]
# COUNT NUMBER OF ELEMENTS ACCORDING TO PLAYER
winsP1 = len([r for r in results if r in ("P1", "T")])
winsP2 = len([r for r in results if r in ("P2", "T")])
...
winsP1 = 0
winsP2 = 0
def determineWinner(anyName1, anyName2):
...
do stuff with anyName1 and anyName 2
...
return anyName1, anyName2
winsP1, winsP2 = determineWinner(anyName1=winsP1, anyName2=winsP2)
The return keyword gives you back any variables you want from the function. Notice that I have returned more than one value in this case. The function can give back multiple values which are stored in a tuple. You can then unpack them like I have using variables seperated by a comma. Note that the function is using a copy of the variables you gave it, and when you get the values back, you have to overwrite the variables outside of the function with the returned copies. You can also simply write
winsValues = determineWinner(winsP1, winsP2)
and then access them by writing
accessP1 = winValues[0]
accessP2 = winValues[1]
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
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
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.
I am trying to write a game where Player One picks a number and Player Two has 5 Guesses to guess it. If he manages to do so, he wins, if not, he losses and Player One wins.
So I have the code, but if for example Player one picks the number '3' and Player Two enters the number '3' on any of his goes, it still says Player One wins.
>>>
Player One enter you chosen number: 3
Player Two have a guess: 3
Player One wins.
>>>
This happens also:
>>>
Player One enter you chosen number: 5
Player Two wins.
Also, player two can have as many turns as he likes, but it should only be 5. If he passes that amount, Player One automatically wins. Here is my code: (I don't know here I went wrong.)
def Game():
Guess = 0
NumberOfGuesses = 0
NumberToGuess = int(input("Player One enter you chosen number: "))
while NumberToGuess < 1 or NumberToGuess > 10:
NumberToGuess = int(input("Not a valid choice, please enter another number: "))
while Guess != NumberToGuess and NumberOfGuesses < 5:
Guess = int(input("Player Two have a guess: "))
NumberOfGuesses = NumberOfGuesses + 1
if Guess == NumberToGuess:
print("Player One wins.")
else:
print("Player Two wins.")
Game()
Your if statement is the wrong way around.
Instead of
if Guess == NumberToGuess:
print("Player One wins.")
else:
print("Player Two wins.")
it should be
if Guess == NumberToGuess:
print("Player Two wins.")
else:
print("Player One wins.")
because player 2 wins if he guesses the number that player 1 has chosen (NumberToGuess).
I cannot reconstruct your second problem where player 2 wins immediately of player 1 enters 5. It works fine for me.
The logic is wrong. If the input is not equal to NumberToGuess then you cannot print Player Two wins.
You must then loop. Then outside the loop check if player one was successful.
while Guess != NumberToGuess and NumberOfGuesses < 5:
Guess = int(input("Player Two have a guess: "))
NumberOfGuesses = NumberOfGuesses + 1
if Guess == NumberToGuess:
print("Player Two wins.")
if Guess != NumberToGuess:
print("Player One wins.")
"""This game generates random number, then players try to guess the number generated"""
import random
#generate number directly
num = random.randrange(1,5)
#initialize global variables
player1 = "Human"
player2 = "Alien"
player = ""
player1PlayCount = 0
player2PlayCount = 0
maxPlayTimes = 3
#game logic
def Game():
global player1, player2, player, player1PlayCount, player2PlayCount, maxPlayTimes, num
"""enter and assign names to players"""
player1Name = input('Player1 Enter Your Name: ')
player2Name = input('Player2 Enter Your Name: ')
player1 = player1Name
player2 = player2Name
player = player1
print(player1, 'turn')
while ((player1PlayCount and player2PlayCount) != maxPlayTimes):
guessNum = int(input("Guess Number: "))
if guessNum == num:
print(player, "won")
exit()
elif player == player1:
player1PlayCount +=1
player = player2
print(player2, 'turn')
elif player == player2:
player2PlayCount +=1
player = player1
print(player1, 'turn')
else:
print("Both ", player1, " and ", player2, " lose")
exit()
Game()