首页 > 解决方案 > 如何修复代码以便 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. 结果只是不断出现“这是平局”。

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

标签: python

解决方案


您的代码只掷一次骰子(获得一个随机数集)。在 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

推荐阅读