This page contains exercise answers and teaching guidance for
Step 7 — Wrap-Around ⭐.
Not linked from the student pages.
Students: please go back and try the activities first.
STEP 7 OF 10 · FACILITATOR NOTES
% (modulo) operator does and why -1 % 20 = 19 in Pythonhx = hx % GRID_COLS to replace a wall-death check with Pac-Man style wrap-aroundMOVES = {"RIGHT": (1, 0), ...}) and look up values with a variable keyif/elif chain for data-driven dispatch[0]hx, hy = snake[0]
if direction == "RIGHT": hx += 1
elif direction == "LEFT": hx -= 1
elif direction == "UP": hy -= 1
elif direction == "DOWN": hy += 1
# wall death
if hx < 0 or hx >= GRID_COLS or hy < 0 or hy >= GRID_ROWS:
running = False
MOVES = {
"RIGHT": ( 1, 0),
"LEFT": (-1, 0),
"UP": ( 0, -1),
"DOWN": ( 0, 1),
}
def update_game(snake, direction, food, score):
hx, hy = snake[0] # (1) head is always index 0
dx, dy = MOVES[direction] # (2) O(1) dict lookup, no if/elif needed
hx += dx; hy += dy # (3) apply the step
hx = hx % GRID_COLS # (4) wrap horizontal — handles both edges
hy = hy % GRID_ROWS # (5) wrap vertical
new_head = (hx, hy)
if new_head in snake[1:]: # (6) self-collision only (wall-death gone!)
return snake, food, score, False
Key changes and why they matter:
hx % GRID_COLS is always in [0, GRID_COLS) regardless of input. No branch needed.| Expression | Result | Game meaning |
|---|---|---|
20 % 20 | 0 | Exits right edge → re-enters column 0 |
-1 % 20 | 19 | Exits left edge → re-enters column 19 |
15 % 15 | 0 | Exits bottom → re-enters row 0 (top) |
-1 % 15 | 14 | Exits top → re-enters row 14 (bottom) |
ⓘ Python’s % always returns a non-negative result when the divisor is positive — that is why -1 % 20 = 19, not -1. This differs from C and Java.
| Blank | Answer | Why |
|---|---|---|
| 1 | 0 | The head is always snake[0] — the first tuple in the list. |
| 2 | direction | Must use the variable, not a hardcoded literal, so the correct vector is returned each tick. |
| 3 | % | Modulo wraps hx into [0, GRID_COLS). |
| 4 | % | Same wrap-around logic for the vertical axis. |
| 5 | in | Python membership test: new_head in snake[1:] is True when head hits body. |
| 6 | False | Fourth return value signals “game not running” to the caller. |
Score logged as t1_score_pct (percentage correct on first attempt).
Buggy: hx = hx / GRID_COLS
Error: Division produces a float; coordinates become fractional and Pygame crashes. The snake does not wrap — it escapes the grid.
Fix: hx = hx % GRID_COLS — change / to %
Buggy: dx, dy = MOVES["right"]
Error: KeyError: 'right' — MOVES keys are uppercase. Even if the case matched, a literal key ignores the actual direction and the snake always goes the same way.
Fix: dx, dy = MOVES[direction] — use the variable.
Buggy: hx, hy = snake
Error: ValueError: too many values to unpack — snake is a list of tuples, not a single tuple.
Fix: hx, hy = snake[0] — add [0] to unpack only the head.
MOVES = {
"RIGHT": ( 1, 0),
"LEFT": (-1, 0),
"UP": ( 0, -1),
"DOWN": ( 0, 1),
"STOP": ( 0, 0), # new — zero vector means no movement
}
# In update_game:
dx, dy = MOVES[direction]
if dx == 0 and dy == 0: # STOP: return state unchanged
return snake, food, score, True
hx += dx; hy += dy
...
Accept any approach that correctly short-circuits when direction == "STOP".
GRID_COLS = 20
GRID_ROWS = 15
MOVES = {
"RIGHT": ( 1, 0),
"LEFT": (-1, 0),
"UP": ( 0, -1),
"DOWN": ( 0, 1),
}
def update_game(snake, direction, food, score):
hx, hy = snake[0] # unpack head
dx, dy = MOVES[direction] # get step vector
hx += dx # apply step
hy += dy
hx = hx % GRID_COLS # wrap horizontal
hy = hy % GRID_ROWS # wrap vertical
new_head = (hx, hy)
if new_head in snake[1:]: # self-collision
return snake, food, score, False
snake = [new_head] + snake[:-1] # move forward
if new_head == food: # food eaten
snake = [new_head] + snake # grow
score += 1
food = (random.randint(0, GRID_COLS-1),
random.randint(0, GRID_ROWS-1))
return snake, food, score, True
Award marks for: correct MOVES dict (4 entries), snake[0] for head, both % wraps, self-collision check, snake movement, food/score logic.
| Prompt | Key ideas a strong answer contains |
|---|---|
1. What does % do? Why is -1 % 20 = 19? | Modulo returns the remainder. Python guarantees non-negative results when the divisor is positive, so -1 % 20 = 19, not -1. Maps “one step past the left wall” to the right-most column. |
2. How did 2 lines of % replace the 8-condition wall check? | The old check tested 4 conditions and ended the game. Modulo keeps coordinates inside the grid automatically — no out-of-bounds value can ever exist after wrapping. |
| 3. Dictionary vs if/elif — main advantage? | Movement data (the vectors) is separated from game logic. Adding a new direction needs one dict entry, not a new elif block. The dict reads as a clear table of facts. |
| 4. What MOVES entry makes the snake freeze? | "STOP": (0, 0) — a zero vector means no displacement. The code handles it without any new if statements. |
| 5. Grid grows to 30 cols — what changes? | Only GRID_COLS = 30. The line hx = hx % GRID_COLS uses the variable, so the wrap boundary updates automatically. |
5 MCQs appear after Tier 4. Results recorded in the Act_7 Google Sheet tab.
| # | Question | Correct Answer |
|---|---|---|
| Q1 | What does 20 % 20 evaluate to? |
✓ 0 (option index 0) |
| Q2 | Given hx = -1 and GRID_COLS = 20, what is hx % GRID_COLS? |
✓ 19 (option index 2) |
| Q3 | Why is a MOVES dictionary better than an if/elif chain? |
✓ It separates movement data from game logic, making the code easier to extend (option index 1) |
| Q4 | Given MOVES = {"LEFT": (-1, 0)}, what does dx, dy = MOVES["LEFT"] give? |
✓ dx = -1, dy = 0 (option index 1) |
| Q5 | After adding % wrap-around, which old check can be removed? |
✓ The wall-death check: if hx < 0 or hx >= GRID_COLS (option index 1) |
Columns in Act_7:
concept_q1_ans–concept_q5_ans (0-based student choice),
concept_q1_cor–concept_q5_cor (1=correct, 0=wrong),
concept_score_pct, concept_passed, concept_attempts.
| What they did | What they see | What to say |
|---|---|---|
Used / instead of % |
Float coordinate crash in Pygame; snake escapes the grid | “/ divides; % gives the remainder. After one full loop the remainder is always 0 — back to the first column. That’s the wrap.” |
Wrote MOVES["right"] (lowercase) |
KeyError: 'right' |
“The keys are uppercase strings. But more importantly: use the variable direction, not a literal — otherwise the snake always goes the same way.” |
Wrote hx, hy = snake (no index) |
ValueError: too many values to unpack |
“snake is a list of tuples. You need the first tuple — add [0].” |
Kept old wall-death check AND added % |
Game ends instantly on any wrap | “Modulo makes the coordinates valid before any check. The wall check is now redundant — remove it.” |
Wrote new_head in snake (not snake[1:]) |
Game ends every step — head is always in snake | “The new head IS in snake. Check if it overlaps the body — slice from index 1.” |
Play 30 s of Step 6 (wall death) then 30 s of Step 7 (wrap). Ask: “Which version would you play longer?” They feel the improvement immediately — now make them understand the two-line fix behind it.
In C and Java, -1 % 20 is typically -1 (negative). Python guarantees non-negative results when the divisor is positive. Demonstrate it live in a Python shell. This catches students who Google “modulo negative” and find C examples.
Draw two columns on the board: data (what moves where) vs logic (what the game does each tick). The if/elif chain mixes them. The MOVES dict separates them. Ask: “If we add a diagonal direction, how many lines change in each version?” (1 vs 5+).
Both refactors are pattern recognition: four directions share the shape (dx, dy); both axes share the same wrap formula. The dictionary and the modulo operator are the abstractions that name those patterns.
Step 7 is a star step — two big ideas in one. Early finishers: “Can you add a diagonal direction ("UP_RIGHT": (1, -1)) without changing any game logic?” One dict entry is all that’s needed.
Students sometimes think wrap-around removes self-collision. Clarify: the snake can still bite itself if it doubles back. Only wall-death is removed.
Every activity submission writes one row to the Act_7 tab (auto-created on first submission).
| Column | Description |
|---|---|
| STUDENT IDENTITY | |
matric | Matric / student ID |
name | Full name |
gender, age, mykid | Demographics |
home_state, class, school_code | Location & cohort |
phone, email | Contact |
| SUBMISSION | |
submitted_iso | KL timestamp (UTC+8, ISO 8601) |
step | Step number (7) |
| PRE-CALIBRATION | |
cal_confidence | Self-confidence before activity (1–10 slider) |
cal_predicted | Predicted Tier 1 score before activity (%) |
cal_reflection | Free-text: prior knowledge of % or dicts |
| ACTIVITY TIERS | |
t1_score_pct | Tier 1 fill-in-blanks score on first attempt (%) |
t2_attempts | Tier 2 debug attempts (max 2) |
refl2_text | Mid-activity reflection free text |
t3_attempts | Tier 3 Extend attempts |
t4_attempts | Tier 4 Create attempts |
| CONCEPT CHECK | |
concept_q1_ans–concept_q5_ans | Student answer index (0-based) per question |
concept_q1_cor–concept_q5_cor | 1 = correct, 0 = incorrect per question |
concept_score_pct, concept_passed, concept_attempts | Summary stats |
| REFLECTIVE JOURNAL | |
jr1–jr5 | Journal prompts 1–5 free-text responses |
| POST-CALIBRATION | |
post_confidence | Confidence after activity (1–10) |
post_actual | Self-reported Tier 1 actual score (%) |
post_r1, post_r2 | Reflections on prediction accuracy |
calibration_index | t1_score_pct − cal_predicted — negative = overconfident |
Research note: calibration_index quantifies metacognitive accuracy. A consistently negative value across the cohort suggests students overestimate prior knowledge of modulo — a documented misconception in secondary computing education.