Reputation: 3
I'm a Python beginning learner. Recently our school teacher asked us to do a project with following requirements:
Randomly pick a number from 1-6 for two players.
Each player starts with 100 points.
Each player rolls one dice. The player with the lower roll loses the number of points shown on the higher dice.
Play until one of the player's score is lower or equal to zero.
The run is Python 3.7.2, and here is the code:
import random
dice1 = random.randint(1,6)
dice2 = random.randint(1,6) #random number
player1 = 100
player2 = 100 #the initial marks for both players
While player1 > 0 or player2 > 0:
if dice1 > dice2: #when the player1 has the higher number
player2 = player2 - dice1
print("player1", player1, "player2", player2)
elif dice2 > dice1: #when the player 2 has the higher number
player1 = player1 - dice2
print("player1", player1, "player2", player2)
elif dice1 == dice2: #when two player get the same number
print("It's a tie.")
if player1 <= 0:
print("player2 win")
break
elif player2 <= 0:
print("player1 win")
break
I tried several times. When I run it, there were two problems:
One of the score keeps 100 all the time while the other one is kept changing until it is lower or equal to zero.
The result just keep coming up with "It's a tie."
I was confused with the result and had no idea how to fix it... Really appreciate any and all help! Thanks|ू・ω・` )
Upvotes: 0
Views: 127
Reputation: 178
Your code only rolls the dice (gets a random number set) once. Move the dice roll inside the while loop like so:
import random
player1 = 100
player2 = 100 #the initial marks for both players
while (player1 > 0 and player2 > 0):
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
if dice1 > dice2: #when the player1 has the higher number
player2 = player2 - dice1
print("player1", player1, "player2", player2)
elif dice2 > dice1: #when the player 2 has the higher number
player1 = player1 - dice2
print("player1", player1, "player2", player2)
elif dice1 == dice2: #when two player get the same number
print("It's a tie.")
if player1 <= 0:
print("player2 win")
break
elif player2 <= 0:
print("player1 win")
break
Upvotes: 1