我正在尝试使用Python制作类骰子掷骰游戏。下面是我的代码。我无法弄清楚游戏的完成方式,即当选择“ N”时,我会无休止地重复最后的印刷品(也就是说,“我希望你喜欢玩骰子。祝你玩得开心!”)>
import random
import time
player = random.randint(1,6)
ai = random.randint(1,6)
cont = str(input('Roll the dice? Y/N'))
while cont == "Y":
print ("You are rolling...")
time.sleep(3)
print ("You rolled " + str(player))
print("The computer rolls...." )
time.sleep(3)
print ("The computer rolled " + str(ai))
if player > ai:
print("You win")
if ai > player:
print("You lose")
cont2 = str(input('Would you like to play again? Y/N'))
while cont != "Y" or cont2 != "Y":
break
print ("I hope you enjoyed playing dice. Have a great day!")
答案 0 :(得分:1)
在将下一个用户输入分配给cont2
的地方,您可以将其重新分配给cont
。如果用户按下“ N”,这将“打破” while循环。然后,您将不再需要第二个while循环。
编辑:如上所述,丹尼尔(Daniel)说,您的代码点总是给出相同的计算机骰子掷骰。 Yoy应该将ai
行更改为while循环内部。
import random
import time
player = random.randint(1,6)
# remove ai = random.randint(1,6) here
cont = str(input('Roll the dice? Y/N'))
while cont == "Y":
print ("You are rolling...")
time.sleep(3)
print ("You rolled " + str(player))
print("The computer rolls...." )
ai = random.randint(1,6) # <-- add here again
time.sleep(3)
print ("The computer rolled " + str(ai))
if player > ai:
print("You win")
if ai > player:
print("You lose")
cont = str(input('Would you like to play again? Y/N')) # <-- this line is changed
print ("I hope you enjoyed playing dice. Have a great day!")
您还可以通过在输入后添加.upper()
使其对于给定的用户输入更加健壮。因此:cont = str(input('Roll the dice? Y/N')).upper()
。如果用户然后输入“ y”而不是“ Y”,它将仍然有效。
答案 1 :(得分:0)
import random
import time
cont = str(input('Roll the dice? Y/N'))
while cont == "Y":
player = random.randint(1,6)
ai = random.randint(1,6)
print ("You are rolling...")
time.sleep(3)
print ("You rolled " + str(player))
print("The computer rolls...." )
time.sleep(3)
print ("The computer rolled " + str(ai))
if player > ai:
print("You win")
if ai > player:
print("You lose")
cont2 = str(input('Would you like to play again? Y/N'))
if cont2.lower() == 'y':
cont == "Y"
elif cont2.lower() == 'n':
cont == "N"
break
print ("I hope you enjoyed playing dice. Have a great day!"
为了使您的代码更健壮,我在while
循环中加入了滚动骰子值。其次,您可以使用while
摆脱第二个if--else
循环,使您的代码更具可读性和可理解性。