mardi 2 mai 2023

Python: random number game with play again where loop fail

This is my first code ever in Python and I'm sure many think "Ohh.. should have done this or that!". I'm aware and I'm here to learn.

I believe a lot of my errors/problems are related to indentation. But there's plenty of it. I also suspect that I'm mixing things up while in loop or if/elif's. I pasted the terminal output into notepad for reference. I'll post my code below all.

It started really simple but then I wanted to make more and when you make more and don't know what you're doing you tend to google stuff. And when googling stuff make you use different peoples thoughts and that seems to clash sometimes. So if it looks like it's a code written by multiple personalities you're not far from the truth.

What I want is:

  1. Correct action on yes/no alternatives.
  2. Warning and forced reentry when input isn't integers and/or yes/no where it's supposed to be.
  3. When new game starts the random_number must reset. This doesn't work when it starts from "Game ended after 10 trials!". It keeps the tries from last round.

My problem(s) is:

1. While reaching the end of a game the game ask you if you want to play again if you guessed the right #. I'm not sure what I changed but it worked earlier, so my guess is that it has something to do with indentation.

2. New run: Input is "no" and should exit but it start a new round. And the new round start at the "guess"-line (#45) and not at game() (#33). This action doesn't reset the random#.

# Gissa slumptal mellan 1 - 100 i Python
"""
The user must guess a number between 1-100, that the program
give by using the built-in function randint.
The user gets 10 attempts before the game ends. The user gets
an indication of how close the guess is to the correct number and another if
this one is in the range of +-3 <> random_number.

The program tells you how many times you guessed and what the number was.
"""

# Use module random and set guessed to 0.
# could have used from random import randint
import random
guessed = 0

# Declare variable and generate random number in range 1 - 100.
def get_random_number():
    random_number = random.randrange(1,100)
    return random_number


def startGame():
    answer = input("Do you want to play a game? Answer yes or no.\n")
    if answer == "yes":
        while guessed != True:
            game()
    if answer == "no":
        print("See you later!")

# Ask user to guess the number in less than 11 times(10 tries).
# The answer will be in variable "guess".
def game():
    print("\nI guessed a number between 1-100")
    print("Can you guess which in less than 10 guesses?")
    
    # Variable to how many tries and boolean on found.
    tries = 0
    found = False
    random_number = get_random_number()    
    
    while not found:
        while True:
            try:
                guess = int(input("Guess which number I'm thinking of!\n"))
                break
            except ValueError:
                print("Only integers please!")
                continue
        if guess == random_number:
                print(str(random_number) + "! It was right! You did " + str(tries) + " attempts. Good work!\n")
                found = True
                
                # Ask if user would like to try again.
                while True:
                    a = str(input("Do you want to try one more time?.\n"))
                    if a in ("yes", "no"):
                        print("Just answer yes or no, please.\n")
                        continue
                    if a=="yes":                        
                        game()
                    if a=="no": # If I answer "no", I go to startGame again, but "yes" works
                        print("Welcome back!")
                        #break
                            
                    
        # The program check if user was right and give response.
        # When in range of +-3 from randomnumber give a notice.
        elif (abs(guess - random_number) <= 3):
            print("It's really close now!")
            stillGuessing = True
        elif guess < random_number:
            print("Sorry, it was too low. Try again!\n")
            stillGuessing = True
        elif guess > random_number:
            print("Sorry, it was too high. Try again!\n")
            stillGuessing = True

        # Loopcount.
        tries += 1

            # End game after 10 tries and ask user if they want to restart.
        if tries == 10:
                print("\nThe correct answer was: " + str(random_number) + ".")
                print("Game ended after 10 tries! Do you want to play again?")           

                # Ask for Y/N. If not Y/N = errormessage and try again.
                while True:
                    b = str(input("Answer yes or no to try again.\n"))
                    if b in ("ues", "no"):
                        break
                    print("Just answer yes or no, please.\n")
                    
                    # if "yes" I return to guess without new random_number
                    if b=="yes": 
                        game()
                        
                    # if "no" I return to game() - I want the run to end with print("Welcome back!")
                    if b== "no":
                        print("Welcome back!")
                        break   
def main():
    startGame()
if __name__ == "__main__":
    main()
        
        

    
    # Hold until input.
    #print()









I've tried to change indentation, tried different valueError/string controls and rearrange the code when I understood that I've written code in the wrong place and so on.. As the code got bigger I had to start using functions etc. I started with a simple thing that outgrow me. Fast.

I expected something like this:

  1. Ask player to play

  2. If yes - start game, if no - end run.

    • check if input is "yes" or "no"
    • If not, prompt reenter yes/no
  3. Output to user about game and prompt action.

  4. Game start: 10 tries to get random#

    • check if input is int
    • If not, ask for reentry a int
    • If guess is correct: Tell "Congrats, #tries and ask for a new game".
    • check if input is "yes" or "no"
      • If not, ask for only "yes" or "no"
      • If not, reenter yes/no
    • If yes: start new game (with random# reset)
    • If no: print "Welcome back" - end run.
  5. If not right in 10 guesses: Tell user the random#, message about 10 tries and ask for a new game.

    • If yes: reset random#, go to game() and start over
    • If no: print "Welcome back" - end run.



Aucun commentaire:

Enregistrer un commentaire