Creating games in Python is a great way to learn basic programming concepts, and build a stronger foundation in programming. One of the games you can create is a simple number-guessing game.

You can create the number guessing game using a single Python script. To play the game, run the script using a command line or terminal.

To make the game more interesting, you can add some additional gameplay concepts. This includes the ability to give hints to the player, or the ability to change the game's difficulty.

How to Generate a Random Number

You can start by creating a new Python script with a .py extension to hold the logic for the game. Inside, add some starting code to generate a random number between 1 and 50 for the player to guess.

If you are not familiar with Python syntax, take a look at some basic Python examples to get you up to speed.

  1. Create a new file called number-guessing-game.py. Open the file using any text editor, such as Visual Studio or Atom.
  2. At the top of the file, import the random module:
            import random
        
  3. Use the random module's randint() method to generate a random number between 1 and 50:
            guess_range = 50
    answer = random.randint(1, guess_range)
  4. Start the game, and ask for the player to guess the number:
            print("Welcome to the number guessing game!")
    print("")
    userInput = input("Guess a number between 1 and " + str(guess_range) + ": ")
    guess = int(userInput)

How to Check if the User Guessed the Correct Number

For the user to win the game, compare the user's input to the random number generated and check if it matches.

  1. While the user has not yet guessed the correct answer, re-ask them to enter a new input. Make sure to indent any nested code, as Python's structure depends on correct indentation:
            guess = ""
    while guess != answer:
      userInput = input("Guess a number between 1 and " + str(guess_range) + ": ")
      guess = int(userInput)
  2. If the code executes past the while loop, that means they have guessed the correct answer:
            print("Congratulations! You guessed the correct number. You win!") 
        

How to Add a Limited Number of Guesses

To limit the player from asking an infinite amount of times, you can limit the number of their guesses.

  1. Declare a new variable at the beginning of the file, to keep track of the player's number of guesses allowed. Set it to 10, to begin with:
            guesses_allowed = 10
        
  2. Change the while statement to a for loop, that only repeats for the limited amount of guesses:
            for i in range(guesses_allowed):
      userInput = input("Guess a number between 1 and " + str(guess_range) + ": ")
      guess = int(userInput)
  3. Inside the for loop, if one of the guesses is the correct answer, break out of the for loop:
            if guess == answer:
      print("Congratulations! You guessed the correct number. You win!")
      break
  4. Still, inside the for loop, add another if statement to check if the player has reached their number of guesses limit. If so, end the game:
            if (i == guesses_allowed - 1):
      print("Sorry, you have run out of guesses. You lose!")

How to Add Hints to the Game

Add another feature to the game to give the player some hints. One hint can include letting them know if they need to guess a higher number or a lower number.

Another hint is to tell them how close or far they are from the answer. For example, the game should inform them if they are getting "warmer". Otherwise, if they are far from the number, the game should tell them they are getting "colder".

  1. Modify the if statement that tells the user if they have won. If they still did not guess the correct answer, let them know if the actual answer is higher or lower.
            if guess == answer:
      print("Congratulations! You guessed the correct number. You win!")
      break
    elif guess < answer:
      print("The number is higher.")
    else:
      print("The number is lower.")
  2. Add another if statement to add additional hints. This will tell them if they are getting closer or "warmer" to the number. Use the absolute function to determine the distance between the guess and the answer. For example, if they are less than 10 numbers away from the answer, the game will print "You're warm":
            if abs(guess - answer) <= 10:
      print("You're warm!")
    elif abs(guess - answer) <= 20:
      print("You're getting warmer.")
    elif abs(guess - answer) <= 30:
      print("You're cold.")
    else:
      print("You're freezing.")

How to Change the Difficulty of the Game

You can ask the user to choose a difficulty level. The difficulty level determines how many guess attempts the player has, and how far the guess range is.

  1. At the beginning of the game, ask the user to choose a difficulty level:
            print("Welcome to the number guessing game!")
    print("")
    while True:
      level = input("Select difficulty level (easy, medium, hard): ").lower()
  2. Add some validation to make sure the player only types the options "easy", "medium", or "hard". If the user enters an invalid response, the game will ask them to re-enter a difficulty level.
            if level in ["easy", "medium", "hard"]:
      break
    else:
      print("Invalid input. Please select either 'easy', 'medium', or 'hard'.")
  3. Before generating the random number, use the player's difficulty to determine how many guesses they can have. You can also use their selected difficulty level to determine how big the guess range is:
            if level == "easy":
      guess_range = 50
      guesses_allowed = 20
    elif level == "medium":
      guess_range = 100
      guesses_allowed = 15
    else:
      guess_range = 150
      guesses_allowed = 10

    answer = random.randint(1, guess_range)

How to Play the Game

Now that you have all the logic for the game, you can play it in a command prompt. You can also view the full number guessing game example on GitHub.

  1. Open a command prompt or terminal, and navigate to the folder where you stored your Python script. For example, if you stored your script on the Desktop, the command would look similar to this:
            cd C:\Users\Sharl\Desktop
        
  2. Use the python command to run your Python script:
            python number-guessing-game.py
        
  3. Enter a difficulty level.
    Python number guessing game in terminal
  4. Enter numbers into the command prompt to try and guess the number.
    Python number guessing game in terminal gameplay

Learn Programming by Creating Simple Games

Now you understand how to create and run a simple game using a single Python script. Continue your learning journey by exploring other interesting project ideas. One example of this is to try building a Ping sweeper in Python.