[英]Loop to ask user to go again
我有一個簡單的程序,可以運行擲骰子游戲。 擲骰子游戲的所有邏輯都在playOnce()方法中。 我需要使用main()方法來調用playOnce()方法,以便通過輸入yes或no來確定用戶是否要再次播放。 我需要不斷詢問用戶是否要在每個回合之后玩。 我在執行詢問用戶的邏輯時遇到麻煩。 我已經嘗試過使用while循環,但是到目前為止沒有任何輸出。 這是一個示例: http : //tinypic.com/r/2las1v/8
import random
def playOnce():
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
roll = dice1 + dice2
print("You rolled", dice1, "+", dice2, "=", roll)
print()
if roll == 2 or roll == 3 or roll == 12:
print("You lose!")
elif roll == 7 or roll == 11:
print("You win!")
else:
print("Point is", roll)
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
roll2 = dice1 + dice2
print("You rolled ",roll2)
while roll2 != 7:
if roll == roll2:
print("You win!")
break
else:
print("Point is ", roll)
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
roll2 = dice1 + dice2
print("You rolled ",roll2)
if roll2 == 7:
print("You lose!")
def main():
playOnce()
print("Would you like to go again?")
main()
怎么樣:
def main():
keep_playing = True
while keep_playing:
playOnce()
ans = raw_input("Would you like to go again?")
if ans != 'y':
keep_playing = False
您可以使用此:
import random
def playOnce():
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
roll = dice1 + dice2
print("You rolled", dice1, "+", dice2, "=", roll)
print()
if roll == 2 or roll == 3 or roll == 12:
print("You lose!")
elif roll == 7 or roll == 11:
print("You win!")
else:
print("Point is", roll)
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
roll2 = dice1 + dice2
print("You rolled ",roll2)
while roll2 != 7:
if roll == roll2:
print("You win!")
break
else:
print("Point is ", roll)
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
roll2 = dice1 + dice2
print("You rolled ",roll2)
if roll2 == 7:
print("You lose!")
def main():
playOnce()
#print("Would you like to go again?")
flag = input("Would you like to go again?")
#flag = True
while flag:
playOnce()
flag = input("Would you like to go again?")
main()
然后您需要回答True或False或1或0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.