
Pygame Zero: Creating games without boilerplate - dvfjsdhgfv
https://pygame-zero.readthedocs.io/en/stable/index.html
======
electronstudio
I have been using this to teach kids to code. I have compiled some of the
material I created into a book: [https://github.com/electronstudio/pygame-
zero-book](https://github.com/electronstudio/pygame-zero-book)

I have also been working on a similiar but 3d library:
[https://github.com/electronstudio/richlib](https://github.com/electronstudio/richlib)

~~~
aoloe
i've skimmed through it: very nice book!

one thought: after having read your introduction for the teachers, i wonder
why you did not "sort it" the other way round: first the hands on and the
tutorials and then the theory...

for our coderdojo we went for a "cards" approach:

[https://github.com/CoderDojoZH/resources/tree/master/cards-p...](https://github.com/CoderDojoZH/resources/tree/master/cards-
python/mu-pgzero)

we suggest the kids to first do the pong game in scratch (we have a booklet
with step by step instructions) and then use the set of cards (in order) to do
the same. we try to avoid that they just copy the snippets line by line,
without thinking at what they are doing...

i will now give them a link to your book when they want to learn about python!

------
acbart
I'm very interested in this project, because I have a student researching what
good options there are for Python Game Dev at the CS1 level. We used Arcade[1]
this past Fall, and things didn't go very well (I'm not sold on Pyglet, and
there was a lot of small "What??" issues with Arcade's design itself). Pygame
Zero is a very appealing choice, but suffers from its design around global
state - which is something I spend most of the semester railing against. The
authors gave me a good explanation for why[2], but it still is a deal-breaker
for an introductory-level university course for CS majors.

At this point, we're leaning towards making our own library to satisfy our
purposes. We're still looking at other options though - hey, if you have one,
feel free to suggest it :)

[1] [http://arcade.academy/](http://arcade.academy/)

[2]
[https://github.com/lordmauve/pgzero/issues/174](https://github.com/lordmauve/pgzero/issues/174)

~~~
nneonneo
OK, so I'm genuinely confused about what your objection to global state is.
You mention issues with assignment, and so on - those are issues with Python
`globals` and variables in the global namespace, not issues with global state
per se. A lot of Python programs use global variables in the form of imports,
so I don't see anything wrong here. (Pygame Zero's implicit imports could be a
point of objection - but it'd be very easy to hack a small wrapper to force
students to import the names they need instead).

In terms of global state, I don't see much of a distinction between Pygame
Zero's globals and a god-singleton like `World`. Both feature large amounts of
implicit state, just off by one layer of indirection. For the vast majority of
games, it wouldn't make sense to have more than one `World`. You might want
more than one game scene/level/etc. but that's distinct from the overall
windowing system, graphics state, etc. which would be stored in `World`.

~~~
chronial
> However, a major concern I have for this architecture from a pedagogical
> perspective is it's reliance on the global namespace.

Their concerns are not specific to pygame. They are trying to teach their
students to not have global state and are afraid that using pygame in its
current form would undermine those teachings.

~~~
bvrmn
There is no difference between OS level global state and framework level
global state. Students and teacher are free to create clean abstractions on
top of any global state. Why are we tolerable to OS boundary and not tolerable
to in-process API boundary?

~~~
foota
Because we have to accept the OS global state?

~~~
bvrmn
These are made up rules in your head. If you can deal with OS global state,
you can deal with any global state and keep clean BL.

------
archgoon
There isn't that much boilerplate with pygame (I've taught middleschool
students pygame in the past); I'm not sure if it makes sense to move things
into a framework, and have a lot of configuration by convention, when the goal
is education.

~~~
ggggtez
I agree. Simply setting a magic global variable WIDTH and HEIGHT doesn't
provide any insight, and confuses things more.

There is no logical reasoning why those two variables are globals, and what
other globals might have special behavior.

~~~
jibe
I don't think there is much downside in starting with the good stuff (placing
and moving pixels). You can, and will eventually expose more of the cruft as
needed. But if you lose a students on day 1 because you spending the day
configuring instead of creating, you may never get it back.

~~~
ggggtez
You have to take a step father to argue that _this_ framework is better than
just using boilerplate.

If you need magic variables, you haven't actually fixed the boilerplate
problem.

~~~
kragen
Possibly you've made it worse: defining the wrong magic variable will pass
silently, as I argue in
[https://news.ycombinator.com/item?id=22156525](https://news.ycombinator.com/item?id=22156525),
while misspelling the name of display.set_mode will give you a traceback that
tells you where the problem is. Of course most people didn't get into
programming because they got excited about reading error messages...

~~~
ducaale
Actually pygame zero warns you if it detects that you have mispelled. For
example of you use width, it will suggest that you use WIDTH. If you write
onmousedown instead of on_mouse_down() it will also catch that and warn you.

~~~
kragen
Cool! So you have to get really far off before it doesn't notice?

------
blondin
the problem with teaching programming is bigger than boiler plate code to be
honest. but what the author is doing is really appreciated!

i feel like the abstraction is leaky though. why the person you are shielding
from the boiler plate has to write on_mouse_down, on_mouse_up,
clock.schedule_unique?!

the problem with teaching programming is that people are given user interfaces
that hide the fact that you "actually make your computer or phone do stuff".
at least that's what i think the bigger issue is.

back then when i discovered i could make the computer do things, i'd spent
hours in the QBasic online manual, discovering new things i can show people.

~~~
zeta0134
While I can certainly appreciate a desire to get down in the nuts and bolts of
a programming problem, and really _understand_ what you're doing, I don't
think that's required to spark the joy of learning in a new student. No, for
video games in particular, what seems to work most consistently is rapid
iteration. How fast can the student go from idea in their head to their
character doing that behavior on screen? That core loop is _fascinating_ to a
youngster, who immediately begins to piece together how Mario might run and
jump, or a race car might move along a track, almost entirely on their own.

To that end, there's a certain value in declaring that, "You know what, PyGame
Zero's event loop is probably fine. Let it sweat the details, and we'll worry
about writing the character.jump() function next." Another framework I love
that works this way is Love2D, which targets Lua but has a similar approach:

[https://love2d.org/](https://love2d.org/)

Sure it's not suitable for any project of decent complexity, but there's a
reason we keep reaching for it during Ludum Dares, and any time we want to
rapidly prototype an idea. It takes the least amount of effort of any tool I
know to go from concept to prototype, and get the idea in playtesters hands so
we know if it's worth doing properly. Getting to do that in Python sounds
awesome, so kudos all around; this is neat stuff.

~~~
Kwantuum
Depends on what you mean by decent complexity:

[https://lk-games.itch.io/citizen-of-nowhere](https://lk-
games.itch.io/citizen-of-nowhere)

This game is made using love2d

------
nnq
Can this target mobile platforms, eg. Android or iOS? Otherwise it's a non
starter, the kind of games a beginer could easily make mostly only make sense
as mobile games...

~~~
dvfjsdhgfv
have a look at Love2D. Although it's Lua rather than Python, it's quite
similar, and you have a bit more distribution options:

[https://news.ycombinator.com/item?id=11633278](https://news.ycombinator.com/item?id=11633278)

The docs are a mess though.

~~~
anonymoushn
Did you mean to link to "A word about why Pinboard was not included?"

~~~
dvfjsdhgfv
Ah sorry, yes, wrong thread, can't edit it now. I meant the following link:

[https://love2d.org/wiki/Game_Distribution](https://love2d.org/wiki/Game_Distribution)

------
dang
A small thread from 2015:
[https://news.ycombinator.com/item?id=9634296](https://news.ycombinator.com/item?id=9634296)

------
kragen
Boilerplate is of course detestable, but PyGame is already pretty low in
boilerplate. [https://github.com/kragen/pyconar-
talk/blob/master/helloneg1...](https://github.com/kragen/pyconar-
talk/blob/master/helloneg1.py) is five lines of code plus the shebang:

    
    
        #!/usr/bin/python
        from pygame import *
        pantalla = display.set_mode((0, 0), FULLSCREEN)
        draw.rect(pantalla, 128, (50, 100, 200, 400))
        display.flip()
        time.delay(2000)
    

Admittedly this is rather daunting compared to

    
    
        print("hello, world")
    

but the benefits of the extra code are rather more immediate than those of
public static void main: you can control whether your window is fullscreen or
not, what size it is, when the screen updates, and how long the program runs
before exiting.

When I see things like this,

> _Your alien should now be appearing on screen! By passing the string 'alien'
> to the Actor class, it automatically loads the sprite,_

I shudder. (That's in [https://pygame-
zero.readthedocs.io/en/stable/introduction.ht...](https://pygame-
zero.readthedocs.io/en/stable/introduction.html#draw-a-sprite.)) When you
write a program and it _doesn 't_ load your sprite, how do you figure out why
not? Maybe you called your sprite file images/alien.PNG or Images/alien.png or
images/alien.jpeg or ./alien.png, and Pygame Zero doesn't happen to look in
those places? I think you're going to have to resort to either trying things
at random or using strace. Similarly, how hard is it to debug Pygame Zero
displaying your window at the wrong size if you write HIEGHT = 300 instead of
HEIGHT = 300?

In that talk I did eventually get around to drawing sprites, but it wasn't
until one of the later examples, [https://github.com/kragen/pyconar-
talk/blob/master/reloj.py](https://github.com/kragen/pyconar-
talk/blob/master/reloj.py). The relevant code is

    
    
        imagen = image.load('trashcan_empty.png')
        ...
            pantalla.blit(imagen, (xx, yy))
    

(The talk was for a Spanish-speaking audience; "imagen" is Spanish for
"image", and "pantalla" for "screen".) So that's what you're saving yourself
when you say

    
    
        alien = Actor('alien')
        alien.pos = 100, 56
        ...
            alien.draw()
    

But I don't have a lot of experience teaching kids to code, so maybe my
intuitions about what makes things harder and what makes them easier are not
well-founded. I'd be interested to hear other people's experiences of the
kinds of errors beginners make and what kinds of interface design work best
for them.

With Yeso, things are slightly more complicated than with PyGame;
[https://gitlab.com/kragen/bubbleos/blob/master/yeso/yv.py](https://gitlab.com/kragen/bubbleos/blob/master/yeso/yv.py)
similarly opens a window and displays a PNG in it:

    
    
        import sys
    
        import yeso
    
    
        if __name__ == '__main__':
            image = yeso.read_png(sys.argv[1])
            if image:
                with yeso.Window(sys.argv[1], image.size) as w:
                    with w.frame() as f:
                        f.copy(image)
                    while True:
                        w.wait()
    

However, I'd argue that this interface is somewhat less error-prone than
PyGame's; a common error I've had when starting new PyGame programs is
forgetting to call pygame.display.flip(), which has the delightful symptom
that whatever I've drawn just doesn't appear on the screen. By using a context
manager, the Yeso Python binding avoids that error. As the comments point out,
you can reduce yv.py to the following six lines of code if you depend on
CPython's prompt finalization to flip buffers:

    
    
        #!/usr/bin/python
        import yeso, sys
        _, n = sys.argv
        p = yeso.read_png(n)
        w = yeso.Window(n, p.size)
        w.frame().copy(p)
        while True: w.wait()
    

Yeso is still in its early stages, and I might change this interface a little
bit, but I don't see why things need to be any more complicated than this for
simple GUI programs. And my intuition is that making the interface less
explicit makes it worse, _for experienced programmers_.

Proce55ing and Arduino offer at least some evidence that at least the
setup()/draw()/mousemove() scaffolding is a significant help to beginners;
they can get a moving object on the screen or a flashing LED before they have
to know what a loop is, and the default behavior you have in Python or C of
closing the window (for GUI programs) or restarting the firmware (for embedded
programs) is not a good default.

~~~
pierrebai
In the example code for pygame you give, what happens if there is a single
typo? It doesn't work either and you probably get an incomprehensible stack
trace.

There is no benefit to teh extra code because that extra code is magic
gibberish. It's an incantation that somehow makes things work.

~~~
kragen
From my point of view, an incomprehensible stack trace is a big improvement
over silently failing to work, because then you learn to comprehend the stack
trace and you can fix the error. This is one of the central design principles
of Python, rooted in experience with teaching beginners to program in the ABC
teaching language.

The extra code is not actually magic gibberish, although it does appear that
way at first. In Python you can comment out individual lines and observe the
effect, change the parameters, or type

    
    
        >>> from pygame import *
        >>> help(display.flip)
    

Although an IDE may make that easier, and of course you don't start out
knowing that.

What is your experience teaching beginners to program? What tools did you have
them use, and what did they have the most difficulty with?

------
sails
This looks really great!

A somewhat related video that your docs reminded me of, "Bret Victor -
Inventing on Principle" [], which I think is a really interesting take on
inventing and learning. Perhaps some useful thoughts for your principles
section.

[][https://vimeo.com/36579366](https://vimeo.com/36579366)

------
tony
Incredible!

The sphinx docs look great. Also, the logo! Not to mention, the translations:

\- [https://pygame-zero.readthedocs.io/zh_CN/latest/](https://pygame-
zero.readthedocs.io/zh_CN/latest/)

\- [https://pygame-zero.readthedocs.io/ja/latest/](https://pygame-
zero.readthedocs.io/ja/latest/)

\- [https://pygame-zero.readthedocs.io/sk/latest/](https://pygame-
zero.readthedocs.io/sk/latest/)

One reason of why I wouldn't use it yet: LGPL.

This is the issue pygame had when I tried it. The license made it very
difficult to incorporate and use in practice, and I ended up playing with kivy
instead ([https://github.com/kivy/kivy](https://github.com/kivy/kivy)). The
reasons why:

1\. Writing anything commercial would be a gamble. I've wrote at length on why
this license isn't meant for scripting languages, but even if it's a compiled
language, SDL moved away from LGPL here:
[https://youtu.be/MeMPCSqQ-34?t=430](https://youtu.be/MeMPCSqQ-34?t=430).

2\. LGPL and scripting languages just don't work from an open source
perspective. It's not copy-paste and vendorize friendly. Functions can't be
copied a la carte. I'd rather write something from scratch than link an LGPL
library in one of my MIT licensed projects. I'm just not willing to open
downstream users to the risk. What ends up happening is 5/10 years on, someone
ends up writing a new MIT/BSD library to get around a viral one (e.g. GCC ->
Clang/LLVM).

~~~
_carl_jung
Do you have any links for the implications for commercial use? If I released a
game made with PyGame, what's the gamble? I've seen examples of people using
it commercially [0].

[0]
[https://www.reddit.com/r/gamedev/comments/16d5ak/is_pygame_o...](https://www.reddit.com/r/gamedev/comments/16d5ak/is_pygame_or_any_other_python_gamedev_library/c7uz2y6?utm_source=share&utm_medium=web2x)

~~~
tony
pygame has successful deployments onto steam, but it doesn't show us
developers that would have used for pygame if it wasn't for licensing
concerns.

LGPL in scripting languages is a gray area. There are no previous legal cases
to cite. Python projects have transferred away from LGPL due to its ambiguity.
Example dating back to 2004: [https://twistedmatrix.com/pipermail/twisted-
python/2004-May/...](https://twistedmatrix.com/pipermail/twisted-
python/2004-May/007946.html)

Namely around the language of what creates a derivative / combined work:

LGPL was intended for languages that use header files, like C and C++. So, if
a project was ever accused of creating a combined work, they'd be on the hook
to defend the the case, whether or not a combined work is created. In v2, the
license even shifts the question onto licensee/licensor: "The threshold for
this to be true is not precisely defined by law."

In licenses such as BSD/MIT/ISC/etc. these issues do not arise, and a breeze
through top python projects show reciprocal contributions and access to source
are commonplace without viral clauses in licenses.

I write about LGPL/python at length before here (2013):
[https://github.com/ScottDuckworth/python-
anyvcs/issues/32#is...](https://github.com/ScottDuckworth/python-
anyvcs/issues/32#issuecomment-28528142) and (2016)
[https://github.com/PyGithub/PyGithub/issues/468#issuecomment...](https://github.com/PyGithub/PyGithub/issues/468#issuecomment-252437234)

For gaming, it's even more relevant, because if the deployment is to steam or
a mobile phone (like what kivy does with [https://github.com/kivy/python-for-
android](https://github.com/kivy/python-for-android)), that could easily be
interpreted as a combined work. They're not like C/C++ application linking to
.so / shared libraries.

~~~
_carl_jung
So there are numerous deployments of "successful" games using PyGame, and no
court cases by the creators/maintainers of PyGame towards those game
developers? I'll take my chances.

I don't see what PyGame's motivation would be to open such cases.

