未添加Python变量值
我是python的初学者,我正在创建一个简单的游戏,在这个游戏中,您可以掷骰子并移动一些随机数目的空格。当我这样做时,变量“position”的值会改变,但当它达到30时,程序仍会继续。有什么解决办法吗未添加Python变量值,python,Python,我是python的初学者,我正在创建一个简单的游戏,在这个游戏中,您可以掷骰子并移动一些随机数目的空格。当我这样做时,变量“position”的值会改变,但当它达到30时,程序仍会继续。有什么解决办法吗 again = True position = 1 while again: move_numb = 0 number = random.randint(1, 6) roll = input("> ") if roll == "
again = True
position = 1
while again:
move_numb = 0
number = random.randint(1, 6)
roll = input("> ")
if roll == "roll":
print("you moved " + str(number) + " spaces")
position += number
print("You are currently on " + "tile " + str(position))
move_numb += 1
**if position == 30:
print("You Win")
print("You reached here in " + str(move_numb) + " moves")
break
else:
continue**
如果位置>=30,则必须通过执行
if position>=30来验证是否超过30
使用此代码:
again = True
position = 1
move_numb = 0
while again:
number = random.randint(1, 6)
roll = input("> ")
if roll == "roll":
print("you moved " + str(number) + " spaces")
position += number
print("You are currently on " + "tile " + str(position))
move_numb += 1
if position >= 30:
print("You Win")
print("You reached here in " + str(move_numb) + " moves")
again = False
首先,您的想法是在瓷砖为30或瓷砖穿过30时停止
如果正好是30,那么您的代码运行良好
如果是tile number>30,则代码中的一个小更改应该是
position>=30
您正在将一个随机数添加到位置
,但您只检查是否命中30,而不是是否超过了30。假设如果位置>=30:
如果位置>=30:
?但我提出了另一个问题。移动次数始终保持为1,这是因为您在while循环中重新初始化了它
,这就是为什么,您可以在我的回答中看到,我初始化了变量move\u numb
,使其超出while范围