Creating a Simple Game with Python in 100 Lines of Code

Python, with its simplicity and readability, is an excellent language for beginners to learn programming. One of the fun ways to practice Python is by creating simple games. In this article, we’ll explore how to create a basic guessing game in just 100 lines of Python code.

The game we’ll build is a simple number guessing game. The computer will randomly generate a number between 1 and 100, and the player will have to guess what it is. The player gets a limited number of attempts to guess the correct number.

Here’s the code for the game:

pythonimport random

def game():
number_to_guess = random.randint(1, 100)
attempts = 0
guess = None

print("Welcome to the Guessing Game!")
print("I'm thinking of a number between 1 and 100.")

while attempts < 5 and guess != number_to_guess:
guess = int(input("Guess the number: "))
attempts += 1

if guess < number_to_guess:
print("Too low. Try again.")
elif guess > number_to_guess:
print("Too high. Try again.")

if guess == number_to_guess:
print(f"Congratulations! You guessed the number in {attempts} attempts.")
else:
print(f"Sorry, you didn't guess the number. The correct number was {number_to_guess}.")

if __name__ == "__main__":
game()

This code defines a function game() that encapsulates the game logic. Inside the function, we generate a random number using the random.randint() function. We also initialize the variables attempts to keep track of the number of guesses and guess to store the player’s input.

The game loop runs as long as the player hasn’t guessed the correct number and hasn’t exceeded the maximum number of attempts (5 in this case). Inside the loop, we prompt the player to enter their guess, convert it to an integer, and update the attempts counter.

Based on the player’s guess, we provide feedback indicating whether the guess is too low or too high. If the player guesses the correct number, we congratulate them and display the number of attempts they took. Otherwise, we tell them the correct number and end the game.

The if __name__ == "__main__": block ensures that the game() function is called only when the script is run directly, not when it’s imported as a module.

With this simple code, you can create an engaging and educational game for beginners to practice their Python skills.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *