Course 6: Five Functions - Functions and event handling
Course overview
In this course, students learn the advanced ways to use functions, andand event-driven programming. Games must respond to various eventssuch as user input, collisions, and the passage of time. Through this course, students learn to build interactive programs that behave like real games.
Estimated time: 12-24 hours
The time required depends on the student's grade level, prior experience, and learning speed, and varies greatly. It also differs between just learning the basic concepts and moving on, versus additional practice problems or creative projects: taking those on makes a difference too. The times above are an average range, so please proceed flexibly at your child's pace.
What abilities will it build?
the "input data → processing → output data" data pipeline way of thinking. A function is a data processing unitthat takes in data, transforms it, and outputs the result. Modern data systems are made of pipelines of countless connected functions.
What principles will you learn?
- (data transformation) A function takes input data, processes it, and returns output data.
calculate_tax(price)→ like a tax calculation result, they learn how to build blocks that transform data. - (event-driven processing) They learn the structure of responding to events and processing datalike "when the user clicks" or "when data arrives." Websites, apps, and IoT systems all operate in an event-driven way.
AI-era thinking: computing (problem-solving) | data-driven | probabilistic thinking
Computational Thinking
| Skill | Description | Example activity |
|---|---|---|
| 📦 Abstraction | Bundle repeated work into a function | draw_star() Function definition |
| 🧱 Modularization | Separate into independent functional units | Separate input handling, drawing, and collision checking |
| ⚡ Event handling | React to a specific action | "jump when the spacebar is pressed" |
| 🔁 Recursive thinking | A function calls itself | Maze generation, tree structure traversal |
Mathematical connections
| Math concept | Programming application | Learning benefit |
|---|---|---|
| Function f(x) | def area(r): return 3.14 * r * r |
input → output relationship |
| Parameter | draw_square(size) |
A function's independent variable |
| Return value | return result |
A function's dependent variable |
| Composite function | f(g(x)) |
Calling another function inside a function |
Function = a math function
Event-driven thinking
| Event (cause) | Callback function (result) | Game example |
|---|---|---|
| Keyboard input | def input(key): |
"W key → move forward" |
| Mouse click | def on_click(): |
"click → fire a bullet" |
| Time passing | def update(): |
"every frame → update position" |
| Collision occurs | def on_collision(): |
"touch an enemy → take damage" |
The mathematical concept of recursion
💻 Code examples & visualization
Example 1: Defining and calling a function
# Define the function
def greet(name):
"""A function that greets"""
return f"Hello, {name}!"
# Call the function
print(greet("Cheolsu")) # Hello, Chulsoo!
print(greet("Younghee")) # Hello, Younghee!
Function = a machine (input → processing → output):
Input
│
▼
┌─────────────────┐
│ greet function │
│ ┌───────────┐ │
│ │ store name│ │
│ │ join string│ │
│ │ return │ │
│ └───────────┘ │
└────────┬────────┘
│
▼
Output
greet("Chulsoo") → "Hello, Chulsoo!"
Example 2: A function with parameters
from ursina import *
app = Ursina()
def create_cube(x, y, z, cube_color):
"""Create a cube at the given position and color"""
return Entity(
model='cube',
color=cube_color,
position=(x, y, z)
)
# Create multiple cubes with function calls
create_cube(0, 0, 0, color.red)
create_cube(2, 0, 0, color.blue)
create_cube(4, 0, 0, color.green)
create_cube(0, 2, 0, color.yellow)
app.run()
The power of function reuse:
Without functions: Using functions:
───────────────────── ─────────────────────
Entity(model='cube', create_cube(0,0,0,red)
color=red, create_cube(2,0,0,blue)
position=(0,0,0)) create_cube(4,0,0,green)
Entity(model='cube', create_cube(0,2,0,yellow)
color=blue,
position=(2,0,0))
Entity(model='cube',
color=green,
position=(4,0,0))
...
→ Code length: 20 lines vs 4 lines!
Example 3: Event handling - the input() function
from ursina import *
app = Ursina()
player = Entity(model='cube', color=color.orange)
def input(key):
"""Handle keyboard input events"""
if key == 'space':
print("Jump!")
player.y += 2
if key == 'r':
print("Reset!")
player.position = (0, 0, 0)
app.run()
Event-driven programming:
flowchart TD
A[Game running<br/>waiting for keyboard input] --> B{Which key?}
B -->|space| C[Jump! 🦘]
B -->|r| D[Reset! 🔄]
B -->|other key| E[Ignore]
C --> A
D --> A
E --> A
Example 4: The update() function - the game loop
from ursina import *
app = Ursina()
player = Entity(model='cube', color=color.red)
speed = 5
def update():
"""Called every frame (60 times per second)"""
# WASD movement
if held_keys['w']:
player.z += speed * time.dt
if held_keys['s']:
player.z -= speed * time.dt
if held_keys['a']:
player.x -= speed * time.dt
if held_keys['d']:
player.x += speed * time.dt
app.run()
Game loop visualization:
flowchart TD
A[Game starts] --> B[Call update]
B --> C[1. Check input<br/>held_keys]
C --> D[2. Update position]
D --> E[3. Check collisions]
E --> F[4. Draw screen]
F --> G[Wait 1/60 sec]
G --> B
style B fill:#f9f,stroke:#333,stroke-width:2px
Repeats 60 times per second = 60 FPS
Example 5: Callback functions
from ursina import *
app = Ursina()
def on_click_red():
print("Red button clicked!")
def on_click_blue():
print("Blue button clicked!")
# Connect a callback function to the button
red_button = Button(
text='red',
color=color.red,
on_click=on_click_red # ← callback function
)
blue_button = Button(
text='blue',
color=color.blue,
position=(0, -0.1),
on_click=on_click_blue # ← callback function
)
app.run()
How callback functions work:
When creating the button:
┌─────────────────┐
│ red_button │
│ on_click = ──────────→ on_click_red function
└─────────────────┘
When a click event occurs:
┌─────────────────┐ ┌─────────────────┐
│ Mouse click! │ ───→ │ on_click_red() │
│ on red_button │ │ runs! │
└─────────────────┘ └─────────────────┘
"When this happens later, run this function for me"
Example 6: Recursive functions - a fractal tree
from turtle import *
def draw_tree(length):
"""Draw a tree recursively"""
if length < 10: # Base case
return
forward(length)
right(30)
draw_tree(length * 0.7) # Right branch (recursion)
left(60)
draw_tree(length * 0.7) # Left branch (recursion)
right(30)
backward(length)
# Start drawing the tree
left(90)
draw_tree(100)
The recursive call process:
Project 1: Bullet Hell - Functions and events
A. Introduction
| Item | Content |
|---|---|
| What will you learn? | Understanding the structure of a bullet-hell game |
| Core Concepts | Game loop, object creation, movement patterns |
Bullet Hell is a genre where huge numbers of bullets pour out in patterns . Students understand that a game runs as a loop that repeats every frame. To efficiently manage dozens or hundreds of bullets, a combination of lists and functionsis essential. This project gives students the experience of integrating previously learned concepts into a real game. The finished game is fun to play and also gives a sense of sense of accomplishmentaccomplishment.
B. Basic concept - Event handling
| Item | Content |
|---|---|
| What will you learn? | Responding to keyboard/mouse input |
| Core Concepts | Events, callback functions, input handling |
def input(key):is a function that is automatically called when there is keyboard input. Students learn that a program waits for the user's actions and responds. They implement game controls like "fire a bullet when the spacebar is pressed" or "move with the arrow keys". This is the core of event-driven programminginteractivity, and the same pattern is used in web and app development. Students come to understand the Basic structurestructure of interactive programs.
C. Understanding the code - the update function
| Item | Content |
|---|---|
| What will you learn? | Logic that runs every frame |
| Core Concepts | Game loop, frames, delta time |
def update():is automatically called every frame (about 60 times per second). All of a game's movement, collision checks, and state updates happen here. Students understand that a game is a sequence of continuous snapshots- just like a comic book. time.dtBy using a constant speed regardless of frame rate, they make things move at. This is a core concept of every real-time game. core structureIt is.
D. Quiz
| Item | Content |
|---|---|
| What will you learn? | Checking concept understanding |
| Core Concepts | Self-check, review |
Through a quiz, they check whether they accurately understood the core concepts. They can spot and correct misunderstandings early. In programming, accurately understanding the concepts comes before writing code. Students build the habit of objectively evaluating their own learning state. This is the metacognitive abilityIt is.
Project 2: Column Graph - Callback functions and dictionaries
A-D. Callback functions, data, and visualization
| Item | Content |
|---|---|
| What will you learn? | Passing a function as an argument |
| Core Concepts | Callback functions, dictionaries, data and visualization |
A callback function is a function you register saying "call me later". It runs when a specific event occurssuch as when a button is clicked or an animation ends. Students learn the powerful concept that a function can be passed around like a variable. A dictionary is a data structure that stores {"name": "value"} in the form of key-value pairs. In this project, they visualize data as a bar graphand experience the basics of data analysis.
Project 3: Maze Timer - Recursive functions and delayed calls
A-D. Recursion and timers
| Item | Content |
|---|---|
| What will you learn? | A function calling itself |
| Core Concepts | Recursion, base case, delayed execution |
A recursive function is a function that calls itself. It becomes an elegant solution for repetitive subproblemssuch as maze generation and tree structure traversal. Students learn that without a base case (stopping condition), it will be called infinitely. invoke(function, delay)with running a function after a set amount of time. They also learn delayed calls that. This concept is widely used, such as processing user names and analyzing messages.
Project 4: Shooter - Input handling and collisions
A-D. Real-time input and collision detection
| Item | Content |
|---|---|
| What will you learn? | Implementing shooting-game mechanics |
| Core Concepts | Input handling, collision detection, game state |
A shooting game is the input → action → resultfast feedback loop. held_keys['w']with whether a key is being held down is continuously checked. Collision detection decides "whether a bullet hit an enemy," and if so it removes the enemy and increases the score. Students understand the game structure where multiple systems (input, physics, score) work together. This project is an experience of integrating previously learned concepts into a real gamebringing together everything learned before.
When you finish this course...
Learning outcomes
Students will be able to:
- event-driven programming: understand and apply the pattern of
- keyboard/mouse respond to input: build a program that
- the update function: implement a game loop with
- A callback function: handle asynchronous behavior using
- Recursive functions: understand the concept of, and apply it to simple examples
- Multiple systems integrated into one gameand implement them