1
Current Location:
>
Game Development
Learning Pygame from Scratch: Your Path to Becoming a Game Development Pro!
Release time:2024-10-15 07:54:28 read: 32
Copyright Statement: This article is an original work of the website and follows the CC 4.0 BY-SA copyright agreement. Please include the original source link and this statement when reprinting.

Article link: https://cheap8.com/en/content/aid/517?s=en%2Fcontent%2Faid%2F517

First Encounter

Have you ever dreamed of creating your own game? Whether it's for profit or to fulfill a personal dream, mastering game development skills is a great choice. And Python's game development library, Pygame, will help you achieve this goal with ease!

As a lightweight cross-platform library, Pygame is not only easy to use but also powerful. You can use it to create various 2D games, from simple arcade games to large RPGs. Let's start our Pygame learning journey today!

Environment Preparation

Before writing our first line of code, let's prepare the development environment. Don't worry, this step is very simple:

  1. Make sure you have Python installed on your computer (version 3.6 or above)
  2. Install Pygame using pip: pip install pygame

It's that simple! You can also choose to use Python distributions like Anaconda, which usually come with Pygame pre-installed.

Hello Pygame

Alright, let's write our first Pygame program! Create a new Python file and enter the following code:

import pygame


pygame.init()


size = (800, 600)
screen = pygame.display.set_mode(size)


pygame.display.set_caption("My First Pygame")


running = True
while running:
    # Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Fill background color
    screen.fill((0, 0, 0))

    # Update screen display
    pygame.display.flip()


pygame.quit()

Run this code, and you'll see an 800x600 black window with the title "My First Pygame". It's that simple, you've created your first Pygame window program!

The main flow of the code is:

  1. Import the Pygame module
  2. Initialize Pygame
  3. Set window size and title
  4. Enter the game main loop
  5. Handle events (like clicking the close button)
  6. Fill the window background color
  7. Update the screen display
  8. Quit Pygame

I know you must be eager to learn more, so let's move forward step by step!

Drawing Sprites

A plain black window isn't very exciting, so let's add some interesting elements to it. In game development, visual elements are collectively called "sprites", such as player characters, enemies, bullets, and so on.

Let's start by drawing a simple rectangular sprite:

import pygame

pygame.init()


size = (800, 600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My Pygame")


player = pygame.Rect(300, 300, 60, 60)


running = True
while running:
    # Event handling
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Fill background color
    screen.fill((0, 0, 0))

    # Draw sprite
    pygame.draw.rect(screen, (255, 0, 0), player)

    # Update display
    pygame.display.flip()

pygame.quit()

In this code, we defined a rectangle data player using pygame.Rect, with coordinates (300,300) and size 60x60 pixels. Then in the main loop, we use pygame.draw.rect to draw this rectangle on the window.

Do you see a red rectangle in the center of the window? That's our first sprite! Try changing the coordinates and size of player to see how the rectangle changes.

Sprite Movement

Static sprites aren't very interesting, so let's make it move! There are generally two ways to move objects in games:

  1. Move by changing sprite coordinates
  2. Use vectors for smooth movement

Let's look at the first method, changing sprite coordinates through keyboard events:

x_speed = 0
y_speed = 0


while running:
    # Event handling
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        # Detect key events
        elif event.type == pygame.KEYDOWN:
            # Left-right movement
            if event.key == pygame.K_LEFT:
                x_speed = -5
            elif event.key == pygame.K_RIGHT:
                x_speed = 5
            # Up-down movement  
            elif event.key == pygame.K_UP:
                y_speed = -5
            elif event.key == pygame.K_DOWN:
                y_speed = 5
        elif event.type == pygame.KEYUP:
            # Stop movement
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                x_speed = 0
            elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:  
                y_speed = 0

    # Move sprite            
    player.x += x_speed
    player.y += y_speed

    # Other code...

In the code above, we defined two variables x_speed and y_speed to control the horizontal and vertical movement speed of the sprite. When a key press event is detected, we change the speed value accordingly. When the key is released, the speed value is reset to 0.

In the main loop, we change the x and y coordinates of the sprite based on the current speed values, thus achieving sprite movement. You can try running this code and use the keyboard to control the sprite moving around the window.

However, this method has a drawback: the sprite's movement may not appear smooth enough. To achieve truly fluid movement effects, we need to use vectors:

import pygame
import math


move_x = 0
move_y = 0


angle = 0


while running:
    # Event handling
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        # Calculate movement vector based on key press    
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                move_x = -1
            elif event.key == pygame.K_RIGHT:
                move_x = 1
            elif event.key == pygame.K_UP:
                move_y = -1
            elif event.key == pygame.K_DOWN:
                move_y = 1
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                move_x = 0
            elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                move_y = 0

    # Calculate angle and movement distance            
    angle = math.atan2(move_y, move_x)
    move_distance = 5

    # Calculate new coordinates after movement
    player.x += move_distance * math.cos(angle)  
    player.y += move_distance * math.sin(angle)

    # Other code...

This example uses the math library to calculate the angle of the movement vector. Based on the direction keys pressed, we calculate a unit vector (move_x, move_y), then use trigonometric functions to convert it into actual movement distance.

This movement method ensures that the sprite's motion is smoother and more natural. You can adjust the value of move_distance to change the movement speed.

Jump Action

Implementing a jump action is a common requirement in game development. Let's see how to implement this feature in Pygame:

is_jumping = False
jump_count = 10 
jump_speed = 10


while running:
    # Event handling
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                # Start jumping
                is_jumping = True

    # Handle jumping            
    if is_jumping:
        # Calculate new y coordinate
        if jump_count >= 0:
            player.y -= jump_speed
            jump_count -= 1
        else:
            is_jumping = False
            jump_count = 10

    # Other code...

In this example, we defined three variables:

  • is_jumping: a boolean value indicating whether the sprite is currently jumping
  • jump_count: a counter controlling the jump height and falling speed
  • jump_speed: the number of pixels moved per frame during a jump

When the space key is pressed, we set is_jumping to True and start executing the jump logic. During the jump, the sprite's y coordinate is adjusted based on the value of jump_count every frame. When jump_count reduces to 0, the current jump ends.

You can try adjusting the values of jump_speed and jump_count to see what kind of jumping effect it produces.

Collision Detection

Detecting collisions between sprites is a very important feature in games. Pygame provides the sprite.spritecollide() method to simplify this process:

import pygame


player = pygame.Rect(100, 100, 60, 60)


enemies = pygame.sprite.Group()
enemy1 = pygame.Rect(300, 300, 40, 40)
enemy2 = pygame.Rect(500, 200, 60, 60)
enemies.add(enemy1, enemy2)


while running:
    # Detect collisions between player and enemies
    hit_enemies = pygame.sprite.spritecollide(player, enemies, False)

    if hit_enemies:
        # Handle collision event
        print("Collision occurred!")

    # Other code...

This code first defines a player sprite player, and an enemy sprite group enemies. Then in the game main loop, we use sprite.spritecollide to check if player has collided with any sprite in enemies.

If a collision occurs, the hit_enemies list will not be empty, and we can add corresponding logic there, such as printing "Collision occurred!".

You can also pass different parameters to control the behavior of collision detection. For example, setting dopkcall to True will automatically call each sprite's callback function upon collision.

Scene Switching

A complete game usually consists of multiple scenes, such as the main menu, game interface, end screen, etc. We can use different functions to represent and manage these scenes:

def main_menu():
    # Menu interface code

def game_scene():
    # Game interface code 

def game_over():
    # End screen code


scene = main_menu

while running:
    scene()

    # Event handling
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RETURN:
                # Press Enter to switch to game scene
                scene = game_scene

    # Other game logic...

In the example above, we defined three scene functions: main_menu, game_scene, and game_over. They represent the game's main menu, game interface, and end screen respectively.

In the main loop, we use a variable scene to store the function reference of the current scene. Each loop calls scene() to execute the code of the current scene.

When the Enter key is pressed, we reassign scene to game_scene, thus switching to the game interface scene. You can add other key detection in the scene assignment statement to achieve seamless switching between scenes.

It's worth mentioning that you can also use an object-oriented approach to organize and manage game scenes by creating a class for each scene.

Adding Sound Effects

Games are incomplete without interesting sound effects! Let's see how to play music and sound effects in Pygame:

import pygame


pygame.mixer.init()


pygame.mixer.music.load("background.mp3")
pygame.mixer.music.play(-1) # Loop playback


jump_sound = pygame.mixer.Sound("jump.wav")
hit_sound = pygame.mixer.Sound("hit.wav")


while running:
    # Event handling 
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                # Play jump sound effect
                jump_sound.play()

    # Collision detection            
    if pygame.sprite.spritecollide(player, enemies, False):
        # Play hit sound effect
        hit_sound.play()

    # Other code...


pygame.mixer.music.stop()

In this example, we first initialize the audio module using pygame.mixer.init(). Then we load the background music file background.mp3 and play it in a loop.

Next, we load two sound effect files jump.wav and hit.wav. When the player presses the space key, the jump sound effect is played; when a collision occurs, the hit sound effect is played.

Finally, we need to stop playing the background music before the game exits.

You can try replacing these with your favorite music and sound effect files. Remember to put the files in the same directory as your Python script. If you want to adjust the volume, you can set pygame.mixer.music.set_volume() or pygame.mixer.Sound.set_volume() before playing.

Summary and Outlook

Through the examples above, I believe you now have a basic understanding of developing 2D games using Pygame. We've learned how to create windows, draw sprites, implement movement and jumping, detect collisions, switch scenes, and add sound effects.

However, this is just the tip of the iceberg in game development. To create more colorful and rich games, you need to learn more, such as:

  • Loading and displaying image assets
  • Implementing game state and scoring systems
  • Writing game artificial intelligence
  • Handling user input and optimizing performance
  • Saving and loading game data
  • Game publishing and running on multiple platforms

I suggest you start with some simple mini-games, learning while practicing. As you gain experience, you'll gradually master more game development techniques and create more outstanding works.

Finally, I wish you smooth sailing on your Python game development journey! Feel free to ask me any questions you may have. Let's work hard together to become pros in the game industry!

Advanced Python Game Development
Previous
2024-10-15 07:54:28
Python Game Development Fundamentals
2024-10-15 07:54:28
Next
Related articles