我正在尝试用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!")
发布于 2018-12-24 18:52:00
在将下一个用户输入赋值给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”,它仍然可以工作。
发布于 2018-12-24 19:02:36
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循环中包含了掷出的骰子值。其次,可以用if--else去掉第二个while循环,使代码更易读、更容易理解。
https://stackoverflow.com/questions/53912266
复制相似问题