← Games with microStudio

Keys and movement

Check the arrow keys in update() and move a paddle, keep it on the screen, then make a player that moves four ways and speeds up.

A game asks the keyboard a question 60 times a second: is the left arrow down right now?

In the turtle course, pressing a key called a function once. A game engine works the other way round: every frame, update() asks whether a key is down, and moves a little if it is. Hold the key and it moves smoothly; let go and it stops.

pressed("LEFT") is a short helper at the top of the game: it is true while that key is down. Copy it as it is into every game (why it is needed is in Investigate).

PredictRead the code and say what it will do before you run anything. A wrong guess is fine: it shows you what to look for.

Predict

game.py
def pressed(key):
    return hasattr(keyboard, key) and keyboard[key] != 0

def init():
    global px
    px = 0

def update():
    global px
    if pressed("LEFT"):
        px -= 2
    if pressed("RIGHT"):
        px += 2

def draw():
    screen.clear("rgb(10,10,40)")
    screen.fillRect(px, -80, 24, 6, "rgb(100,200,255)")

How many times does update() run while you hold the key?

You hold the right arrow for one second. What happens to the paddle?

RunRun it and compare the result with your prediction.

Run

Click the game, then hold the arrow keys. Then put this code in your microStudio project (a new project, or replace the code in last lesson's) and run it there.

game.py
def pressed(key):
    return hasattr(keyboard, key) and keyboard[key] != 0

def init():
    global px
    px = 0

def update():
    global px
    if pressed("LEFT"):
        px -= 2
    if pressed("RIGHT"):
        px += 2

def draw():
    screen.clear("rgb(10,10,40)")
    screen.fillRect(px, -80, 24, 6, "rgb(100,200,255)")
    screen.drawText("px = " + str(px), 0, 80, 10, "#FFF")
Play itClick the game to play. Make your own on microstudio.dev.

InvestigateTrace how each line of code connects to what you see.

Investigate

game.py
def pressed(key):
    return hasattr(keyboard, key) and keyboard[key] != 0

def init():
    global px
    px = 0

def update():
    global px
    if pressed("LEFT"):
        px -= 2
    if pressed("RIGHT"):
        px += 2

def draw():
    screen.clear("rgb(10,10,40)")
    screen.fillRect(px, -80, 24, 6, "rgb(100,200,255)")
    screen.drawText("px = " + str(px), 0, 80, 10, "#FFF")

Four frames, one at a time.

Which number is the speed?

Why the helper is there.

px starts at 0. Fill in px after each frame.

framekey downpx
1RIGHT2
2RIGHT
3none
4LEFT

How would you make the paddle move faster?

This looks right, but it stops with AttributeError: no attribute 'LEFT' before any key is pressed. Click the line where it goes wrong.

ModifyChange the code on purpose and check the result.

Modify

game.py
def pressed(key):
    return hasattr(keyboard, key) and keyboard[key] != 0

def init():
    global px
    px = 0

def update():
    global px
    if pressed("LEFT"):
        px -= 2
    if pressed("RIGHT"):
        px += 2

def draw():
    screen.clear("rgb(10,10,40)")
    screen.fillRect(px, -80, 24, 6, "rgb(100,200,255)")
    screen.drawText("px = " + str(px), 0, 80, 10, "#FFF")

Hold the right arrow for a while: the paddle disappears off the edge. Make it stop at both edges. The game on this page does.

Need a hint?

After moving, check the edges: if px > 90, set it back to 90.

Another hint

Do the same for the left edge: if px < -90, px = -90.

Make the up and down arrows move the paddle too.

Need a hint?

Add a second variable, py, for the height. Start it at -80 and draw the box at (px, py).

Another hint

UP adds to py and DOWN takes away (y goes up the screen). Put py in both global lines.

Play itClick the game to play. Make your own on microstudio.dev.

MakeBuild something new using what you have learned. Expect a few tries; that is normal.

A player that moves

Make a player you can move all four ways, then add one thing of your own: a key that makes it go faster, a different colour when it is moving, wrapping round to the other side at the edges... Key names include "SPACE", "ENTER" and letters such as "Q" ("LEFT" and the other arrows also work with W, A, S and D). The game on this page goes fast while you hold Space.

game.py
def pressed(key):
    return hasattr(keyboard, key) and keyboard[key] != 0

def init():
    pass

def update():
    pass

def draw():
    screen.clear("rgb(10,10,40)")
Play itClick the game to play. Make your own on microstudio.dev.

Info

Where this leads

Asking every frame is called polling; MakeCode and Godot can do both, polling and events. Next: lots of stars falling at once, each one an object.

A player should jump once when Space is pressed, not keep jumping while it is held. Why does pressed("SPACE") alone not do this?

For teachers

Students check the arrow keys every frame in update() to move a paddle, trace its position frame by frame, find why keyboard.LEFT fails before a key is pressed, keep the paddle on the screen, add up and down, and make a player with an extra key of their own. About 50 minutes.

Open the teacher guide: answers, solutions, slides and a worksheet.

Students will be able to

Before class

Read the unit primer first. pressed(key) is a recipe: two lines students copy into every game. It is needed because microStudio's keyboard has no LEFT until the first key press, so keyboard.LEFT fails at the start (the bug task); hasattr(keyboard, key) asks first. Students need not understand hasattr yet. In microStudio the arrow names also answer to W, A, S and D. Games on our page need a click before they get the keys; so does the game in microStudio's run window.

Running the lesson

  1. Predict: ask how many times update() runs in one second, then how far 2 steps each time adds up to.
  2. Investigate: fill in the trace table on the board; ask what a frame with no key does.
  3. Modify: ask where the edge check goes: before or after the move? (after).
  4. Make: let pairs test each other's player and name the extra key.

The hard part (on purpose)

Thinking in frames: a key held for a second is 60 small moves. The trace table is the moment to slow down.

When students get stuck

Stretch and support

Stretch: Make the paddle wrap round to the other side at the edges, or give it a short dash on Space that only works every few seconds.

Support: Give the edge check for the right side and ask students to write the left one.

Where it leads

Next lesson: falling stars as objects, which they have already made with turtles. Polling (asking every frame) and events (a function called on a key) are the two ways every engine reads keys.

What each step is for

Now you can
Next lesson3. Stars as objectsBring the Star class from Objects with turtles into a game engine: each star moves itself in update() and draws itself in draw(). Change colours and numbers, then add a class of your own.