Pyglet Window with Arrow-Key Controlled Ball

  • Share this:

Code introduction


This code defines a Pyglet window with a ball that can be moved with the arrow keys.


Technology Stack : Pyglet, Sprite, Image

Code Type : Pyglet Game

Code Difficulty : Intermediate


                
                    
import pyglet
from pyglet.window import key
from pyglet.window import Window

def create_moving_ball(window):
    # Create a ball image
    ball = pyglet.sprite.Sprite(pyglet.image.load('ball.png'))
    ball.position = window.width // 2, window.height // 2
    window.push_handlers(on_key_press)

    def on_key_press(symbol, modifiers):
        if symbol == key.LEFT:
            ball.x -= 10
        elif symbol == key.RIGHT:
            ball.x += 10
        elif symbol == key.UP:
            ball.y -= 10
        elif symbol == key.DOWN:
            ball.y += 10

    pyglet.app.run()