我正在尝试用python创建一个骰子游戏,其中一个规则是当分数低于零时会重置
我曾尝试在开始、结束和掷骰子脚本中设置分数重置检查,但它们总是允许分数低于零
#import all modules.
import math
import random
print("successfully imported modules.")
roundno=0
p1score=0
p2score=0
p1dicecomb=0
p2dicecomb=0
p1dice1=0
p1dice2=0
p2dice1=0
p2dice2=0 # assign values.
while roundno < 6:
if p2score < -1 or p2score == -1:
p2score = 0
if p1score < -1 or p1score == -1:
p1score = 0
print("round number is round", roundno) #new round always begins on player 1 turn.
print("player 1")
p1dice1 = random.randint(1,6)
p1dice2 = random.randint(1,6)# roll dice using cpu.
p1dicecomb = p1dice1+p1dice2
if p1dicecomb % 2 == 0:
p1score = p1score+10# compare the score to see if odd or even.
if p1dicecomb % 2 == 1:
p1score = p1score-5
print ("score is", p1score)
print("dice 1 is", p1dice1)
print("dice 2 is", p1dice2)
input("press enter to continue rolling dice.")
print ("player 2")
if p2score < -1 or p2score == -1:
p2score = 0
if p1score < -1 or p1score == -1:
p1score = 0
p2dice1 = random.randint(1,6)
p2dice2 = random.randint(1,6)# roll dice using cpu.
p2dicecomb = p2dice1+p2dice2
if p2dicecomb % 2 == 0:
p2score = p2score+10# compare the score to see if odd or even.
if p2dicecomb % 2 == 1:
p2score = p2score-5
print ("score is", p2score)
print("dice 1 is", p2dice1)
print("dice 2 is", p2dice2)
roundno = roundno+1
input("press enter to continue rolling dice.")
我希望当代码变为-5时,它应该将分数重置回零,但是它说分数是-5
设置分数后,您没有进行小于零的检查
为了测试,我添加了以下几行:
您将看到第一次打印
p2score
时,它是0。如果p2dicecomb
是奇数,那么p2score
变成0-5,即-5稍微重新排列代码,在减法后设置检查,例如:
(也可以导入
math
,但不要使用它!)这是操作顺序的问题:
所以,如果打印的分数有时是负片,这是正常的
以下是一个工作示例:
重新阅读代码后,我发现代码不正确
正确的代码是:
这为我解决了问题
相关问题 更多 >
编程相关推荐