Python random in a game - Python project

In this video, we build a Python number guessing game where the player tries to guess a randomly generated number between 1 and 100.

Python random in a game - Python project
Python random in a game - Python project

In this video, we build a Python number guessing game where the player tries to guess a randomly generated number between 1 and 100.

Also check out my other game videos:

The game provides feedback to the player if their guess is too high or too low and allows them to keep guessing until they get the correct number. The script uses a Python while loop to keep the game running until the player chooses to exit by entering the word "exit". It also handles invalid input and counts the number of tries. Finally, it uses an f-string (formatted string literal) to display the number of tries when the player guesses correctly.

Python Random in a game 👾 Python project command line game

Full Python script from the video

Here's the full Python script from the video:

# randomNumber.py

import random


def play_game():
    secret_number = random.randint(1, 100)
    tries = 0
    while True:
        try:
            guess = input(
                "Guess a number between 1 and 100. Enter 'exit' to quit. 👉 "
            )
            if guess.lower() == "exit":  # EXIT, eXit
                print("Game exited. See you next time!")
                break
            guess = int(guess)
        except ValueError:
            print("Invalid input. Enter a valid number or 'exit' to quit.")
            continue
        tries += 1
        # if, elif, else
        if guess < secret_number:
            print("Too low!")
        elif guess > secret_number:
            print("Too high!")
        else:
            print(f"Congrats! You guess the number in {tries} tries!")
            break


play_game()
Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications

Step-by-step Python script explanation

Let's go through the script line by line and explain each part:

# Importing the random module
import random

We import the random module, which provides functions for generating random numbers.

def play_game():
    # Generating a random secret number between 1 and 100
    secret_number = random.randint(1, 100)

Inside the play_game function, we generate a random secret number using the random.randint() function, which generates a random integer within a specified range (1 to 100 in this case).

    # Initializing the number of tries
    tries = 0

We initialize a variable called tries to keep track of the number of attempts made by the player. It starts at 0.

    while True:
        # Asking the player for their guess
        guess = input("Guess a number between 1 and 100. Enter 'exit' to quit. 👉 ")

We start an infinite loop using while True. Inside the loop, we ask the player to enter their guess using the input() function. The prompt message asks for a number between 1 and 100, and also provides the option to enter 'exit' to quit the game.

        if guess.lower() == 'exit':
            # Exiting the game if the player enters 'exit'
            print("Game exited. See you next time!")
            break

We check if the player's guess, after converting it to lowercase using the lower() method, is equal to the string 'exit'. If it is, we print a message indicating that the game has been exited and break out of the infinite loop using the break statement.

        try:
            guess = int(guess)
        except ValueError:
            # Handling invalid input
            print("Invalid input. Enter a valid number or 'exit' to quit.")
            continue

We use a try statement to attempt to convert the player's guess into an integer using the int() function. If the conversion fails and raises a ValueError, we catch the exception and handle it by printing an error message. We then use the continue statement to skip the rest of the loop and start the next iteration.

        tries += 1

We increment the tries variable by 1 to keep track of the number of attempts made by the player.

        if guess < secret_number:
            # Providing feedback if the guess is too low
            print("Too low!")
        elif guess > secret_number:
            # Providing feedback if the guess is too high
            print("Too high!")
        else:
            # Congratulating the player if the guess is correct
            print(f"Congrats! You guessed the number in {tries} tries!")
            break

We use an if-elif-else statement to check if the player's guess is less than the secret number, greater than the secret number, or equal to the secret number. We provide appropriate feedback to the player in each case. If the guess is correct, we congratulate the player using an f-string to display the number of tries taken. We then break out of the loop using the break statement.

play_game()

Finally, we call the play_game() function and run the Python script to start the game.

Python random module in game app development

The random module in Python is commonly used in game app development to introduce randomness and unpredictability into games. It provides functions for generating random numbers, shuffling sequences, and making random selections. Here are some ways the random module can be used in game app development:

Generating random numbers

  • Generating random coordinates for objects, enemies, or power-ups within the game world.
  • Determining the outcome of chance-based events or random encounters.
  • Randomizing the initial position, velocity, or attributes of game entities.

Shuffling and randomizing sequences

  • Shuffling a deck of cards or arranging game elements in a random order.
  • Randomizing the order of questions or answers in a quiz or trivia game.
  • Creating randomized levels or mazes by shuffling tiles or blocks.

Making random selections

  • Selecting a random enemy or opponent from a pool of possibilities.
  • Randomly choosing items, weapons, or abilities for the player character.
  • Randomly assigning attributes or characteristics to non-player characters (NPCs).

Simulating probability and chance

  • Implementing random chance-based events such as critical hits, misses, or item drops.
  • Simulating random dice rolls or outcomes of virtual gambling or betting games.
  • Introducing random elements in procedural generation of terrain, landscapes, or levels.

The random module provides various functions to accomplish these tasks, such as random.randint(), random.choice(), random.shuffle(), and random.random(), among others. These functions allow game developers to introduce elements of surprise, variety, and replayability by incorporating randomness into the gameplay.

By utilizing the capabilities of the random module, game developers can create dynamic and engaging game experiences that are different each time they are played, adding excitement and challenge to the game app.

Python project ideas using the Python random module

Here are some Python project ideas that leverage the random module:

Password generator

Develop a password generator that generates strong and secure passwords. Use the random module to randomly select characters from different character sets and create a password with the desired length.

Check out my video where we build a password generator in Python!

Randomized quiz generator

Check out my video where we build a Python quiz game with a third-party quiz API!

Develop a program that generates randomized quizzes. Create a pool of questions and randomize the order of questions and choices for each quiz attempt using the random module.

Dice rolling simulator

Create a program that simulates rolling dice. The user can specify the number of dice and the number of sides on each die, and the program will generate random outcomes.

Random quote generator

Build a program that randomly selects and displays inspirational quotes, jokes, or facts from a predefined list. Use the random module to select a random item from the list.

Rock-paper-scissors game

Create a text-based version of the classic game "Rock-Paper-Scissors" where the player competes against the computer. The computer's choice can be determined using the random module.

Name generator

Build a program that generates random names for characters, pets, or any other purpose. Utilize the random module to select random syllables or letters and combine them to create unique names.

Lottery number generator

Develop a program that generates random numbers for a lottery game. The program should allow the user to specify the range of numbers and the number of tickets to generate.

Random walk visualization

Create a visualization of a random walk, where a point moves randomly in a two-dimensional grid. Use the random module to determine the direction and distance of each step.

Random image manipulation

Load an image and use the random module to apply random transformations, such as rotation, scaling, cropping, or color manipulation, to create interesting and artistic effects.

Random music playlist

Create a program that generates random music playlists. Use the random module to randomly select songs from a music library and create diverse and unpredictable playlists.

These project ideas can serve as starting points for your Python programming journey, allowing you to explore the capabilities of the random module while building fun and practical applications.

Enjoy! 🎉