Creating a Simple Python Game in 100 Lines of Code

Python, as a beginner-friendly programming language, is often used to teach the fundamentals of coding. One of the most engaging ways to learn a new language is by creating simple games. In this blog post, we’ll explore how to create a simple Python game within 100 lines of code.

Let’s design a basic guessing game where the computer generates a random number between 1 and 100, and the player has to guess it. Here’s the code:

pythonimport random

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

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

while guess != number_to_guess:
guess = int(input("Guess a number: "))
attempts += 1

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

print(f"Congratulations! You guessed the number in {attempts} attempts.")

if __name__ == "__main__":
game()

Let’s break down the code:

  1. Imports: We import the random module to generate a random number.
  2. Function Definition: We define a function game() that encapsulates the game’s logic.
  3. Initialization: Inside the function, we initialize the number_to_guess as a random number between 1 and 100. We also initialize guess to None and attempts to 0.
  4. Game Introduction: We print a welcome message and tell the player the range of numbers.
  5. Guessing Loop: We use a while loop to keep asking the player for guesses until they guess correctly.
  6. Input and Feedback: Inside the loop, we take the player’s input, convert it to an integer, and update the number of attempts. Based on the guess, we give the player feedback (too low, too high).
  7. Win Condition: Once the player guesses correctly, we exit the loop and congratulate them, telling them the number of attempts they took.
  8. Execution: Finally, we check if the script is being run directly (not imported as a module) and call the game() function.

This simple game not only teaches the basics of Python programming but also introduces concepts like loops, conditionals, and user input. It’s a great starting point for beginners interested in learning Python through hands-on experience.

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 *