This page contains exercise answers and teaching guidance for
Step 9 — OOP Refactor.
Not linked from the student pages.
Students: please go back and try the activities first.
class keyword and understand what it represents (a blueprint for objects)__init__ method to initialise instance attributes using selfself is a reference to the specific instance being acted onsnake.move())Snake, Food, and Gameclass Snake:
# ── __init__ runs automatically when Snake() is called ──
def __init__(self):
# self refers to THIS particular Snake instance
self.body = [(100, 100), (80, 100), (60, 100)] # instance attribute
self.direction = "RIGHT" # instance attribute
# ── instance method: first parameter is ALWAYS self ──
def move(self):
x, y = self.body[0] # read THIS snake's head
if self.direction == "RIGHT": x += 20
elif self.direction == "LEFT": x -= 20
elif self.direction == "UP": y -= 20
elif self.direction == "DOWN": y += 20
self.body.insert(0, (x, y)) # add new head
self.body.pop() # remove tail
def change_direction(self, new_dir):
# "self" lets us access instance data from any method
opposites = {"RIGHT":"LEFT","LEFT":"RIGHT","UP":"DOWN","DOWN":"UP"}
if new_dir != opposites.get(self.direction):
self.direction = new_dir
class Food:
def __init__(self):
self.position = self._random_pos()
def _random_pos(self): # leading _ means "internal helper"
import random
return (random.randrange(0, 600, 20), random.randrange(0, 400, 20))
def respawn(self):
self.position = self._random_pos()
class Game:
def __init__(self):
self.snake = Snake() # instantiate Snake class
self.food = Food() # instantiate Food class
self.score = 0
def update(self):
self.snake.move()
if self.snake.body[0] == self.food.position:
self.score += 1
self.food.respawn()
def run(self):
while True: # main loop lives inside the class
self.update()
# draw, handle events, clock.tick...
class Snake: — defines a blueprint. You can create many independent Snake instances from one class.def __init__(self): — the constructor. Python calls it automatically when you write Snake(). It sets up the object's initial state.self — the invisible first argument that Python fills in automatically. When you call snake.move(), Python secretly passes snake as self. Inside the method, self.body means "this snake's body list".self (e.g. self.body). Each object has its own copy. Contrast with a regular variable inside a function, which disappears when the function returns.self.snake = Snake() creates an object from the class blueprint. The parentheses call __init__. Without them (Snake) you get the class itself, not an object.Students complete a Snake and Game class skeleton. Each blank is a single keyword, name, or value.
| Blank | Correct answer | Why |
|---|---|---|
Blank 1 — ___1___ Snake: |
class |
The keyword that starts a class definition in Python. def defines functions; class defines classes. |
Blank 2 — self.___2___ = "RIGHT" |
direction |
The name of the attribute that stores which way the snake is moving. Must match wherever else the attribute is referenced. |
Blank 3 — def move(___3___): |
self |
Every instance method must have self as its first parameter so Python can pass the calling object in automatically. |
Blank 4 — self.body.___4___() |
pop |
list.pop() removes and returns the last element — used to remove the snake's tail after adding a new head, keeping the length constant. |
Blank 5 — self.snake = ___5___() |
Snake |
Instantiates the Snake class. The parentheses are essential — without them you get the class object, not an instance. |
Blank 6 — while ___6___: |
True |
A game loop runs indefinitely until explicitly broken out of. while True: is the standard Python idiom for an infinite loop. |
class Snake: # blank 1: class
def __init__(self):
self.body = [(100,100),(80,100),(60,100)]
self.direction = "RIGHT" # blank 2: direction
def move(self): # blank 3: self
x, y = self.body[0]
if self.direction == "RIGHT": x += 20
self.body.insert(0, (x, y))
self.body.pop() # blank 4: pop
class Game:
def __init__(self):
self.snake = Snake() # blank 5: Snake
self.score = 0
def run(self):
while True: # blank 6: True
self.snake.move()
| Bug | Buggy line | Fixed line | Explanation |
|---|---|---|---|
| 1 | def move(): |
def move(self): |
All instance methods must have self as their first parameter. Without it Python raises TypeError: move() takes 0 positional arguments but 1 was given when you call snake.move(). |
| 2 | score += 1 |
self.score += 1 |
Inside a method, bare score looks for a local variable which does not exist. The attribute is stored on the instance, so self.score is required. Forgetting self. is the single most common OOP mistake. |
| 3 | self.snake = Snake |
self.snake = Snake() |
Without parentheses Snake is the class object itself, not an instance. Calling self.snake.move() would then fail with TypeError: move() missing 1 required positional argument: 'self' because no instance was created. |
Students add a draw(self, screen) method to both Snake and Food.
class Snake:
def __init__(self):
self.body = [(100, 100), (80, 100), (60, 100)]
self.colour = (0, 200, 100)
def move(self):
pass # movement logic (already implemented)
def draw(self, screen):
# draw each segment of the snake's body
for segment in self.body:
rect = pygame.Rect(segment[0], segment[1], 20, 20)
pygame.draw.rect(screen, self.colour, rect)
class Food:
def __init__(self):
self.position = (200, 200)
self.colour = (220, 50, 50)
def draw(self, screen):
# draw the food as a single rectangle
rect = pygame.Rect(self.position[0], self.position[1], 20, 20)
pygame.draw.rect(screen, self.colour, rect)
Accept any valid call to pygame.draw.rect(screen, colour, rect). Students may use pygame.draw.circle or ellipse for food — accept these too. The key criterion is that the method takes self and screen, and uses self.colour and self.body / self.position.
Students write a complete Game class with four methods: __init__, update, draw, run.
import pygame, random
class Snake:
def __init__(self):
self.body = [(100,100),(80,100),(60,100)]
self.direction = "RIGHT"
self.colour = (0,200,100)
def move(self):
x,y = self.body[0]
if self.direction=="RIGHT": x+=20
elif self.direction=="LEFT": x-=20
elif self.direction=="UP": y-=20
elif self.direction=="DOWN": y+=20
self.body.insert(0,(x,y))
self.body.pop()
def draw(self,screen):
for seg in self.body:
pygame.draw.rect(screen,self.colour,pygame.Rect(seg[0],seg[1],20,20))
class Food:
def __init__(self):
self.position=(random.randrange(0,600,20),random.randrange(0,400,20))
self.colour=(220,50,50)
def respawn(self):
self.position=(random.randrange(0,600,20),random.randrange(0,400,20))
def draw(self,screen):
pygame.draw.rect(screen,self.colour,pygame.Rect(self.position[0],self.position[1],20,20))
class Game:
def __init__(self):
# create instances of the collaborating objects
pygame.init()
self.screen = pygame.display.set_mode((600,400))
self.clock = pygame.time.Clock()
self.snake = Snake()
self.food = Food()
self.score = 0
self.running = True
def update(self):
# move snake and check food collision
self.snake.move()
if self.snake.body[0] == self.food.position:
self.score += 1
self.food.respawn()
# wall collision
hx, hy = self.snake.body[0]
if hx < 0 or hx >= 600 or hy < 0 or hy >= 400:
self.running = False
def draw(self, screen):
# draw all game elements
screen.fill((30,30,30))
self.snake.draw(screen)
self.food.draw(screen)
font = pygame.font.SysFont(None, 28)
screen.blit(font.render(f"Score: {self.score}", True, (255,255,255)), (10,10))
pygame.display.flip()
def run(self):
# main game loop encapsulated inside the class
while self.running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
if event.type == pygame.KEYDOWN:
dirs = {pygame.K_UP:"UP",pygame.K_DOWN:"DOWN",
pygame.K_LEFT:"LEFT",pygame.K_RIGHT:"RIGHT"}
if event.key in dirs:
self.snake.change_direction(dirs[event.key])
self.update()
self.draw(self.screen)
self.clock.tick(10)
pygame.quit()
if __name__ == "__main__":
Game().run()
The key assessment criterion for Tier 4 is structure, not a runnable game: does the class have __init__, update, draw, and run? Are Snake and Food instantiated inside __init__? Is the game loop inside run? These are the markers of genuine encapsulation understanding.
| Prompt | Key ideas a strong answer contains |
|---|---|
| 1. What problem does OOP solve that functions cannot? | Functions scatter related data and behaviour across the file. OOP bundles them: all snake state (body, direction, colour) and all snake behaviour (move, draw, change_direction) live in one Snake class. You can create two independent snakes without duplicating any code, and you know exactly where to look when a bug appears. |
2. Why must every method have self as its first parameter? |
snake.move() is shorthand for Snake.move(snake). Python automatically passes the calling object as the first argument. If self is missing, the method receives the object as an unexpected argument and raises TypeError. self is the door through which a method accesses its own object's data. |
| 3. Class attribute vs instance attribute | A class attribute is defined directly in the class body and shared by all instances: GRID_SIZE = 20. An instance attribute is set with self.name = ... in __init__ and belongs only to that object: self.body = [(100,100)]. Two Snake objects have different bodies but share the same GRID_SIZE. |
| 4. Design Player and Ghost classes for Pac-Man | Player attributes: position, lives, score, powered_up. Methods: move(direction), eat(dot), die(). Ghost attributes: position, colour, frightened. Methods: move(), respawn(), is_frightened(). Strong answers explain why each attribute/method belongs to that class, not to a global variable. |
| 5. Advantages of a Game class instead of global scope | State (score, snake, food, running) lives on self, not in globals — no accidental overwriting. The loop is in run() so it is easy to start and stop. You can create multiple Game instances for testing. Maintenance is easier: looking for a bug in the update logic? Go to update(), not a 300-line script. |
| What they did | What they see | What to say |
|---|---|---|
Forgot self in def move(): |
TypeError: move() takes 0 positional arguments but 1 was given |
"Python silently passes the object as the first argument. If self is missing, that object lands in the wrong slot. Always put self first." |
Used bare score += 1 instead of self.score += 1 |
UnboundLocalError: local variable 'score' referenced before assignment |
"The attribute is stored on the object, not as a local variable. Inside any method, prefix instance attributes with self." |
Wrote self.snake = Snake (no parentheses) |
No error yet, but later: TypeError: move() missing 1 required positional argument: 'self' |
"Snake is the class (blueprint). Snake() with parentheses calls __init__ and creates an object from the blueprint. Always instantiate with ()." |
Called method without the instance: move() instead of self.snake.move() |
NameError: name 'move' is not defined |
"Methods live on the object, not in global scope. You must always say which object: self.snake.move()." |
Defined attribute inside a method (not __init__): def move(self): self.body = ... |
Attribute re-initialised every frame — snake always stays 3 segments long, never grows | "__init__ is the right place to set up an object's starting state. A method that re-assigns self.body resets the snake on every call." |
| Indented class body incorrectly | IndentationError or method defined outside the class |
"Everything inside the class must be indented consistently. Use 4 spaces. Methods that are not indented are just global functions and have no access to self." |
"What if we needed two snakes on screen at the same time — how would you do it with our current code?" Students quickly realise that duplicating all the variables is a nightmare. Classes solve exactly this problem.
selfself confuses almost everyone on first encounter. The clearest explanation: snake.move() is Python shorthand for Snake.move(snake). Python is passing the object as the first argument automatically. self is just the name we give that argument — it could be called anything, but self is the universal convention.
Live demo: define a method without self, call it, see the error. Add self, call again. The error message "takes 0 positional arguments but 1 was given" is Python telling you it tried to pass the object but had nowhere to put it.
Start with the students' existing snake code (one long script). Ask: "Where does all the snake's data live?" Circle global variables. "Where is all the snake's behaviour?" Circle functions. "OOP says: put them in the same place." Then copy-paste the globals into __init__ (add self.), and the functions into the class (add self as first parameter). The transformation is visible and not magic.
Students sometimes ask if OOP means inheritance. Clarify: OOP has several pillars. Step 9 focuses on encapsulation only — grouping data and behaviour. Inheritance is a separate concept (a future step).
CT connection — Abstraction: "When you call self.snake.move() in the Game class, you don't need to know HOW it moves — just that it does. The Snake class hides the implementation. This is called abstraction, and it's why large software systems are manageable."
The Tier 4 rubric is structural: four methods present, Snake and Food instantiated inside __init__, game loop inside run(). Don't penalise for minor syntax errors if the student clearly understands where data and methods belong.
5 questions appear in the activity page after Tier 4. Pass mark is 4 of 5 (80%). CQ_ANS array (0-indexed): [1, 1, 1, 2, 2].
| # | Question (displayed to student) | Correct option (0-indexed) | Correct Answer |
|---|---|---|---|
| Q1 | Which keyword is used to define a class in Python? | 1 | ✓ class |
| Q2 | What does self refer to inside a class method? |
1 | ✓ The specific instance (object) that the method was called on |
| Q3 | When is __init__ called? |
1 | ✓ It is called automatically when a new object is created |
| Q4 | Given snake = Snake(), how do you call its move method? |
2 | ✓ snake.move() |
| Q5 | What best describes encapsulation in OOP? | 2 | ✓ Bundling related data (attributes) and behaviour (methods) together inside a class |
Recorded in Google Sheet (Act_9 tab):
concept_q1_ans–concept_q5_ans (student's 0-based answer index),
concept_q1_cor–concept_q5_cor (1 = correct, 0 = wrong),
concept_score_pct, concept_passed (1 = pass, 0 = fail),
concept_attempts (retry count).
Every submission writes one row to the Act_9 tab. Column structure is identical to Act_8 — same 41 columns, same student identity fields.
| Column | Description |
|---|---|
| STUDENT IDENTITY (10 fields) | |
matric | Matric / student ID |
name | Full name |
gender | Gender |
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 (9) |
submitted_iso | KL timestamp (UTC+8, ISO 8601) |
| PRE-CALIBRATION | |
cal_confidence | Self-confidence before activity (1–10) |
cal_predicted | Predicted Tier 1 score before activity (%) |
cal_reflection | Prior knowledge free-text |
| ACTIVITY TIERS | |
t1_score_pct | Tier 1 Fill-in-Blanks first-attempt score (%) |
t2_attempts | Tier 2 Debug — attempts (max 2) |
refl2_text | Mid-activity reflection on self |
t3_attempts | Tier 3 Extend attempts |
t4_attempts | Tier 4 Create 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 (OOP: classes, self, attributes, design, Game class) |
| POST-CALIBRATION | |
post_confidence | Confidence rating after activity (1–10) |
post_actual | Self-estimated actual Tier 1 score (%) |
post_r1 | Reflection: prediction vs actual |
post_r2 | Second reflection (if collected) |
calibration_index | post_actual − cal_predicted (negative = overconfident) |