[英]Dice Roll input for 2 players
我有一个掷两个骰子的代码,对于每个键入“ roll”来掷骰子的玩家。 但是,如果他们没有正确输入“ roll”,则代码将无法正常工作,并且不会一遍又一遍地要求用户再次/正确输入“ roll”,而是会遍历代码,而不验证他们的输入。
该代码应该要求玩家1将他们的第一个骰子掷出第一回合,然后移至玩家2的两个骰子进行第一回合,然后移至第二轮,直到两个玩家经过5轮,如果他们输入错误,它只是要求正确的输入,直到正确为止。
import random
tot1 = 0
tot2 = 0
tot2 = 0
rnd2 = 0
for i in range (1,6):
while True:
from random import randint
print()
print("Player 1")
ro1_1 = input("Type 'roll' to roll your 1st dice: ")
if ro1_1 == 'roll':
dice1_1 = (randint(1,6))
print("Player1 dice 1:", dice1_1)
else:
ro1_1 = input("Type 'roll' to roll your 1st dice: ")
ro1_2 = input("Type 'roll' to roll your 2nd dice: ")
if ro1_2 == "roll":
dice1_2 = (randint(1,6))
print("Player1 Dice 2:", dice1_2)
else:
ro1_2 = input("Type 'roll' to roll your 1st dice: ")
print()
print ("Player1's total for round",(rnd1)," is:",tot1)
print()
print ("Player 2")
ro2_1 = input("Type 'roll' to roll your 1st dice: ")
if ro2_1 == 'roll':
dice2_1 = (randint(1,6))
print("Player2 Dice 1:", dice2_1)
else:
ro1_1 = input("Type 'roll' to roll your 1st dice: ")
ro2_2 = input("Type 'roll' to roll your 2nd dice: ")
if ro2_2 == 'roll':
dice2_2 = (randint(1,6))
print("Player2 Dice 2:", dice2_2)
else:
ro2_2 = input("Type 'roll' to roll your 1st dice: ")
break
print()
print ("Player2's total for round",(rnd2)," is:",tot2)
print()
break
首先, from random import randint
移到顶部-至少在while
循环之外。 这不会解决问题,而只是说。
接下来,您要停止播放,直到播放器键入“ roll”为止。 在几个地方。
编写一个函数:
def wait_for_right_input():
while True:
if input("Type 'roll' to roll your 1st dice: ") == 'roll':
break
您现在可以在需要的地方调用它:
from random import randint
for i in range (1,6):
#while True: ## not sure why you have both, and this would make the indents wrong
print()
print("Player 1")
wait_for_right_input() #<-- here
dice1_1 = randint(1,6)
print("Player1 dice 1:", dice1_1)
wait_for_right_input() #<-- here
dice1_2 = randint(1,6)
print("Player1 Dice 2:", dice1_2)
# etc
如果您想循环直到输入无效(我假设while True
并break
的原因),则可以更改该函数以返回一个布尔值,指示是否继续。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.