Hey, you're back! I knew you would be. Once you start making things happen on screen, it's hard to stop, right?
Last chapter, we learned about switches—how to make decisions and route our code down different tracks. But here's a question: what happens when the train reaches the end of the track?
It stops. Game over. Program done.
But what if we don't WANT it to stop? What if we want the train to keep going... forever? Or at least until we tell it to stop?
That's where loops come in. And honestly? Loops are where programming gets REALLY fun.
The Circular Track
Picture a model train set. Not a straight track from A to B, but a circular one—the kind where the train just goes around and around and around, passing the same little plastic trees and tiny station over and over.
That's a loop! Your code goes around in circles, doing the same thing repeatedly.
"But Crash-tan," you might ask, "why would I want my code to do the same thing over and over?"
Great question! Here's why:
- Games need to keep running. Check input, update positions, draw everything—60 times per second, forever (or until the player quits).
- You need to process lots of stuff. Draw 100 stars in the sky? Loop! Check collision with 50 enemies? Loop! Count from 1 to 1000? You guessed it—loop!
- Waiting for something. Keep checking until the player presses a key. Keep moving until we hit a wall.
Loops are EVERYWHERE in games. Let's learn how to build them!
DO/LOOP: The Infinite Circle
The simplest loop in Crash BASIC is DO/LOOP. It's exactly what it sounds like: DO this stuff, then LOOP back and do it again.
DO
PRINT "Around and around we go!"
LOOPWARNING: Don't actually run that yet! It will print forever and ever and you'll have to force-quit the program. That's called an infinite loop, and while they're sometimes useful (game loops!), you need to be careful with them.
Let's make it safer by adding a way out:
count = 0
DO
PRINT "Loop number: "; count
count = count + 1
DELAY 500
LOOPThis still runs forever, but at least it waits half a second between prints so you can see what's happening. The train goes around the track, but it pauses at the station each time.
Breaking Free: EXIT DO
Sometimes you need to jump off the train. Maybe the player pressed Escape. Maybe we found what we were looking for. Whatever the reason, EXIT DO lets you break out of the loop immediately.
count = 0
DO
PRINT "Counting: "; count
count = count + 1
IF count >= 5 THEN
PRINT "That's enough!"
EXIT DO
END IF
DELAY 200
LOOP
PRINT "We escaped the loop!"
PAUSESee that? The train was going around in circles, but when count hit 5, we flipped a switch and derailed it right out of the loop. The code after LOOP then runs normally.
DO WHILE: Circle With a Checkpoint
What if you want to check a condition BEFORE each lap around the track? "Should I keep going? Yes? Okay, one more lap."
That's DO WHILE:
fuel = 10
DO WHILE fuel > 0
PRINT "Vroom! Fuel remaining: "; fuel
fuel = fuel - 1
DELAY 200
LOOP
PRINT "Out of gas!"
PAUSEThe train checks its fuel before each lap. "Do I have fuel? Yes? Keep going!" When fuel hits 0, the condition becomes FALSE, and the loop ends naturally.
This is super useful for games:
health = 100
DO WHILE health > 0
' Game stuff happens here
' Enemies might damage you
' health = health - damage
LOOP
PRINT "Game Over!"DO UNTIL: Circle Until Something Happens
DO UNTIL is the opposite of DO WHILE. Instead of looping while something is true, you loop until something becomes true.
password$ = ""
DO UNTIL password$ = "secret"
INPUT "Enter password: "; password$
LOOP
PRINT "Access granted!"
PAUSE"Keep asking until they get it right!" The loop runs until the condition becomes TRUE, then it stops.
DO WHILE and DO UNTIL are two sides of the same coin:
DO WHILE fuel > 0= Keep going while we have fuelDO UNTIL fuel <= 0= Keep going until we run out
Use whichever reads more naturally for your situation!
WHILE/WEND: The Classic Loop
There's another way to write a conditional loop: WHILE/WEND. It works just like DO WHILE:
countdown = 10
WHILE countdown > 0
PRINT countdown
countdown = countdown - 1
DELAY 500
WEND
PRINT "Blastoff!"
PAUSEWHILE checks the condition, runs the code, then WENDs back to check again. (WEND = "While END" - get it?)
Some programmers prefer WHILE/WEND because it's more traditional. Others prefer DO/LOOP because it's more flexible. Use whichever you like! They do the same thing.
FOR/NEXT: The Counted Loop
Sometimes you don't want to loop forever or until something happens. You want to loop a specific number of times: "Do this exactly 10 times."
That's what FOR/NEXT is for!
FOR i = 1 TO 10
PRINT "This is loop number "; i
NEXT i
PAUSELet's break it down:
FOR i = 1 TO 10— Start a counter callediat 1, and keep going until it reaches 10- The code inside runs with
iset to each value (1, then 2, then 3...) NEXT i— Add 1 toiand loop back
It's like telling the train: "Go around the track exactly 10 times, then stop."
Counting by Different Amounts
What if you want to count by 2s? Or backwards?
' Count by 2s
FOR i = 0 TO 10 STEP 2
PRINT i ' Prints: 0, 2, 4, 6, 8, 10
NEXT i
PRINT "---"
' Count backwards
FOR i = 10 TO 1 STEP -1
PRINT i ' Prints: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
NEXT i
PRINT "Liftoff!"
PAUSESTEP tells the loop how much to add (or subtract!) each time. STEP 2 counts by twos. STEP -1 counts backwards. STEP 0.5 would count by halves!
Loops Are Your Best Friend for Graphics
Remember Chapter 1, where I said games redraw everything 60 times per second? That's a loop! And loops are also how you draw lots of things without writing a million lines of code.
Want to draw 50 stars in the sky?
SCREEN 13
' Draw 50 random stars
FOR i = 1 TO 50
x = INT(RND * 320)
y = INT(RND * 100)
PSET (x, y), 15
NEXT i
PAUSEFifty stars with just a few lines of code! The loop runs 50 times, each time picking a random position and drawing a white dot.
Want a gradient effect?
SCREEN 13
FOR y = 0 TO 199
FOR x = 0 TO 319
COLOR = (x + y) MOD 256
PSET (x, y), COLOR
NEXT x
NEXT y
PAUSEThat's a loop INSIDE a loop! The outer loop goes through each row (y), and the inner loop goes through each column (x). Together they visit every single pixel on the screen. Loops inside loops are called nested loops, and they're super powerful.
The Game Loop: Putting It All Together
Every game has a main loop—the heartbeat that keeps everything running. Here's the basic structure:
SCREEN 13
' === SETUP ===
playerX = 160
playerY = 100
score = 0
gameOver = FALSE
' === GAME LOOP ===
DO UNTIL gameOver
' --- INPUT ---
k$ = INKEY$
IF k$ = CHR$(27) THEN gameOver = TRUE ' ESC to quit
' --- UPDATE ---
IF k$ = "a" THEN playerX = playerX - 3
IF k$ = "d" THEN playerX = playerX + 3
IF k$ = "w" THEN playerY = playerY - 3
IF k$ = "s" THEN playerY = playerY + 3
' Keep player on screen
IF playerX < 10 THEN playerX = 10
IF playerX > 310 THEN playerX = 310
IF playerY < 10 THEN playerY = 10
IF playerY > 190 THEN playerY = 190
' --- DRAW ---
BEGIN FRAME
CLS
CIRCLE (playerX, playerY), 8, 14
LOCATE 1, 1: PRINT "WASD to move, ESC to quit"
END FRAME
DELAY 16
LOOP
PRINT "Thanks for playing!"
PAUSELook at that beautiful loop! It:
- Checks for input
- Updates the game state
- Draws everything
- Repeats until gameOver becomes TRUE
This is the skeleton of EVERY game. The details change—more enemies, fancier graphics, complex physics—but the loop stays the same.
Putting It All Together
Loops let your code run in circles:
- DO/LOOP — The basic infinite loop
- EXIT DO — Break out of a loop early
- DO WHILE — Loop while a condition is true
- DO UNTIL — Loop until a condition becomes true
- WHILE/WEND — Classic conditional loop
- FOR/NEXT — Loop a specific number of times
- STEP — Count by different amounts
Every game is built on loops. The main game loop keeps everything running. Inner loops draw stars, check enemies, process input. Loops are the engine that makes your game GO.
Try It Yourself!
Here are some loop challenges:
- Countdown Timer: Use FOR to count down from 10 to 1, printing each number with a 1-second delay
- Starfield: Create a scrolling starfield (hint: redraw stars slightly lower each frame, reset them to the top when they go off-screen)
- Input Validator: Keep asking for a number until the player enters something between 1 and 100
- Drawing Patterns: Use nested FOR loops to draw a checkerboard pattern
Loops might feel repetitive (pun intended!), but mastering them is the key to making games that feel alive.
See you in Chapter 4!
Next Chapter: We'll organize our code with subroutines—because sometimes you need to send the train to a different station and have it come back!