Graphics and Games with Pyctures
Pyctures ("Python pictures") draws 2D and 3D graphics from a Python file. You write a function called draw(), and it is called every frame, about sixty times a second. Change what it draws a little each time and the picture moves. That is how every game works.
Pyctures is a free, open-source library. It is built into Circuitry, and the same programs run with the library on your own computer: see Use your scenes outside Circuitry.
Who this is for
A school or college student who has written a few lines of Python, perhaps with turtle, and wants to make pictures that move and games that answer the keyboard. It also suits a complete beginner who would rather start with a game.
What you need
- Circuitry in a web browser, in the desktop app, or on an iPad or a phone.
- Nothing to install. There is no
importline to write either.
Your first program
Make a Python file ( → Code → Python) and type or paste this:
x = 0
def update(dt):
global x
x += 120 * dt # 120 points every second
if x > width + 30: # off the right edge: back to the left
x = -30
def draw():
background("midnightblue")
circle(width - 90, 90, 45, "gold") # the moon
rect(0, height - 70, width, 70, "seagreen") # the ground
circle(x, height - 95, 25, "tomato") # the ball
text("Hello, Pyctures", 20, 40, "white", 24)
A file that draws starts by itself, about half a second after you stop typing. Run in the footer starts it again, and the same button is Stop while it runs.
What you should see
A dark blue sky with a gold moon, green ground, the words Hello, Pyctures, and a red ball that rolls along the ground from left to right, then comes round again.
draw()paints the whole picture, every frame.update(dt)is called just before it.dtis the time since the last frame, in seconds, so120 * dtis 120 points a second on every screen.widthandheightare the size of the preview, so the picture fits whatever shape the preview is.global xlets the function change thexmade at the top of the file.
Three things to try
- Faster. Change
120to400. - Your own colours. Change
"gold"to"white"and"midnightblue"to"skyblue". There are about 140 colour names: see Colours. - Steer it. Replace the three lines inside
updateafterglobal xwith these, click the preview so it has the keyboard, and use the arrow keys:
if "ArrowLeft" in keys: x -= 300 * dt
if "ArrowRight" in keys: x += 300 * dt
Coming from pygame
Circuitry has no pygame. A program written for it has to be rewritten, and the shape is close: the loop that pygame makes you write is update(dt) and draw() here, the event queue is keys and mouse, and a sprite is a Sprite.
Where to go next
- Pyctures: Python 2D and 3D graphics: the next three steps, including a small game with sprites.
- Tutorials: a bouncing ball, a simple game, Space Rocks and a spinning 3D cube.
- How a program is shaped and the function index.
- Debugging: errors you can tap, printing, breakpoints and the frame rate.
- Maths animations with Pymations: the next path.