Pyglet Circle Movement with Arrow Key Control

  • Share this:

Code introduction


This code uses the Pyglet library to create a window with a colored circle that can move left, right, up, and down. The user can control the direction and speed of the circle using the arrow keys on the keyboard.


Technology Stack : Pyglet

Code Type : Game

Code Difficulty : Intermediate


                
                    
import pyglet
from pyglet.window import key
from pyglet.window.key import KEY_DOWN, KEY_UP
import random

def random_color():
    return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

def move_circle(window, x, y, dx, dy, color):
    window.dispatch_event('on_draw')
    window.clear()
    window.draw_circle(x, y, 50, color=color)
    x += dx
    y += dy
    if x <= 0 or x >= window.width:
        dx = -dx
    if y <= 0 or y >= window.height:
        dy = -dy
    return x, y, dx, dy

def main():
    window = pyglet.window.Window(800, 600, "Pyglet Circle Movement")
    color = random_color()
    x, y = 400, 300
    dx, dy = 5, 5

    @window.event
    def on_draw():
        x, y, dx, dy = move_circle(window, x, y, dx, dy, color)

    @window.event
    def on_key_press(symbol, modifiers):
        if symbol == key.RIGHT:
            dx += 5
        elif symbol == key.LEFT:
            dx -= 5
        elif symbol == key.UP:
            dy -= 5
        elif symbol == key.DOWN:
            dy += 5

    pyglet.app.run()                
              
Tags: