python - 如何修复代码以便 Python 选择随机数
问题描述
我是一名 Python 初学者。最近我们学校老师让我们做一个项目,要求如下:
随机从 1-6 中为两名玩家选择一个数字。
每个玩家以 100 分开始。
每个玩家掷一个骰子。掷骰较低的玩家失去较高骰子上显示的点数。
玩直到其中一名玩家的分数低于或等于零。
运行的是 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
我试了几次。当我运行它时,有两个问题:
其中一个分数一直保持 100,而另一个分数一直在变化,直到它低于或等于零。
结果只是不断出现“这是平局”。
我对结果感到困惑,不知道如何解决它......非常感谢任何和所有的帮助!谢谢|ू・ω・`)
解决方案
您的代码只掷一次骰子(获得一个随机数集)。在 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
推荐阅读
- html - 为什么在我的 html 头标签中添加 google 字体链接后我的网页会抖动?
- owl-carousel - 为什么猫头鹰轮播不喜欢doctype?
- package - 重新定义已删除的包(Common Lisp)
- swift - SwiftUI 崩溃预览中具有资产目录颜色的颜色扩展
- python - 无法使用函数测试 Pandas 数据框中的 NaT
- python - 如何使用python将下一个文本存储在电报机器人中
- swift - 在 SWIFT 中分解字符串
- apache-spark - 结构化流 CoarseGrainedExecutorBackend:驱动程序命令关闭
- kubernetes - DNS 查找在 Kubernetes 集群中无法正常工作
- jsonschema - JSON模式递归似乎没有正确验证