Course 3: Two Flow - Mastering Control Flow
Course overview
This course teaches the two core structures, loops and conditionals,in depth within the context of 3D game development. Building on the basics from Pre Basics, students master the control flow needed to create real game logic. They develop the ability to express a game's rules, state changes, and repeating patterns in code.
Estimated time: 8-16 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?
automatically process large amounts of data. In the era of big data, you can't process millions of records one by one. Using loops to batch-process dataand conditionals to classify datais the heart of all data processing.
What principles will you learn?
- (Batch data processing) By creating hundreds of objects at once with loops, students efficiently process large amounts of dataand experience the underlying principle. It's the same idea as dragging an Excel formula down a column.
- (Data classification) They classify data with conditionals. Rules like "90 or above is an A, 80 or above is a B" are data-driven classification rulesand are the basic principle behind spam filters, recommendation systems, and AI classifiers.
AI-era thinking: computing (problem-solving) | data-driven | probabilistic thinking
Computational Thinking
| Skill | Description | Example activity |
|---|---|---|
| 🔄 Loop automation | Auto-generate patterns with code | Create 100 blocks with a single for loop |
| 🔀 Conditional branching | Different handling by situation | Assign A/B/C grades based on score |
| ➗ Applying formulas | Express math formulas in code | position = (i * 2, 0, 0) |
| ➡️ Code structuring | Define scope with indentation | Distinguish loop/conditional blocks |
Mathematical connections
| Math concept | Programming application | Learning benefit |
|---|---|---|
| Linear functions | y = i * 2 + 1 |
Understanding slope and y-intercept |
| Arithmetic sequences | range(0, 20, 3) → 0, 3, 6, 9... |
First term and common difference concepts |
| Trigonometric functions | sin(i * 30) → Wave patterns |
Visualizing period and amplitude |
| Modulo operation | i % 2 → Even/odd detection |
Periodicity and multiples concepts |
Pattern-generating formula
| Pattern | Code | Mathematical principle |
|---|---|---|
| Linear arrangement | x = i * 2 |
Arithmetic sequence: a_n = 2n |
| Grid arrangement | x = i % 5, y = i // 5 |
Division and remainder |
| Circular arrangement | x = cos(i*36°), y = sin(i*36°) |
Trigonometric functions, equation of a circle |
| Spiral | r = i, θ = i * 10° |
Polar coordinates, Archimedean spiral |
Conditional logic structure
💻 Code examples & visualization
Example 1: Linear arrangement - using the loop variable
from ursina import *
app = Ursina()
# Arrange 10 cubes in a row
for i in range(10):
cube = Entity(
model='cube',
color=color.red,
position=(i * 2, 0, 0) # Change position based on i
)
app.run()
Result:
i=0 i=1 i=2 i=3 i=4 i=5 i=6 i=7 i=8 i=9
┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐
│■│ │■│ │■│ │■│ │■│ │■│ │■│ │■│ │■│ │■│
└─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘
x=0 x=2 x=4 x=6 x=8 x=10 x=12 x=14 x=16 x=18
Mathematical principle: position.x = i × 2
Example 2: Staircase shape - using two variables
from ursina import *
app = Ursina()
# Arrange in a staircase shape
for i in range(5):
cube = Entity(
model='cube',
color=color.orange,
position=(i, i * 0.5, 0) # x is i, y is i×0.5
)
app.run()
Result:
┌─┐ i=4, y=2
┌─┐ │■│
┌─┐ │■│─┘
┌─┐ │■│─┘ i=3, y=1.5
┌─┐ │■│─┘
│■│─┘ i=2, y=1
┌─┐─┘
│■│ i=1, y=0.5
┌─┘
│■│ i=0, y=0
─────────────────────
Example 3: Chessboard pattern with conditionals
from ursina import *
app = Ursina()
for i in range(8):
for j in range(8):
# Change color based on even/odd
if (i + j) % 2 == 0:
tile_color = color.white
else:
tile_color = color.black
tile = Entity(
model='cube',
color=tile_color,
position=(i, 0, j),
scale=(1, 0.1, 1)
)
app.run()
Chessboard pattern principle:
Sum of i+j:
┌───┬───┬───┬───┬───┬───┬───┬───┐
│ 0 │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │ 7 │ j=0
├───┼───┼───┼───┼───┼───┼───┼───┤
│ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │ 7 │ 8 │ j=1
├───┼───┼───┼───┼───┼───┼───┼───┤
│ 2 │ 3 │ 4 │ 5 │ 6 │ 7 │ 8 │ 9 │ j=2
└───┴───┴───┴───┴───┴───┴───┴───┘
i=0 i=1 i=2 ...
(i+j) % 2 result:
┌───┬───┬───┬───┐
│ ◻ │ ◼ │ ◻ │ ◼ │ even=white
├───┼───┼───┼───┤ odd=black
│ ◼ │ ◻ │ ◼ │ ◻ │
├───┼───┼───┼───┤
│ ◻ │ ◼ │ ◻ │ ◼ │
└───┴───┴───┴───┘
Example 4: Color gradient with conditionals
from ursina import *
app = Ursina()
for i in range(10):
# Shift from red to blue based on i
r = 1 - (i / 10) # 1.0 → 0.0
b = i / 10 # 0.0 → 1.0
cube = Entity(
model='cube',
color=color.rgb(r, 0, b),
position=(i * 1.5, 0, 0)
)
app.run()
Color change:
i=0 i=1 i=2 ... i=8 i=9
🟥 🟪 🟪 ... 🟦 🟦
red ─────────────────────→ blue
R value: 1.0 0.9 0.8 ... 0.1 0.0
B value: 0.0 0.1 0.2 ... 0.8 0.9
Example 5: Circular arrangement - trigonometric functions
from ursina import *
import math
app = Ursina()
num_cubes = 12 # 12 cubes
radius = 5 # Radius
for i in range(num_cubes):
angle = math.radians(i * 30) # 30-degree spacing (360/12)
x = math.cos(angle) * radius
z = math.sin(angle) * radius
cube = Entity(
model='cube',
color=color.orange,
position=(x, 0, z)
)
app.run()
Circular arrangement principle:
90° (π/2)
■
■ ■
■ ■
180° ■ ● ■ 0°
■ ■
■ ■
■
270° (3π/2)
x = cos(θ) × radius
z = sin(θ) × radius
θ = 0°: x = 5, z = 0
θ = 90°: x = 0, z = 5
θ = 180°: x = -5, z = 0
Flowchart:
flowchart TD
A[i = 0] --> B[angle = i × 30°]
B --> C[x = cos angle × r<br/>z = sin angle × r]
C --> D[Create cube<br/>position x, z]
D --> E{i < 12?}
E -->|Yes| F[i = i + 1]
F --> B
E -->|No| G[Done! 🎉]
Chapter 01: Deep Dive into For Loops
A. What Is a Loop?
| Item | Content |
|---|---|
| What will you learn? | Revisiting the concept and necessity of loops |
| Core Concepts | Automation, efficiency, pattern recognition |
A loop perform the same task many times. To draw 100 stars, instead of writing the same code 100 times, you can solve it with a single loop. By asking "Is this task repeating?", students develop the ability to recognize patterns. Loops are essential when spawning 10 enemies in a game or making 20 inventory slots. A computer's true power lies in performing repetitive tasks tirelessly.
B. range() Number Factory
| Item | Content |
|---|---|
| What will you learn? | Various ways to use the range function |
| Core Concepts | Generating sequences, using parameters |
range()is a factory that generates number sequencesIt is. range(10)produces 0 through 9, range(5, 10)produces 5 through 9, range(0, 10, 2)produces 0, 2, 4, 6, 8. Students learn how to flexibly adjustthe start, end, and step values. When building a 3D grid, they can create range(-5, 6)Use symmetric structures centered on the middle. This flexibility is key to efficiently generatingvarious patterns and structures.
C. The Variable i Basket
| Item | Content |
|---|---|
| What will you learn? | Dynamic use of the loop variable |
| Core Concepts | Index, dynamic calculation, placement |
Loop variable iis a basket that holds the current iteration count. Using this value in position calculations lets you position=(i * 2, 0, 0)like place objects at regular intervals. Students learn to use mathematical formulas to create regular patterns. With circular arrangement (usingsin, cos ), staircase arrangement, and more, they can create various patterns. These skills are directly applicable, such as processing user names and analyzing messages.
D. Indentation
| Item | Content |
|---|---|
| What will you learn? | Defining the scope of a Python code block |
| Core Concepts | Code structure, scope, readability |
In Python Indentation is part of the syntax. Code that runs inside a loop must be indented. Students understand that indentation determines the structure and flow of the code. Indentation errors are one of the most common problems beginners face, and overcoming them improves their ability to read code structure. Consistent indentation (usually 4 spaces) improves readability and maintainability.
E. Using Calculations
| Item | Content |
|---|---|
| What will you learn? | Calculating position and size with math formulas |
| Core Concepts | Mathematical modeling, using functions |
Combining the loop variable with math formulas lets you generate complex patterns. sin(i * 30)for waves, i ** 2for acceleration effects, i % 3for periodic patterns. Students experience that programming is a tool that puts math to real use. They can create visually impressive resultssuch as spiral staircases, spinning fans, and rolling seas. This experience boosts their interest in and appreciation for the usefulness of math.
Chapter 02: Deep Dive into Conditionals
A. What Is an If Statement?
| Item | Content |
|---|---|
| What will you learn? | Branching based on conditions |
| Core Concepts | Decision-making, branching, boolean logic |
ifstatements let a program decide "if such-and-such". In games they express rules like "if health is 0, game over" and "if you grab an item, the score goes up." Students learn to translate game rules into code. They understand selective execution, where specific code runs only when a condition is True. This is the core structureIt is.
B. Else Statements
| Item | Content |
|---|---|
| What will you learn? | Handling the alternative when a condition is false |
| Core Concepts | Binary branching, alternative handling |
elseis "otherwise". Like "if the score is 100 or more, show a victory message; otherwise, show an encouraging message," it handles both cases. Students develop a mindset of considering every possibility. If exceptional cases aren't handled, a program can behave unexpectedly. defensive programmingThey begin to learn the basics of it.
C. Elif Statements
| Item | Content |
|---|---|
| What will you learn? | Handling three or more cases |
| Core Concepts | Multiple branching, sequential condition checks |
elif(else if) checks multiple conditions in sequence. It handles three or more casessuch as grade calculation (A, B, C, D, F) or game difficulty selection (easy, normal, hard). Students learn that Order mattersorder matters, if an earlier condition is true, the rest are skipped. They develop the ability to systematically codecomplex decision-making processes.
D. Comparison Operators
| Item | Content |
|---|---|
| What will you learn? | Various ways to compare |
| Core Concepts | Relational operations, boolean results |
==, !=, <, >, <=, >=is compare two valuesand return true/false. ==(equals) and =(assignment): understanding the difference is important. They can be applied to various typessuch as string comparison, number comparison, and object comparison. Students write precise conditions so that the program behaves as intended. They also learn the importance of boundary testing: like the difference between < 10and <= 10.
E. Using Conditionals in Games
| Item | Content |
|---|---|
| What will you learn? | Implementing real game logic |
| Core Concepts | Game state, event handling, rule implementation |
A game is a collection of conditionals, you could say. Collision detection ("take damage when touching an enemy"), win/lose conditions ("reach 1000 points"), and state changes ("jump when the spacebar is pressed"): every game rule is a conditional. When playing games, students start to wonder "How was this rule coded?" Once they understand that even a complex game is a combination of small conditionals, they gain the confidencethat big problems can be broken into small parts.
When you finish this course...
Learning outcomes
Students will be able to:
- complex repeating patternsand implement them
- multi-condition branchessystematically
- game rules into conditionals
- use math formulas to create dynamic arrangements and patterns
- the indentation and structureof code correctly
- to learn more complex game logic (physics engines, AI, etc.) more complex game logic (movement, collisions, etc.)