Pytech Resources

Building Your First Game With Python

Sep 8, 2023

Posted by:

Introduction

Let's create a simple text-based game using Python where the player has to guess a number. The game will prompt the player to guess a randomly chosen number within a certain range, and it will provide hints if the guessed number is too high or too low. The game will continue until the player guess the number correctly or exceeds the maximum number of tries allowed.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import random

def guess_the_number():
    # Set the maximum number for the game
    MAX_NUM = 20
    MAX_TRIES = 6
    # Generate a random number for the player to guess
    secret_number = random.randint(1, MAX_NUM)
    
    print("Welcome to the Guess the Number game!")
    print(f"I am thinking of a number between 1 and {MAX_NUM}. Can you guess it?")
    
    tries = 0
    while tries < MAX_TRIES:
        # Ask the player to guess the number
        try:
            guess = int(input("Enter your guess: "))
        except ValueError:
            print("Invalid input. Please enter a valid number.")
            continue
        
        tries += 1
        
        # Check if the guess is correct
        if guess == secret_number:
            print(f"Congratulations! You guessed the number {secret_number} correctly in {tries} tries!")
            break
        elif guess < secret_number:
            print("Too low! Try again.")
        else:
            print("Too high! Try again.")
    else:
        print('Game over!')
        print(f'The number I was thinking of was {secret_number}.')

if __name__ == "__main__":
    guess_the_number()

Line by Line Explanation

Line 1 - Use the import statement to import the random module (from the Python Standard Library)

Line 3 - The def keyword is used to define a function named guess_the_number, which is the entry point for this program. We can give our function any meaningful name. A very common practice is to name the entry point function as main.

Line 36 - __name__is a special Python variable. If you run this script as the main program, this variable takes on the value __main__ and the if statement evaluates to true and runs the guess_the_number function.