Python Forum
Play again, in a guessing game
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Play again, in a guessing game
#1
Question 
Hello!

Here the computer comes up with a number in range(1, 9), and we try to guess it, until we come up with the correct number.
We can exit anytime during the game and also at the end we have the choice to play again.
import random
def guessing():
    computer = random.randint(1, 9)
    number_of_guesses = 0
    while True:
        number_of_guesses += 1
        pick = input("Guess, if you dare: ")
        if pick.lower() == "exit":
            print("Better luck next time!")
            print("Attempts:", number_of_guesses - 1)
            break
        elif int(pick) > computer:
            print("Too high.")
        elif int(pick) < computer:
            print("Too low.")
        elif int(pick) == computer:
            print("Yes!")
            if number_of_guesses == 1:
                print("Are you God?!")
            elif number_of_guesses < 3:
                print(f"Impressive! Only {number_of_guesses} attemps.")
            else:
                print(f"Finally! After {number_of_guesses} attemps.")
            break
    again()

def again():
    if input("Continue?(y/n) ") == 'y':
        guessing()
    else:
        exit

guessing()
I've been told that I don't need to define a separate function for just asking the user if they want to play again. But I can't seem combine the two functions together. Wall

Thank you for reading.
Reply
#2
Yes, it doesn't make sense to make a separate function.
the problem is that you need to call sys.exit(). Just exit doesn't do anything even if you have imported it from sys (not shown here).
Anyway, calling recursively the game function is not good idea. Ultimately (although unlikely) you will reach max recursive calls limit.

If it has to be in function - better to return user choice (True/False)
banidjamali likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
All in one.
while True:
    # Start a game
    while True:
        # Play game
        number_of_guesses += 1
        ...
        elif int(pick) == computer:
            ...
            break
    # Do you want to play again?
    if input('Continue (y/n)? ') != 'y':
        break;
You can do this with just one function though I think it cleaner to write a function that plays the game and repeatedly call the game function if you want to play again. I would implement the logic like this:
def play_game():
    """play the game"""

while True:
    play_game()
    if input('Play again (y/n)? ') not in ('Y','y'):
        break
The way you are doing it, with recursion, is ugly. It mixes up the game function with the repeat logic. The game should play the game and the repeat code should ask if you want to play a again and call the game function or end the loop. Recursion also causes a problem where you have to use the nuclear option of exiting the program to unwind the recursion stack.

Both choices have only one function.
banidjamali likes this post
Reply
#4
A function more may not be needed as buran say or deanhystad show.
For me it make better/cleaner to have repeat game and quit game in one function and the game logic in one function.
Then always fall back to menu function where can start a new game or quit out.
import random

def play_game():
    print("Guess a number betwwen 1 and 10")
    secret_number = random.randint(1, 10)
    guess, tries = 0, 0
    while guess != secret_number:
        guess = int(input("Take a guess: "))
        if guess > secret_number:
            print ("Lower")
        elif guess < secret_number:
            print ("Higher")
        tries += 1
    print(f'You guessed it! The number was {guess} in {tries} tries\n')

def menu():
   while True:
       print('(1) Play guess number game')
       print('(Q) Quit')
       choice = input('Enter your choice: ').lower()
       if choice == '1':
           play_game()
       elif choice == 'q':
           return False
       else:
           print(f'Not a correct choice: {choice}')

if __name__ == '__main__':
    menu()
buran and banidjamali like this post
Reply
#5
(Jan-20-2021, 06:38 PM)snippsat Wrote: def menu():
Very helpful. Thank you.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help - random number/letter guessing game juin22 1 3,182 Aug-16-2020, 06:36 AM
Last Post: DPaul
  making a guessing number game blacklight 1 2,184 Jul-02-2020, 12:21 AM
Last Post: GOTO10
  An interesting Role-Play-Game battle script NitinL 4 3,388 Apr-02-2020, 03:51 AM
Last Post: NitinL
  Guessing game with 4 different digits LinseyLogi 6 3,615 Mar-29-2020, 10:49 AM
Last Post: pyzyx3qwerty
  Guessing game with comparison operators Drone4four 9 13,736 Dec-02-2018, 06:12 PM
Last Post: ichabod801
  Guessing Game "limit 4 attempts" help rprollin 3 19,709 Jun-23-2018, 04:37 PM
Last Post: ljmetzger
  Name guessing game in python Liquid_Ocelot 6 14,977 Apr-01-2017, 12:52 PM
Last Post: ichabod801
  guessing script simon 3 5,545 Oct-10-2016, 01:47 PM
Last Post: simon
  trying to get my random number guessing game to work! NEED HELP RaZrInSaNiTy 4 6,820 Oct-06-2016, 12:49 AM
Last Post: tinabina22

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020