MC, 2025
Ilustracja do artykułu: How to Create a Simple Python Game with Code: A Beginner's Guide

How to Create a Simple Python Game with Code: A Beginner's Guide

If you're a beginner in programming and wondering how to create your first Python game, you're in the right place! Python is one of the most accessible programming languages, and it's widely used for game development, from small projects to larger, more complex games. In this article, we will walk you through the steps of creating a simple Python game with code examples and give you the tools to get started on your own game development journey.

Why Python for Game Development?

Python is known for its simplicity and readability, making it an ideal choice for beginner developers. It has a vast collection of libraries and frameworks that are particularly useful for game development. Pygame is one of the most popular libraries for creating games in Python. It offers easy access to graphics, sound, and user input, which makes it a great choice for your first game.

Not only is Python an accessible language, but it also helps you focus on understanding the concepts of game development without being bogged down by complex syntax. With Python, you can bring your creative ideas to life without needing years of experience in coding.

Setting Up Python and Pygame

Before you start creating your game, you need to set up Python on your computer. Here’s how:

  • Download and Install Python: Visit the official Python website (https://www.python.org/downloads/) and download the latest version of Python.
  • Install Pygame: After installing Python, you can install the Pygame library by opening your terminal or command prompt and running the following command:
pip install pygame

Once you've installed Pygame, you're all set to start coding your game! Now let's look at a simple example of a Python game.

Example 1: A Simple Python Game - "Catch the Ball"

In this simple game, we will create a window where a ball moves around the screen. The player controls a rectangle (representing a paddle) to catch the ball. The ball will bounce off the edges of the window, and the goal is to catch it with the paddle. Here's the basic code for this game:

import pygame
import random

# Initialize Pygame
pygame.init()

# Set the dimensions of the screen
width, height = 800, 600
screen = pygame.display.set_mode((width, height))

# Define colors
white = (255, 255, 255)
red = (255, 0, 0)
blue = (0, 0, 255)

# Set up the ball
ball_radius = 20
ball_x = random.randint(ball_radius, width - ball_radius)
ball_y = ball_radius
ball_speed_x = random.choice([-5, 5])
ball_speed_y = 5

# Set up the paddle
paddle_width = 100
paddle_height = 10
paddle_x = (width - paddle_width) // 2
paddle_y = height - paddle_height - 10
paddle_speed = 15

# Game loop
running = True
while running:
    screen.fill(white)
    
    # Draw the ball and paddle
    pygame.draw.circle(screen, red, (ball_x, ball_y), ball_radius)
    pygame.draw.rect(screen, blue, (paddle_x, paddle_y, paddle_width, paddle_height))
    
    # Move the ball
    ball_x += ball_speed_x
    ball_y += ball_speed_y
    
    # Ball bouncing off the edges
    if ball_x - ball_radius < 0 or ball_x + ball_radius > width:
        ball_speed_x *= -1
    if ball_y - ball_radius < 0:
        ball_speed_y *= -1
    
    # Check if the ball hits the paddle
    if paddle_y < ball_y + ball_radius < paddle_y + paddle_height and paddle_x < ball_x < paddle_x + paddle_width:
        ball_speed_y *= -1  # Bounce the ball off the paddle
    
    # Move the paddle with arrow keys
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and paddle_x > 0:
        paddle_x -= paddle_speed
    if keys[pygame.K_RIGHT] and paddle_x < width - paddle_width:
        paddle_x += paddle_speed
    
    # Check for game exit
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    pygame.display.flip()
    pygame.time.Clock().tick(60)

pygame.quit()

In this game, the ball moves around the screen, bouncing off the edges. The player controls the paddle at the bottom using the left and right arrow keys. If the ball hits the paddle, it bounces back up.

How This Code Works

Let's break down the code to understand how it works:

  • pygame.init(): Initializes all the modules in Pygame.
  • screen = pygame.display.set_mode(): Creates a window with the specified dimensions (800x600 in this case).
  • pygame.draw.circle() and pygame.draw.rect(): These functions are used to draw the ball (circle) and the paddle (rectangle) on the screen.
  • ball_speed_x and ball_speed_y: These variables control the movement of the ball. When the ball reaches the edge of the window, it bounces off by reversing the direction of movement.
  • paddle movement: The paddle's position is updated based on user input (left or right arrow keys).

Example 2: Adding a Score System

Now that we have a simple game, let's add a score system to track how many times the player successfully catches the ball. We will increase the score every time the ball hits the paddle. Here's how we can modify the previous code:

import pygame
import random

pygame.init()

width, height = 800, 600
screen = pygame.display.set_mode((width, height))

white = (255, 255, 255)
red = (255, 0, 0)
blue = (0, 0, 255)
black = (0, 0, 0)

ball_radius = 20
ball_x = random.randint(ball_radius, width - ball_radius)
ball_y = ball_radius
ball_speed_x = random.choice([-5, 5])
ball_speed_y = 5

paddle_width = 100
paddle_height = 10
paddle_x = (width - paddle_width) // 2
paddle_y = height - paddle_height - 10
paddle_speed = 15

score = 0
font = pygame.font.Font(None, 36)

running = True
while running:
    screen.fill(white)
    
    pygame.draw.circle(screen, red, (ball_x, ball_y), ball_radius)
    pygame.draw.rect(screen, blue, (paddle_x, paddle_y, paddle_width, paddle_height))
    
    ball_x += ball_speed_x
    ball_y += ball_speed_y
    
    if ball_x - ball_radius < 0 or ball_x + ball_radius > width:
        ball_speed_x *= -1
    if ball_y - ball_radius < 0:
        ball_speed_y *= -1
    
    if paddle_y < ball_y + ball_radius < paddle_y + paddle_height and paddle_x < ball_x < paddle_x + paddle_width:
        ball_speed_y *= -1
        score += 1  # Increase score when the ball hits the paddle
    
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and paddle_x > 0:
        paddle_x -= paddle_speed
    if keys[pygame.K_RIGHT] and paddle_x < width - paddle_width:
        paddle_x += paddle_speed
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    # Display score
    score_text = font.render(f"Score: {score}", True, black)
    screen.blit(score_text, (10, 10))
    
    pygame.display.flip()
    pygame.time.Clock().tick(60)

pygame.quit()

Now, every time the player catches the ball, the score increases, and the score is displayed on the screen. You can expand this further by adding more features, such as a game-over condition or different levels of difficulty.

Conclusion: Your Journey in Game Development

Congratulations! You've just built a simple Python game with code, and you can now expand it to add more exciting features. The world of game development is vast and full of possibilities. With Python and Pygame, you have all the tools you need to create a fun game. Start with simple projects like this and keep adding new features to improve your skills. Remember, the best way to learn is by doing, and every line of code brings you closer to becoming a game developer!

Komentarze (0) - Nikt jeszcze nie komentował - bądź pierwszy!

Imię:
Treść: