Talstra

Talstra

Shifting Focus...

Array

Python

Py Space Invader-Style Game

Estimated reading: 3 minutes 162 views Contributors

Let’s create a simple Space Invaders-style game using Pyglet. In this game, you’ll control a spaceship that can move left and right across the bottom of the window, and you’ll be able to shoot bullets to destroy incoming enemies. This example will focus on smooth and fluid movement for the player’s spaceship, as well as basic shooting mechanics.

Step 1: Setting Up the Game Environment

First, make sure you have Pyglet installed. If not, you can install it using pip:

pip install pyglet

Create a new Python file for your game, such as space_invaders.py.

Step 2: Writing the Game Code

Here’s the complete Python script for the game, including comments to explain each part:

import pyglet
from pyglet.window import key

# Initialize the window
window = pyglet.window.Window(width=800, height=600, caption='Simple Space Invaders')

# Initialize key handler for fluid movement
key_handler = key.KeyStateHandler()
window.push_handlers(key_handler)

# Load player ship image and create sprite
player_image = pyglet.resource.image('player.png')
player = pyglet.sprite.Sprite(img=player_image, x=window.width//2, y=30)
player.speed = 200  # speed in pixels per second

# Initialize list to keep track of bullets
bullets = []
bullet_image = pyglet.resource.image('bullet.png')

# Handle drawing everything on the screen
@window.event
def on_draw():
    window.clear()
    player.draw()
    for bullet in bullets:
        bullet.draw()

# Update the game state
def update(dt):
    # Player movement
    if key_handler[key.LEFT]:
        player.x = max(0, player.x - player.speed * dt)
    if key_handler[key.RIGHT]:
        player.x = min(window.width - player.width, player.x + player.speed * dt)

    # Update bullet positions
    for bullet in bullets:
        bullet.y += 300 * dt  # move the bullet upwards
        if bullet.y > window.height:  # remove off-screen bullets
            bullets.remove(bullet)

# Function to handle shooting
def on_key_press(symbol, modifiers):
    if symbol == key.SPACE:
        # Create a new bullet
        bullet = pyglet.sprite.Sprite(img=bullet_image, x=player.x + player.width//2, y=player.y + player.height)
        bullets.append(bullet)

window.push_handlers(on_key_press)

# Schedule updates
pyglet.clock.schedule_interval(update, 1/60.0)  # 60 times per second

# Run the game
pyglet.app.run()

Explanation of the Game Code

  1. Window and Resource Initialization: Sets up the game window and loads resources (images for the player ship and bullets).
  2. Player Initialization: Creates a sprite for the player ship. The ship’s speed is set for fluid movement.
  3. Bullet Management: Implements functionality to create and manage bullets, allowing them to move up the screen and removing them when they go off-screen.
  4. Event Handling:
  • on_draw(): Clears the window and draws the player and all bullets.
  • update(dt): Updates the position of the player and bullets. It uses the dt parameter to ensure frame rate-independent movement.
  • on_key_press(): Handles spacebar presses to shoot bullets.
  1. Fluid Movement: Uses key.KeyStateHandler to check if keys are pressed each frame, allowing for smooth and responsive movement.

Running Your Game

  • Save the above code in space_invaders.py.
  • Make sure you have the images (player.png and bullet.png) in the same directory as your script or adjust the path in the code.
  • Run the script from your terminal or command prompt:
python space_invaders.py

This simple game demonstrates how to handle basic gameplay mechanics like movement and shooting in a Pyglet game. It provides a good foundation for adding more complex features such as enemy waves, scoring, and more advanced graphics.

Share this Doc

Py Space Invader-Style Game

Or copy link

CONTENTS
Chat Icon Close Icon