Pyglet Circle Movement with Arrow Keys

  • Share this:

Code introduction


This code creates a Pyglet window and draws a colored circle that can be moved around the window using the arrow keys.


Technology Stack : Pyglet

Code Type : Pyglet Graphics Programming

Code Difficulty : Intermediate


                
                    
import pyglet
from pyglet.window import key

def draw_circle(window, x, y, radius, color=(255, 255, 255)):
    """Draw a circle in the window at the specified position and radius with a given color."""
    gl = pyglet.gl
    gl.glBegin(gl.GL_TRIANGLE_FAN)
    gl.glColor3f(*color)
    gl.glVertex2i(x, y)
    for i in range(0, 360, 10):
        angle = i * 3.141592653589793 / 180.0
        gl.glVertex2f(x + int(radius * cos(angle)), y + int(radius * sin(angle)))
    gl.glEnd()

window = pyglet.window.Window(800, 600)
pyglet.gl.glClearColor(0, 0, 0, 1)
player_x, player_y = 400, 300
player_radius = 50
player_color = (255, 0, 0)

@window.event
def on_draw():
    window.clear()
    draw_circle(window, player_x, player_y, player_radius, player_color)

@window.event
def on_key_press(symbol, modifiers):
    if symbol == key.LEFT:
        player_x -= 10
    elif symbol == key.RIGHT:
        player_x += 10
    elif symbol == key.UP:
        player_y -= 10
    elif symbol == key.DOWN:
        player_y += 10

pyglet.app.run()                
              
Tags: