Python Forum
Asking for help in my code for a "Guess the number" game.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Asking for help in my code for a "Guess the number" game.
#1
Hey all, I'm pretty new to Python, well new might be an understatement.
I've been tasked to create one of those guess the number games. One of my friends was nice enough to let me use his code as a base. All I'm capable of is rephrasing some print messages, comments, variables, and fixing some really basic problems. But being as green as grass has really made this a struggle for me. Wall
I seem to have broken the code, as it's now getting errors. Doh

I'd like to ask for help from anyone, any and all help is appreciated.
Thanks in advance.

The code:
import random #Brings in Python's built-in random module.

#This variable is currently set to false. It determines whether the player has won or not. When this is true, the game has ended and the player has won.
player_win == False 

#The set of code below begins the program by asking what the player's name is.
while player_win == False:
    print("Hello, and welcome to the program!")
player_name = input("Please enter your name to continue! \n What is your name? \n :") #This variable will store what the player has entered when they are asked to input a name.
if player_name.isalpha(): #This code makes it so that players can only enter alphabetic characters as their name.
        break


#After the player has entered their name, it will greet them using the name they entered.
print("Hey {}, let's get started!".format(player_name))
print("I'm thinking of a number between 1 - 20, can you guess what it is? \n Be careful though, because you only have 7 lives! \n Oh, and I'll give you clues by telling you if the number is higher or lower than your guess!")

invalid_response = False #This is a variable that checks whether or not the player has entered an invalid response.

lives = 7 #This variable sets the amount of guesses the player is allowed before losing the game.

random_integer = random.randrange (1, 20) #This generates a random number between 1 - 20, which the program will store as the number it is 'thinking' of.

while lives > -1: #If somehow the player manages to get to -1 lives this will create an infinite loop. But this shouldn't be possible, so this will be used to indicate that the player has lost the game.
          try:
            if player_win == True: #If the player has won this code will be triggered.
                play_again = input("Good game, wanna play again? \n")

                invalid_values = True
                if play_again == "yes":
                    print("Here we go again!")
                #The code below restarts the game by repeating some of the code, as if the program were start for the first time.
                    player_win = False
                    lives = 7
                    random_integer = random.randrange (1, 20)
                elif play_again == "no":
                    break
                else:
                    print("""Please enter a valid response either
                      "yes" or "no" """)
                      
         #When lives hit zero, this code will be triggered and tell the player what number the program was 'thinking' of
            elif lives == 0:
                print("Aw man, it looks like you're out of lives! The number I was thinking of was {}".format(random_integer))
                player_win = True
       #This chunk of code here asks the user to guess what number the program is 'thinking of'
            if player_win == False
              lives -= 1
              player_guess = int(input("What number am I thinking of? \n")

        #The chunk of code below checks if the players response is invalid. If it is the program will ask them to enter a valid response.
              invalid_value = False

          except SyntaxError and ValueError
           print("Please enter a whole number/integer. \n Enter the number now.")
           
           player_guess = False
           
           invalid_value = True
           
           lives += 1

          if player_guess == random_integer and invalid_response == False: # this code tells the player whether the number they guessed is either to high or too low.
                print("You guessed the correct number!")
                player_win = True
         #This code tells the player that their guess is higher than the number the program is 'thinking' of.       
          elif player_guess > random_integer and player_guess < 20 and player_win == False and invalid_value == False:
                print("Looks like your guess is higher than my number!")
         #This code tells the player that their guess is lower than the number the program is 'thinking' of.
          elif player_guess < random_integer and player_win == False and invalid_value == False:
                print("Your guess is lower than my number!")
         #The code below reminds the player the range of numbers the program can 'think' of.    
          elif player_guess >= 20 or player_guess <= 0 and player_win == False and invalid_value == False :
              print("Remember that the number I'm thinking of is between 1 and 20.")
Reply
#2
Starting with someone else's code is a bad idea, largely because you can't be sure of the logic he/she used to put it together. Suggest you start with mapping the flow and tasks of the program, like this:
1. Welcome note and get user name
2. Generate random integer, initiate counter
3. Start loop asking for guesses
4. If guess high give message, deduct 1 from counter. If counter > 0 go to 3, otherwise go to end block
5. If guess low give message, deduct 1 from counter. If counter > 0 go to 3, otherwise go to end block
6. If guess correct, give message and go to end block
7. <end block> Print game over, ask if wants to play again
8. if response is yes, go to 2, otherwise stop

OK so that is the basic blocking out of the tasks. Do each one, and you learn along the way.
Reply
#3
Hi, thanks for the response. My friend and I talked about it so I think that most of this can be cleared up, I'm mainly just focused on trying to fix the errors.

I'd really prefer to just get the errors fixed because this is due quite soon.
Reply
#4
(Aug-14-2019, 11:46 AM)Domz Wrote: I'd really prefer to just get the errors fixed because this is due quite soon.
Obviously the indentation is quite messed up. Start from there. If you get other errors - post the full traceback you get, in error tags
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
#5
Already the first line of code is not doing what you want it to do.
Reply
#6
One thing to ask from yourself - is your objective to meet deadline and move on with your life or learn to program?

If first then (based on your moral values) cheating is an option. However, if you intend to learn to program then you should start yourself from scratch.

jefsummers provided one way how to split 'big task' into smaller chunks. It doesn't matter if you use this or create your own 'algorithm' - you have to solve all these small tasks one after another.

Just and idea:

You should test your code as you go. For beginner 'testing' means that you write small chunk of code, run it and observe if it's working as expected. If so you add new lines of code and repeat.

Write code into .py file, run it from terminal in interactive mode and check whether all names, values etc are as you excpect them to be. You should be able to understand error messages as well.

Lets write two first lines of code into file (guessing_game.py) and observe what happens:

import random


player_win == False
Now from terminal cd into directory where your guessing_game.py is. Then enter:

python -i guessing_game.py (or python3 or something else depending how Python is set up on your computer)

This will run the file and keep Python interactive session alive. But in this case it doesnt matter. You will see:

Output:
Traceback (most recent call last): File "guessing_game.py", line 4, in <module> player_win == False NameError: name 'player_win' is not defined
What did happen? You check whether player_win is False. As player_win is not defined you will get NameError. If you intend to assing False to player_win then you should write player_win = False. If you make changes in file and run it again then nothing happens except Python interactive prompt appears in terminal. You can check the value of player_win:

>>> player_win
False
Now you take next step and repeat process until you have working code.

Instead of .py file and terminal one can use Jupyter Notebook / JupyterLab.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help - random number/letter guessing game juin22 1 3,181 Aug-16-2020, 06:36 AM
Last Post: DPaul
  Dynamically chosing number of players in a "game" nsadams87xx 5 4,114 Jul-17-2020, 02:00 PM
Last Post: deanhystad
  Can someone help me optimize this game for large number of strings Emekadavid 13 4,894 Jul-06-2020, 06:16 PM
Last Post: deanhystad
  making a guessing number game blacklight 1 2,183 Jul-02-2020, 12:21 AM
Last Post: GOTO10
  Prime number code ryfoa6 3 2,889 Mar-21-2020, 12:23 AM
Last Post: ryfoa6
  Trouble interpreting prime number code ryfoa6 1 2,249 Mar-20-2020, 03:47 PM
Last Post: stullis
  Guess the number game jackthechampion 5 3,169 Mar-07-2020, 02:58 AM
Last Post: AKNL
  restarting game code zyada7med 5 4,619 Sep-03-2019, 09:24 PM
Last Post: ichabod801
  Guess a number game Drone4four 4 5,235 Nov-16-2018, 03:56 AM
Last Post: Drone4four
  Code: Creating a basic python game? searching1 5 3,418 Nov-12-2018, 05:18 AM
Last Post: searching1

Forum Jump:

User Panel Messages

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