Advertisements
The code below ends after a player has reached a value of 20. What I tried to code (but failed) was that if a player (say player 1) reaches 20 it stops that player’s part of code and keeps the other player’s (player 2) code running until he reaches 20 aswell and then displays who reached 20 first.
import random
player1 = 0
rollnum_player1 = 0
player2 = 0
rollnum_player2 = 0
def die():
roll = random.randint(1,6)
return roll
while True:
# Player 1 code
player1 += die()
print("Player 1 roll:",player1)
rollnum_player1 += 1
if player1 >= 20:
print("Congratulations player 1 you have won!")
break
# Player 2 code
player2 += die()
print(player2)
rollnum_player2 += 1
if player2 >= 20:
print("Congratulations player 2 you have won!")
break
>Solution :
Instead of breaking when a player wins, use if
statements to skip over the code for the player who has already won. Break out of the loop when both have reached 20.
while player1 < 20 or player2 < 20:
if player1 < 20:
# Player 1 code
player1 += die()
print("Player 1 roll:",player1)
rollnum_player1 += 1
if player2 < 20:
# Player 2 code
player2 += die()
print("Player 2 roll:",player2)
rollnum_player2 += 1
if rollnum_player1 < rollnum_player2:
print("Congratulations player 1 you have won!")
elif rollnum_player2 < rollnum_player1:
print("Congratulations player 2 you have won!")
else:
print("It's a tie!")