This page contains exercise answers and teaching guidance for
Step 3 — Direction & Movement.
Not linked from the student pages.
Students: please go back and try the activities first.
STEP 3 OF 10 · FACILITATOR NOTES
What students will be able to do after Step 3:
if / elif / else chains to handle mutually exclusive conditionspygame.KEYDOWN and pygame.K_UP etc.# Direction as dx, dy offset
dx, dy = 1, 0 # start moving right
# --- Inside the event loop ---
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and dy != 1: # reverse guard
dx, dy = 0, -1
elif event.key == pygame.K_DOWN and dy != -1:
dx, dy = 0, 1
elif event.key == pygame.K_LEFT and dx != 1:
dx, dy = -1, 0
elif event.key == pygame.K_RIGHT and dx != -1:
dx, dy = 1, 0
# --- Update step ---
head_x += dx
head_y += dy
(dx, dy) = (1, 0) means "move 1 cell right, 0 cells up/down." This is cleaner than storing a direction string like "right" — addition gives the new position directly without a lookup table.
pygame.KEYDOWNFired once when a key is first pressed (not held). Using pygame.KEYDOWN for direction changes is correct — pygame.key.get_pressed() returns True every frame while the key is held, which would fire too often.
and dy != 1Prevents UP being pressed when already going DOWN (which would move the head into the neck). Without this guard, the snake can immediately eat itself on the very next frame.
elif not ifWe want only ONE direction change per frame. If all branches were if, pressing two keys simultaneously could cause the snake to process both and end up moving diagonally — which is not possible on a grid.
Students complete a direction-control skeleton using string-based direction ("RIGHT", "DOWN", etc.) and movement math.
| Blank | Hint shown | Correct answer |
|---|---|---|
| 1 | "______ | "RIGHT" — the starting direction |
| 2 | K______ | KEYDOWN — the pygame event constant for a key press |
| 3 | "_____ | "DOWN" — guard: UP is blocked when already going DOWN |
| 4 | "___ | "UP" — guard: DOWN is blocked when already going UP |
| 5 | "______ | "RIGHT" — guard: LEFT is blocked when already going RIGHT |
| 6 | "_____ | "LEFT" — guard: RIGHT is blocked when already going LEFT |
| 7 | _ | - — hy -= 1: UP decrements the y coordinate |
| 8 | _ | + — hy += 1: DOWN increments y |
| 9 | _ | - — hx -= 1: LEFT decrements x |
| 10 | _ | + — hx += 1: RIGHT increments x |
Common stumble: blanks 3–6 are the reverse guards. Students often swap the opposite (e.g. write "UP" for the UP guard instead of "DOWN"). Remind them: "What direction would reverse this move?"
Buggy: if event.key == pygame.K_UP and direction != "UP":
Fix: if event.key == pygame.K_UP and direction != "DOWN":
The guard should block the opposite direction, not the same one. != "UP" blocks the correct direction and lets the reverse happen.
Buggy: if direction == "UP": hx -= 1
Fix: if direction == "UP": hy -= 1
Moving UP changes the row (y-axis), not the column (x-axis). hx is the wrong variable.
Buggy: if direction == "LEFT": hx -= 1 (standalone second if)
Fix: elif direction == "LEFT": hx -= 1
Without elif, this branch fires independently every frame — the snake double-moves on one step. The chain must use elif.
Students add W/A/S/D key handling as an extra elif chain inside the same event loop, each with the correct reverse guard.
# Add inside the KEYDOWN block after the arrow-key elif chain:
elif event.key == pygame.K_w and direction != "DOWN":
direction = "UP"
elif event.key == pygame.K_s and direction != "UP":
direction = "DOWN"
elif event.key == pygame.K_a and direction != "RIGHT":
direction = "LEFT"
elif event.key == pygame.K_d and direction != "LEFT":
direction = "RIGHT"
Watch for: Students who add separate if event.type == pygame.KEYDOWN: blocks for WASD. Both sets must live inside the same event loop and use elif so only one direction fires per frame.
Students replace the four-branch if/elif chain with a single dict mapping each key constant to its new direction and the direction it must not be coming from.
KEY_MAP = {
pygame.K_UP: ("UP", "DOWN"),
pygame.K_DOWN: ("DOWN", "UP"),
pygame.K_LEFT: ("LEFT", "RIGHT"),
pygame.K_RIGHT: ("RIGHT", "LEFT"),
}
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key in KEY_MAP:
new_dir, forbidden = KEY_MAP[event.key]
if direction != forbidden:
direction = new_dir
Discussion prompt: "What does the dictionary buy us here?" — removing duplication, adding a new key in one line, separating data from logic. Connect to the DRY principle students will see in Step 6.
| Prompt | Key ideas a strong answer contains |
|---|---|
| 1. Direction storage — how stored, why string/tuple not number? | Direction stored as a string ("UP", "RIGHT" …) or tuple ((0,-1)). A string is readable and self-documenting; a tuple allows direct arithmetic. A bare number (0,1,2,3) works but requires a lookup and is harder to read. |
| 2. Blocking reverse — why not allowed, what code prevents it? | The head would move into the neck — immediate self-collision. The guard (and direction != "DOWN" etc.) checks the requested direction against the forbidden opposite and ignores the key press if it would reverse. |
| 3. if-elif-else — why a good fit for four directions? Another way? | elif ensures only the first matching branch fires — one direction change per frame. Alternatives: a dict lookup (Tier 4), a match statement (Python 3.10+). Trade-off: dict is more data-driven and extensible; elif chain is simpler and familiar. |
| 4. Challenge faced — trickiest part, debugging walk-through | Open-ended — mark for honest reflection and clear explanation of what went wrong and what they tried. Good answers name a specific bug and a specific fix, not "I was confused". |
| 5. Real-world connection — similar input-handling in another program | Any reasonable analogy: cursor-key navigation in a menu, WASD in a 3D game, swipe direction in a mobile app, drone controller, robot navigation, scroll-wheel direction. Credit understanding that the input is discrete and directional. |
| What they did | What they see | What to say |
|---|---|---|
Used if instead of elif for directions |
Snake moves diagonally when two keys pressed | "Only one direction change per frame. elif means only the first matching branch fires." |
dy == 1 instead of dy != 1 in guard |
Controls seem inverted or broken | "The guard should prevent reversal. != means 'not equal to the opposite direction'." |
head_x = dx instead of head_x += dx |
Snake teleports to (1, 0) every frame | "= replaces the value; += adds to it. The snake position accumulates over time." |
Used pygame.K_UP with get_pressed() |
Direction changes every frame the key is held — too fast | "KEYDOWN fires once; get_pressed() fires every frame. For direction changes, use the event." |
| Forgot to update position inside the loop | Snake never moves | "The update step (head_x += dx) must be inside the while loop, not before it." |
"What information does your brain use to move your hand? Direction and distance — the same two things as dx and dy."
Draw a snake on the board. Mark the head and neck. Ask: "If the head is moving right and you press LEFT, where does the head go?" Students will see it moves into the neck. This makes the guard intuitive rather than a mysterious rule to memorise.
The if/elif chain decomposes the key-handling problem into four mutually exclusive cases. Ask students: "What is the algorithm for deciding which direction to move?" This surfaces the idea that conditionals are a tool for expressing decisions.
Watch for: Students who make direction work but forgot pygame.display.flip() from Step 2 — nothing will appear to move. Check this first before debugging direction logic.
If students finish early, ask them to try making the snake start moving UP instead of RIGHT — this surfaces the guard logic because they need to adjust the initial dx, dy values and think through which guards change.
These 5 questions appear in the activity page after Tier 4 (post-calibration gate). Pass mark is 4 of 5 (80%). Students who fail may retry; the system records attempts and final score in Google Sheets.
| Question (displayed to student) | Correct Answer |
|---|---|
| Q1: How is the snake's current direction typically stored? | ✓ As a string like 'UP' or a tuple like (0,-1) |
| Q2: What condition prevents the snake from reversing directly? | ✓ Comparing the requested direction to the opposite of the current one |
| Q3: if event.type == pygame.KEYDOWN: — what does this test? | ✓ Whether a keyboard key was pressed this frame |
| Q4: Which direction vector moves the snake one cell to the RIGHT? | ✓ (1, 0) |
| Q5: What should happen if the player presses LEFT while snake moves RIGHT? | ✓ The input is ignored — opposite direction blocked |
Recorded in Google Sheet (Act_3 tab):
concept_q1–concept_q5 (student’s 0-based answer index),
concept_score_pct, concept_passed (1 = pass, 0 = fail),
concept_attempts (retry count).
Every submission to this step writes one row to the Act_3 tab in the research spreadsheet. All 13 tabs (Student_Reg, Pre_Test, Post_Test, Act_1–Act_10) share the same student identity columns.
| Column | Description |
|---|---|
| STUDENT IDENTITY (10 fields) | |
matric | Matric / student ID |
name | Full name |
gender | Gender (Female / Male / Other) |
age | Age in years |
mykid | MyKid / IC number |
home_state | Home state in Malaysia |
class | Class or cohort code |
school_code | School or programme code |
phone | Phone number |
email | Email address |
| SUBMISSION | |
step | Step number (3) |
submitted_iso | KL timestamp (UTC+8, ISO 8601) |
| PRE-CALIBRATION | |
cal_confidence | Self-confidence before activity (1–5 scale) |
cal_predicted | Predicted score before activity (%) |
cal_reflection | Free-text: what will be hard? |
| ACTIVITY TIERS | |
t1_score_pct | Tier 1 Fill-in-Blanks score (%) |
t2_attempts | Tier 2 Debug — number of attempts |
refl2_text | Tier 2 reflection free text |
t3_attempts | Tier 3 Complete-Code attempts |
t4_attempts | Tier 4 New Task attempts |
| CONCEPT CHECK | |
concept_q1–concept_q5 | Student answer index (0-based) per question |
concept_score_pct | Percentage correct (0–100) |
concept_passed | 1 = passed (≥80%), 0 = failed |
concept_attempts | Total retries |
| REFLECTIVE JOURNAL | |
jr1–jr5 | Journal prompts 1–5 free-text responses |
| POST-CALIBRATION | |
post_confidence | Confidence rating after activity (1–5) |
post_actual | Self-reported actual score (%) |
post_r1 | Reflection: how accurate was the prediction? |
post_r2 | Reflection: what would you do differently? |
calibration_index | post_actual − cal_predicted (negative = overconfident) |