Pyxel Lesson 01 - Red Light, Green Light
About Red Light, Green Light
#Red Light, Green Light
is an example program to learn Python, using Pyxel.
I first wrote Red Light, Green Light
in MIT Scratch to support teaching programming to kids at my local library. It's mean to be fun while using as few commands as possible.
After you Install Pyxel, you can follow the steps below to create the program.
Step 1: Draw a runner
#Start up the Pyxel
editor:
pyxel edit redlight
Now draw a runner in left window.
Tip: The right window should show a smaller version of your bug drawing, and it should be in the very upper-left corner.
Be sure to press Ctrl+S
to save, before pressing ESC
to exit.
You should now have a file called redlight.pyxres
.
Step 2: Draw a place to run
#Start up the Pyxel
editor:
pyxel edit redlight.pyxres
Click the second icon in the upper-left to switch to the 'Tile Map' window.
Step 3: Copy in the Code
#Open a text editor, and copy the following code into it. Save it as redlight.py
:
import pyxel
from dataclasses import dataclass
@dataclass
class Pixel:
x: int
y: int
color: int
class App:
def __init__(self):
pyxel.init(200, 150, title="Red Light, Green Light")
pyxel.mouse(True)
pyxel.load('redlight.pyxres')
self.runner_x = 0
self.runner_y = 75
pyxel.run(self.update, self.draw)
def update(self):
self.update_runner()
def update_runner(self):
if pyxel.btn(pyxel.KEY_LEFT) or pyxel.btn(pyxel.GAMEPAD1_BUTTON_DPAD_LEFT):
self.runner_x = max(self.runner_x - 2, 0)
if pyxel.btn(pyxel.KEY_RIGHT) or pyxel.btn(pyxel.GAMEPAD1_BUTTON_DPAD_RIGHT):
self.runner_x = min(self.runner_x + 2, pyxel.width - 16)
if pyxel.btn(pyxel.KEY_UP) or pyxel.btn(pyxel.GAMEPAD1_BUTTON_DPAD_UP):
self.runner_y = max(self.runner_y - 2, 0)
if pyxel.btn(pyxel.KEY_DOWN) or pyxel.btn(pyxel.GAMEPAD1_BUTTON_DPAD_DOWN):
self.runner_y = min(self.runner_y + 2, pyxel.width - 16)
def draw(self):
pyxel.cls(6) # Clear the screen to a light grey
pyxel.blt(0, 88, 0, 0, 88, 160, 32)
pyxel.blt(0, 88, 0, 0, 64, 160, 24, 12)
# Print text to tell us where the runner is
pyxel.text(x=3, y=3, s="runner is at: " + str(self.runner_x), col=0)
pyxel.text(x=120, y=140, s="Press ESC to quit.", col=0)
# Draw the runner
pyxel.blt(x=self.runner_x, y=self.runner_y, # draw at runner X,Y
img=0, # From image bank 0
u=0, v=0, w=16, h=16, # Choose pixels 0,0 through 16,16
colkey=0 # Treat color 0 as transparent
)
App()
Step 3: Play Red Light, Green Light
#pxyel run redlight.py
Step 4: Remix!
#Open redlight.py
in your text editor, and change some numbers, save the file, and run the program again so see what changed.
pxyel run redlight.py