Salted Fish
Salted Fish

Reputation: 3

How can I fix the code so Python will select the random number

I'm a Python beginning learner. Recently our school teacher asked us to do a project with following requirements:

  1. Randomly pick a number from 1-6 for two players.

  2. Each player starts with 100 points.

  3. Each player rolls one dice. The player with the lower roll loses the number of points shown on the higher dice.

  4. 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:

  1. One of the score keeps 100 all the time while the other one is kept changing until it is lower or equal to zero.

  2. 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

Answers (1)

ohyesyoucan
ohyesyoucan

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

Related Questions