Home >Backend Development >Python Tutorial >How to use PyGame Zero in python
Say goodbye to boring templates with PyGame Zero in your game development process.
Python is a good entry-level programming language. And, games are a great starter project: they are visual, self-driven, and fun to share with friends and family. Although, most libraries written in Python, such as PyGame, will confuse beginners because forgetting tiny details can easily lead to rendering nothing.
Until they understand what all the parts do, they will treat many of them as "mindless template files" -- magical passages that need to be copied and pasted into the program to make it work.
PyGame Zero attempts to bridge this gap by placing an abstraction layer on top of PyGame so it literally doesn't require templates.
The "literal" we are talking about means literally.
This is a qualified PyGame Zero file:
# This comment is here for clarity reasons
We can put it in a game.py
file and run:
$ pgzrun game.py
This will display a window and run a game loop that can be interrupted by closing the window or pressing CTRL-C
.
Sadly, this will be a boring game. Nothing happened.
To make it a little more interesting, we can draw a different background:
def draw(): screen.fill((255, 0, 0))
This will change the background color from black to red. But it's still a boring game where nothing happens. We can make it a little more interesting:
colors = [0, 0, 0] def draw(): screen.fill(tuple(colors)) def update(): colors[0] = (colors[0] + 1) % 256
This will make the window start from black, gradually get brighter, until it turns to bright red, and then back to black, repeating the cycle over and over again. The
update
function updates the values of the parameters, and draw
renders the game based on these parameters.
Even so, there is no way for players to interact with this game. Let's try some other things:
colors = [0, 0, 0] def draw(): screen.fill(tuple(colors)) def update(): colors[0] = (colors[0] + 1) % 256 def on_key_down(key, mod, unicode): colors[1] = (colors[1] + 1) % 256
The above is the detailed content of How to use PyGame Zero in python. For more information, please follow other related articles on the PHP Chinese website!