Pyglet Game: Player Movement with A and D Keys

  • Share this:

Code introduction


This code creates a simple game window using Pyglet, where the player can move left by pressing the 'A' key and right by pressing the 'D' key.


Technology Stack : Pyglet

Code Type : Game window creation and interaction

Code Difficulty : Intermediate


                
                    
import pyglet
from pyglet.window import key

def create_game_window():
    # Create a window
    window = pyglet.window.Window()

    # Set the window title
    window.set_title('Pyglet Game')

    # Create a text label
    label = pyglet.text.Label('Press A or D to move',
                              font_name='Arial',
                              font_size=36,
                              color=(255, 255, 255, 255),
                              x=window.width//2,
                              y=window.height//2)

    # Set the initial position of the player
    player_x = window.width//2
    player_y = window.height//2

    # Move the player left or right
    def on_key_press(symbol, modifiers):
        if symbol == key.A:
            player_x -= 10
        elif symbol == key.D:
            player_x += 10
        # Keep the player within the window bounds
        player_x = max(0, min(player_x, window.width - 50))

    # Add event handler for key presses
    window.on_key_press = on_key_press

    # Update the game window
    def update(dt):
        label.x = player_x
        label.y = player_y

    pyglet.clock.schedule_interval(update, 1/60.0)

    # Run the game
    pyglet.app.run()                
              
Tags: