2017-08-13 227 views
0

我想在PYTHON中做一個小型的隨機猜測遊戲,但它在用戶播放後很好地工作,我希望它恢復到開始狀態並允許用戶在輸入「y」時再次播放。所以它會回到代碼的頂部。我瞭解它的一個循環,但我不知道如何使其工作。 任何幫助,非常感謝!隨機猜測遊戲

import random 



bet = input("How much would you like to bet?") 
print ("You are betting €",bet,) 

win = int(bet) * int(2) 

print('Pick either 1 or 0') 
number = random.randint(0,1) 
guess = 0 
while number < 2: 

    guess_number = int(input('Enter a number:')) 


    if guess_number == number: 
     print('Your guess is correct the number is',number) 
     print("you have won €",win,) 
     break 
    if guess_number >=2: 
     print ("Number too high") 
    else: 
     print("you are wrong, you have lost €",bet,) 
     break 

play_again = input("Play Again? y/n") 
y = bet 
n = print("bye") 
if play_again == y: 
    bet 

回答

1

將整個代碼(除了import random)在while循環。

while True: 
    bet = input("How much would you like to bet?") 
    print ("You are betting €",bet,) 

    win = int(bet) * int(2) 

    print('Pick either 1 or 0') 
    number = random.randint(0,1) 
    guess = 0 
    while number < 2: 

     guess_number = int(input('Enter a number:')) 


     if guess_number == number: 
      print('Your guess is correct the number is',number) 
      print("you have won €",win,) 
      break 
     if guess_number >=2: 
      print ("Number too high") 
     else: 
      print("you are wrong, you have lost €",bet,) 
      break 

    play_again = input("Play Again? y/n") 
    if play_again.lower() == "y": 
     continue 
    else: 
     break 
0

你也可以把你的代碼的函數像這樣:

import random 

def game(): 
    bet = input("How much would you like to bet?") 
    print ("You are betting €",bet,) 

    win = int(bet) * int(2) 

    print('Pick either 1 or 0') 
    number = random.randint(0,1) 
    guess = 0 
    while number < 2: 

     guess_number = int(input('Enter a number:')) 


     if guess_number == number: 
      print('Your guess is correct the number is',number) 
      print("you have won €",win,) 
      break 
     if guess_number >=2: 
      print ("Number too high") 
     else: 
      print("you are wrong, you have lost €",bet,) 
      break 
    play_again = input("Play Again? y/n: ") 
    if play_again =='y': 
     game() 
    if play_again =='n': 
     n = print("bye") 
game()