Skip to main content

Pygame Toolbox for Beginners by Petlja

Project description

PygameBg is a small Python package aimed to reduce boilerplate code in simple Pygame programs, primarily initialization code and main loop.

PygameBg should make Pygame learning curve more gradual for beginner programmers, but without losing focus from the pure Pygame API.

When we compare Python with C-like programming languages, one of the positive features we usually mention is a single line “Hellow World!” example:

print('Hellow World!')

Pygame is not pythonic enough here. A proper “Draw circle” program looks like:

import pygame as pg

pg.init()
surface = pg.display.set_mode((400,400))
pg.display.set_caption("Blue circle")

pg.draw.circle(surface, pg.Color("blue"), (200,200), 100)

pg.display.update()
while pg.event.wait().type != pg.QUIT:
    pass
pg.quit()

The central line of code in this example is:

pg.draw.circle(surface, pg.Color("blue"), (200,200),100)

We could say that the first three lines (excluding import) opens a window, and the last four lines waits for user to quit, but we would not like to burden beginners with details of those boilerplate statements.

Here is an equivalent example that use PatljaBg:

import pygame as pg
import pygamebg

surface = pygamebg.open_window(400, 400, "Blue circle")

pg.draw.circle(surface, pg.Color("blue"), (200,200), 100)

pygamebg.wait_loop()

This is much more readable first example for beginners and easier to explain: We open window, then draw blue circle and then wait for user to quit.

Besides wait_loop, PygameBg supports frame_loop and event_loop.

Here is example that use frame_loop:

import pygame as pg
import pygamebg

surface = pygamebg.open_window(300, 300, "Read keyboard state")

x, y = 150, 150

def update():
    global x, y
    surface.fill(pg.Color("white"))
    pressed = pg.key.get_pressed()
    if pressed[pg.K_RIGHT]:
        x += 1
    if pressed[pg.K_LEFT]:
        x -= 1
    if pressed[pg.K_DOWN]:
        y += 1
    if pressed[pg.K_UP]:
        y -= 1
    pg.draw.circle(surface , pg.Color("red"), (x, y), 30)

pygamebg.frame_loop(30, update)

So, frame loop calls update function once per frame and may optionally call an event handler:

import pygame as pg
import pygamebg

width, height = 500, 300
surface = pygamebg.open_window(width, width, "Increasing and decreasing speed")
pg.key.set_repeat(10,10)

fps = 30
x, y = 150, 150
vx, vy = 0, 0

def update():
    global x,y
    x = (x + vx/fps) % width
    y = (y + vy/fps) % height

    surface.fill(pg.Color("white"))
    color = pg.Color("red")
    pg.draw.circle(surface, color, (int(x), int(y)), 30)

def handle_event(d):
    global vx, vy
    if d.type == pg.KEYDOWN:
        if d.key == pg.K_RIGHT:
            vx += 1
        elif d.key == pg.K_LEFT:
            vx -= 1
        elif d.key == pg.K_DOWN:
            vy += 1
        elif d.key == pg.K_UP:
            vy -= 1

pygamebg.frame_loop(fps, update, handle_event)

We can also use a dictionary argument to specify event handlers for specific event types:

def keydown(e):
    global vx, vy
    if e.key == pg.K_RIGHT:
        vx += 1
    elif e.key == pg.K_LEFT:
        vx -= 1
    elif e.key == pg.K_DOWN:
        vy += 1
    elif e.key == pg.K_UP:
        vy -= 1

pygamebg.frame_loop(fps, update, {pg.KEYDOWN: keydown})

Frame loop can handle events, but it is always frame driven: it updates on each frame and handles pending events before each update.

A pure event loop handles events immediately when they occurred and triggers repaint when needed (when an event handler returns True):

import pygame as pg
import pygamebg

surface = pygamebg.open_window(500, 500, "Keyboard and mouse events")
pg.key.set_repeat(10,10)

x, y = 150, 150

def handle_event(e):
    global x, y
    if e.type == pg.MOUSEBUTTONDOWN:
        x,y = e.pos
        return True
    if e.type == pg.KEYDOWN:
        if e.key == pg.K_RIGHT:
            x += 1
        elif e.key == pg.K_LEFT:
            x -= 1
        elif e.key == pg.K_DOWN:
            y += 1
        elif e.key == pg.K_UP:
            y -= 1
        else:
            return False
        return True
    return False

def paint():
    surface.fill(pg.Color("white"))
    pg.draw.circle(surface, pg.Color("blue"), (x, y), 50)

pygamebg.event_loop(paint, handle_event)

A dictionary argument can also be used to specify event handlers for specific event types:

import pygame as pg
import pygamebg

surface = pygamebg.open_window(500, 500, "Keyboard and mouse events")
pg.key.set_repeat(10,10)

x, y = 150, 150

def clicked(e):
    global x, y
    x,y = e.pos
    return True

def keypressed(e):
    global x,y
    if e.key == pg.K_RIGHT:
        x += 1
    elif e.key == pg.K_LEFT:
        x -= 1
    elif e.key == pg.K_DOWN:
        y += 1
    elif e.key == pg.K_UP:
        y -= 1
    else:
        return False
    return True

def paint():
    surface.fill(pg.Color("white"))
    pg.draw.circle(surface, pg.Color("blue"), (x, y), 50)

pygamebg.event_loop(paint, {pg.MOUSEBUTTONDOWN:clicked, pg.KEYDOWN:keypressed})

Source files of all examples are available here.

How to install PygameBg

Use pip to install PygameBg:

pip3 install pygamebg

If you use Windows and previous command does not work, try:

py -3 -m pip install pygamebg

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

PygameBg-0.9.3.tar.gz (4.0 kB view details)

Uploaded Source

Built Distribution

PygameBg-0.9.3-py3-none-any.whl (4.5 kB view details)

Uploaded Python 3

File details

Details for the file PygameBg-0.9.3.tar.gz.

File metadata

  • Download URL: PygameBg-0.9.3.tar.gz
  • Upload date:
  • Size: 4.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.35.0 CPython/3.7.3

File hashes

Hashes for PygameBg-0.9.3.tar.gz
Algorithm Hash digest
SHA256 840d377c9c4f22b67050af4a0b0e822a12a1cee7ba15997c2be8f4964486f86f
MD5 258d96cabb49569e468bb2f78b5cf3b0
BLAKE2b-256 7bf4b69b351154716decc4b131a0bc5bca339fd5fed70e3f944d9fc9a4758deb

See more details on using hashes here.

File details

Details for the file PygameBg-0.9.3-py3-none-any.whl.

File metadata

  • Download URL: PygameBg-0.9.3-py3-none-any.whl
  • Upload date:
  • Size: 4.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.35.0 CPython/3.7.3

File hashes

Hashes for PygameBg-0.9.3-py3-none-any.whl
Algorithm Hash digest
SHA256 ce9005f38c6c62f2557a4450ed1a438ffb06c2b5df878bc00f642d7495f751f2
MD5 be17bb6f6e6ffb0a1fdb8883a36e29c2
BLAKE2b-256 79b5e8f65113858c097f197ae7c3c58b62fe89e1afd948aa28831680e6366646

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page