如何修复代码,以便Python选择随机数

时间:2019-05-30 01:44:51

标签: python

我是Python的初学者。最近,我们的学校老师要求我们做一个符合以下要求的项目:

  1. 从1-6中随机选择两位玩家。

  2. 每个玩家都以100点开始。

  3. 每个玩家掷出一个骰子。掷骰较低的玩家会失去骰子较高的点数。

  4. 播放,直到玩家的得分之一低于或等于零为止。

运行的是Python 3.7.2,下面是代码:

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

我尝试了几次。当我运行它时,有两个问题:

  1. 其中一个得分一直保持100分,而另一个得分一直保持变化,直到其低于或等于零。

  2. 结果总是显示“这是一条领带。”

我对结果感到困惑,不知道如何解决... 非常感谢任何帮助!谢谢|ू・ω・`)

1 个答案:

答案 0 :(得分:1)

您的代码只会掷骰子一次(获得一个随机数集)。 将骰子卷移动到while循环内,如下所示:

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