2016-11-06 3 views
1

Этот вопрос трудно объяснить, я надеюсь, что название не смущает людей.Как сохранить ход цикла, но получить одно и то же случайное число, но изменить после завершения

Поэтому я должен заставить пользователя угадать число от 1 до 100, и если пользователь правильно угадывает номер, я хочу, чтобы он перезапустил игру, но сгенерировал новый номер и снова отобразил приветственное сообщение. Также пользователь может попробовать только 10 раз, а затем появится сообщение с надписью. Я застрял, пытаясь отобразить новое сообщение, сгенерировав новый номер, чтобы число было одинаковым во всем цикле и не удалось выполнить попытку пользователя в 10 попыток.

Прошу прощения, если это смущает.

Это то, что у меня есть:

import random 
import time 
def getInput(): 
    x = random.randrange(100) 
    print(x) # for testing 

    print("***Welcome! Guess and try to find a number between 1 and 100!***") 
    while True: 
     userGuess = int(input("Enter Your Guess: ")) 

     if (userGuess > x): 
      print("Lower! Enter Again: ") 

     elif (userGuess < x): 
      print("Higher! Enter Again: ") 
     elif (userGuess > 100): 
      print("Guess must be between 1 and 100") 
     elif (userGuess < 1): 
      print("Guess must be greater then 0") 
     elif (userGuess == x): 
      print("You win!") 
      time.sleep(3) 
      continue 

def main(): 
    getInput() 

main() 

ответ

1

Каждый раз, когда начинается цикл вам нужно создать новое случайное число, то сбросить число от попыток до 0

import random 
import time 
def getInput(): 
    x = random.randrange(100) 
    print(x) # for testing 

    print("***Welcome! Guess and try to find a number between 1 and 100!***") 
    tries = 0 # we need a variabe to see how many tries the user has had 
    while True: 
     userGuess = int(input("Try "+str(tries + 1)+" Enter Your Guess: ")) 

     if (userGuess == x): 
      print("You win!") 
      print("***Think you can win again? Guess and try to find a number between 1 and 100!***") 
      x = random.randrange(100) 
      tries = 0 # reset tries 
      print(x) # we need a new random number for the user to guess 
      time.sleep(3)    
      continue 

     elif (userGuess > x): 
      print("Lower! Enter Again: ") 
     elif (userGuess < x): 
      print("Higher! Enter Again: ") 

     if (userGuess > 100): 
      print("Guess must be between 1 and 100") 
     elif (userGuess < 1): 
      print("Guess must be greater then 0") 
     else: 
      tries = tries + 1 # add 1 to tries unless they make an invalid guess 
      if tries == 10: 
       print("<<GAME OVER>>") 
       break # end 


def main(): 
    getInput() 

main() 
1
def getInput(): 
    for i in range(10): 
    #loop body 

    return "Game Over." 

Если я интерпретации вы хотите закончить после 10 догадок.

1

Я пытался сохранить изменения к минимуму, чтобы вы легко понять, увидеть @ ответ Тома для лучшего способа

import random 
import time 

def startNewGame(): 
    x = random.randrange(100) 
    print(x) # for testing 

    print("***Welcome! Guess and try to find a number between 1 and 100!***") 
    numberOfTries = 0 
    while numberOfTries<10: 
     userGuess = int(input("Enter Your Guess: ")) 
     numberOfTries += 1 
     if (userGuess > x): 
      print("Lower! Enter Again: ") 
     elif (userGuess < x): 
      print("Higher! Enter Again: ") 
     elif (userGuess > 100): 
      print("Guess must be between 1 and 100") 
     elif (userGuess < 1): 
      print("Guess must be greater then 0") 
     elif (userGuess == x): 
      print("You win!") 
      time.sleep(3) 
      return 
    print("You Lose!") 
    time.sleep(3) 

def main(): 
    startNewGame() 
    while(True): 
     again = input("Would you like to play again?(yes/no) ") 
     if again == "yes": 
      startNewGame() 
     elif again == "no": 
      break 


main() 
0

Вот как я предлагаю сделать это. Я добавил комментарии с тремя хэшей, где я сделал изменения:

import random 
import time 
def playMany(): 
    def play(): 
     x = random.randrange(100) 
     print(x) # for testing 

     print("***Welcome! Guess and try to find a number between 1 and 100!***") 
     for attempt in range(10): ### try 10 times at the most 
      userGuess = int(input("Enter Your Guess: ")) 

      ### change the order of the tests: 
      if (userGuess > 100): 
       print("Guess must be between 1 and 100") 
      elif (userGuess < 1): 
       print("Guess must be greater then 0") 
      elif (userGuess > x): 
       print("Lower!") ### Don't ask to "enter" here 
      elif (userGuess < x): 
       print("Higher!") 
      else: ### no need to test for equality: it is the only possibility left 
       print("You win!") 
       return True ### Exit play() with True (to play again) 
     ### Deal with too many wrong guesses 
     print('Too many wrong guesses. Game over') 
     return False 

    while play(): ### Keep repeating the game until False is returned 
     time.sleep(3) ### Move sleep here 

def main(): 
    playMany() ### Use a more telling function name 

main() 

Посмотреть работать на repl.it.

0

Вот если еще один способ сделать это:

import random 
import time 

def matchGuess(randNumber, userGuess): 
    if userGuess > 100   : print "Guest must be between 1 and 100" 
    elif userGuess < 0   : print "Guest must be greater than 0" 
    elif userGuess > randNumber : print "Lower! Enter Again:" 
    elif userGuess < randNumber : print "Higher! Enter Again:" 
    elif userGuess == randNumber : print "You win!" 

if __name__ == "__main__": 
    print "***Welcome! Guess and try to find a number between 1 and 100!***" 
    for i in range(10): 
     userGuess = int(raw_input("Enter Your Guess:")) 
     randNumber = random.randrange(100) 
     matchGuess(randNumber, userGuess) 
Смежные вопросы