Progress
1/8
Module 1Foundations

Why Loops? โ€” The Game Loop Concept

A loop is just "repeat until done." In games, this is the Game Loop โ€” the heartbeat of every game engine running 60 times per second, keeping your player's world alive.

The Mental Model

Real-World Analogy: Think of a conveyor belt at checkout โ€” items (frames) keep moving through scan โ†’ bag โ†’ receipt until the belt stops. Your game does the same: input โ†’ update โ†’ render, forever.

๐ŸŽฎ
processInput()
Read keyboard, mouse, controller every frame
โš™๏ธ
update()
Move entities, check collisions, run AI
๐Ÿ–ผ๏ธ
render()
Draw everything to screen, 60fps target
๐Ÿ”
Loop
Repeat until player quits or game ends

The Game Loop โ€” Every Engine Ever

GameLoop.java
// THE GAME LOOP โ€” runs 60 times per second!
while (gameIsRunning) {
    processInput();   // 1. Read keyboard/mouse/controller
    update();         // 2. Move entities, check collisions
    render();         // 3. Draw everything to screen
}
๐Ÿ’ก
KEY INSIGHT

Without loops, you'd need to write render() 3,600 times for just one minute of gameplay. Loops let computers do the repetitive work so you can focus on the fun stuff.

Why Java Has Four Loop Types

Loop TypeBest ForGame Example
forKnown countSpawn 10 enemies, tick 60fps timer
whileUnknown countGame loop, resource gathering, input wait
do-whileRun at least onceMenu systems, retry logic
for-eachCollectionsRender all entities, check all bullets
Quick Check
In a game loop, which order correctly represents the three main phases?
Input must come first so we know what changed, then we calculate the new state, then we draw it. This is the canonical game loop order.
1 of 8
Module 2Counted Iterations

The for Loop โ€” "I Know Exactly How Many Times"

Use the for loop when you know the exact number of iterations up front โ€” inventory slots, level counts, countdown timers. The three-part header puts initialization, condition, and update all in one visible line.

Anatomy of a for Loop

FOR LOOP ANATOMY
int i = 0 ; i < 10 ; i++ โ†’ { body }
โ‘  init โ€” runs once โ‘ก condition โ€” checked every time โ‘ข update โ€” runs after each body โ‘ฃ body โ€” your code here
ForSyntax.java
for (int i = 0; i < 10; i++) {
    // body runs 10 times (i = 0,1,2,...,9)
}
//   โ†‘ init    โ†‘ condition  โ†‘ update

๐ŸŽฎ Example 1: Inventory Slot Initialization

๐ŸŽฎ Game Dev Example
Inventory.java
// Create 20 empty inventory slots for an RPG
String[] inventory = new String[20];

for (int slot = 0; slot < inventory.length; slot++) {
    inventory[slot] = "[EMPTY]";
    System.out.println("Slot " + (slot + 1) + ": " + inventory[slot]);
}
// Output: Slot 1: [EMPTY] ... Slot 20: [EMPTY]

๐ŸŽฎ Example 2: Countdown Timer (Boss Fight Warning)

๐ŸŽฎ Game Dev Example
BossSpawn.java
System.out.println("โš”๏ธ BOSS SPAWNING IN:");

for (int seconds = 10; seconds >= 1; seconds--) {
    System.out.println(seconds + "...");
    // Thread.sleep(1000); // Uncomment for real delay
}

System.out.println("๐Ÿ’€ THE BOSS HAS ARRIVED!");
โš ๏ธ
COUNTDOWN TIP

Notice the loop counts DOWN: seconds = 10; seconds >= 1; seconds--. The init starts high, condition checks it's still positive, and the update decrements.

๐ŸŽฎ Example 3: XP Table Generator

๐ŸŽฎ Game Dev Example
XPTable.java
// Exponential XP curve โ€” common in RPGs
for (int level = 1; level <= 20; level++) {
    int xpRequired = (int) (100 * Math.pow(1.5, level - 1));
    System.out.printf("Level %2d โ†’ %,d XP%n", level, xpRequired);
}
// Level  1 โ†’     100 XP
// Level  2 โ†’     150 XP
// Level 20 โ†’ 221,683 XP
Quick Check
How many times does this loop execute?
for (int i = 5; i <= 10; i++)
The loop runs for i = 5, 6, 7, 8, 9, 10 โ€” that's 6 iterations. The condition is <= (less than OR EQUAL TO), so 10 is included.
๐ŸŸข Easy Challenge

Spell Cooldown Display

Write a for loop that prints all 5 spells in an array with their cooldown in seconds. Cooldowns: {3, 5, 8, 12, 20}.

  • Print: Fireball: 3s cooldown (one per spell)
  • Use String[] for names, int[] for cooldowns
  • Bonus: mark spells with cooldown > 10 as "LONG"
2 of 8
Module 3Condition-Driven

The while Loop โ€” "Keep Going While True"

Use while when you don't know how many iterations you'll need โ€” only when to stop. The condition is checked before each iteration. If it starts false, the body never runs.

for loop

When you know how many times

for (int i=0; i<10; i++)

Counter is built-in, clean syntax

while loop

When you know the stop condition

while (playerIsAlive)

Flexible, works for unknown counts

WhileSyntax.java
while (condition) {
    // body โ€” condition checked BEFORE each iteration
    // if condition starts false, body NEVER runs
}

๐ŸŽฎ Example 1: Input Validation (Menu System)

๐ŸŽฎ Game Dev Example
MenuSystem.java
Scanner scanner = new Scanner(System.in);
int choice = -1;

while (choice < 1 || choice > 4) {
    System.out.println("""
        === MAIN MENU ===
        1. New Game
        2. Load Game
        3. Settings
        4. Quit
        Choose (1-4): """);
    
    if (scanner.hasNextInt()) {
        choice = scanner.nextInt();
        if (choice < 1 || choice > 4)
            System.out.println("โŒ Invalid! Enter 1-4.");
    } else {
        System.out.println("โŒ Numbers only!");
        scanner.next(); // consume bad input
    }
}
System.out.println("โœ… You chose: " + choice);

๐ŸŽฎ Example 2: Resource Gathering (Idle Game Mechanic)

๐ŸŽฎ Game Dev Example
ResourceGathering.java
int gold = 0;
int workers = 3;
int targetGold = 1000;

System.out.println("โ›๏ธ Mining gold... (target: " + targetGold + ")");

while (gold < targetGold) {
    gold += workers * 5; // each worker mines 5 gold/tick
    System.out.printf("Gold: %,d | Workers: %d%n", gold, workers);
    
    // Hire more workers at milestones
    if (gold >= 500 && workers == 3) {
        workers = 5;
        System.out.println("๐ŸŽ‰ Hired 2 more workers!");
    }
}
System.out.println("๐Ÿ’ฐ Target reached! Total: " + gold);
๐Ÿšจ
INFINITE LOOP DANGER

Always make sure something inside the loop eventually makes the condition false. A while(true) loop with no break will freeze your program โ€” and your game!

Quick Check
If the condition is false when a while loop is first reached, what happens?
The while loop checks the condition BEFORE each iteration. If it's false immediately, the body is skipped entirely โ€” zero executions. This is what makes it different from do-while.
3 of 8
Module 4Guaranteed Execution

The do-while Loop โ€” "Run Once, Then Check"

The do-while loop guarantees the body runs at least once before checking the condition. Perfect for menu systems, retry logic, and any situation where you need one initial action before deciding to repeat.

The Key Difference

LoopChecks ConditionGuaranteed First Run?Use When
whileBefore each iterationโŒ NoCondition may already be false
do-whileAfter each iterationโœ… YesMust execute once regardless
DoWhileSyntax.java
do {
    // body runs FIRST
    // THEN condition is checked
} while (condition); // โ† semicolon required!

๐ŸŽฎ Example 1: Retry Mechanism (Server Connection)

๐ŸŽฎ Game Dev Example
ConnectionRetry.java
int maxAttempts = 3;
int attempt = 0;
boolean connected = false;

do {
    attempt++;
    System.out.println("๐Ÿ”„ Attempt " + attempt + " of " + maxAttempts);
    
    connected = Math.random() < 0.3; // 30% success rate
    
    if (!connected && attempt < maxAttempts)
        System.out.println("โŒ Failed. Retrying...");
        
} while (!connected && attempt < maxAttempts);

if (connected)
    System.out.println("โœ… Connected to game server!");
else
    System.out.println("๐Ÿ’ฅ Failed after " + maxAttempts + " attempts.");

๐ŸŽฎ Example 2: Play Again Prompt

๐ŸŽฎ Game Dev Example
PlayAgain.java
Scanner scanner = new Scanner(System.in);
String playAgain;

do {
    playGame(); // Your game logic here โ€” always runs first!
    
    System.out.print("\n๐ŸŽฎ Play again? (y/n): ");
    playAgain = scanner.nextLine().trim().toLowerCase();
    
} while (playAgain.equals("y") || playAgain.equals("yes"));

System.out.println("๐Ÿ‘‹ Thanks for playing!");
โœ…
WHEN TO CHOOSE do-while

Ask yourself: "Is it possible I should skip this entirely?" If yes โ†’ while. If no, it must happen at least once โ†’ do-while. Menu systems, first attempts, and initial prompts almost always use do-while.

Quick Check
You're building a "retry login" feature. The user must attempt login at least once. Which loop should you use?
The do-while guarantees the body (the login attempt) runs at least once before checking whether to retry. A while loop could theoretically skip the attempt entirely if the condition was somehow false from the start.
4 of 8
Module 5Collections Made Easy

Enhanced for Loop โ€” "For Each Item in Collection"

The enhanced for (or "for-each") loop gives you clean syntax for iterating over arrays and collections. No index arithmetic, no off-by-one errors โ€” just "for each item, do this."

ForEachSyntax.java
for (Type item : collection) {
    // use item directly โ€” no index needed!
    // works with arrays, Lists, Sets, and more
}
Traditional for

Need the index variable

Can modify the array

Risk of off-by-one

Enhanced for

Cleaner, no index needed

Read-only (can't modify source)

Cannot skip or reverse

๐ŸŽฎ Example 1: Displaying Player Inventory

๐ŸŽฎ Game Dev Example
InventoryDisplay.java
List<String> inventory = Arrays.asList(
    "๐Ÿ—ก๏ธ Iron Sword", "๐Ÿ›ก๏ธ Wooden Shield", "๐Ÿงช Health Potion",
    "๐Ÿงช Mana Potion", "๐Ÿ’ฐ Gold Coin x50", "๐Ÿ—๏ธ Dungeon Key"
);

System.out.println("๐ŸŽ’ YOUR INVENTORY:");
int slot = 1;
for (String item : inventory) {
    System.out.println("  [" + slot++ + "] " + item);
}
// [1] ๐Ÿ—ก๏ธ Iron Sword
// [2] ๐Ÿ›ก๏ธ Wooden Shield ... etc

๐ŸŽฎ Example 2: Calculating Total Damage

๐ŸŽฎ Game Dev Example
CombatDamage.java
int[] hits = {15, 22, 8, 30, 18, 25};
int totalDamage = 0;
int critCount = 0;

for (int damage : hits) {
    totalDamage += damage;
    if (damage >= 25) critCount++;
    System.out.println("  Hit: " + damage + " dmg");
}

System.out.println("๐Ÿ’ฅ Total: " + totalDamage + " | Crits: " + critCount);

๐ŸŽฎ Example 3: Leaderboard Display

๐ŸŽฎ Game Dev Example
Leaderboard.java
record PlayerScore(String name, int score) {}

List<PlayerScore> leaderboard = List.of(
    new PlayerScore("ShadowStrike", 98750),
    new PlayerScore("PixelPwner", 87650),
    new PlayerScore("CodeCrusher", 82340)
);

System.out.println("๐Ÿ† GLOBAL LEADERBOARD:");
int rank = 1;
for (PlayerScore p : leaderboard) {
    String medal = switch (rank) {
        case 1 -> "๐Ÿฅ‡"; case 2 -> "๐Ÿฅˆ"; case 3 -> "๐Ÿฅ‰"; default -> "  ";
    };
    System.out.printf("%s #%-2d %-15s %,d%n", medal, rank++, p.name(), p.score());
}
Quick Check
When should you use a traditional for loop instead of the enhanced for loop?
The enhanced for is read-only and index-free. Use a traditional for when you need i (to modify elements via arr[i] = x, to iterate backwards, or to skip certain indexes).
5 of 8
Module 6Grids & Matrices

Nested Loops โ€” Grids, Boards & Tile Maps

Nested loops are the key to working with 2D data. Every tile map, game board, pixel buffer, and grid system in game development uses this pattern: outer loop handles rows, inner loop handles columns.

NestedPattern.java
for (int row = 0; row < rows; row++) {       // OUTER: rows
    for (int col = 0; col < cols; col++) {   // INNER: columns
        // Process cell [row][col]
        // Inner loop completes ALL columns before outer advances
    }
}
๐Ÿ’ก
MENTAL MODEL

Think of a book: the outer loop turns pages (rows), the inner loop reads each word on that page (columns). When you finish a row, you start the next one from the beginning.

๐ŸŽฎ Example 1: Tic-Tac-Toe Board

๐ŸŽฎ Game Dev Example
TicTacToe.java
char[][] board = {
    {'X', 'O', 'X'},
    {'O', 'X', ' '},
    {' ', 'O', 'X'}
};

System.out.println("  0 1 2");
for (int r = 0; r < board.length; r++) {
    System.out.print(r + " ");
    for (int c = 0; c < board[r].length; c++) {
        System.out.print(board[r][c]);
        if (c < 2) System.out.print("|");
    }
    if (r < 2) System.out.println("\n  -----");
}
// Output:
//   0 1 2
// 0 X|O|X
//   -----
// 1 O|X|
//   -----
// 2  |O|X

๐ŸŽฎ Example 2: Tile Map Renderer

๐ŸŽฎ Game Dev Example
TileMap.java
// Legend: G=Grass, W=Water, T=Tree, P=Player
char[][] world = {
    {'G','G','G','W','W','W'},
    {'G','T','G','W','W','W'},
    {'G','G','P','G','G','G'},
};

for (int r = 0; r < world.length; r++) {
    for (int c = 0; c < world[r].length; c++) {
        String emoji = switch (world[r][c]) {
            case 'G' -> "๐ŸŸข"; case 'W' -> "๐Ÿ”ต";
            case 'T' -> "๐ŸŒฒ"; case 'P' -> "๐Ÿง";
            default -> "โ“";
        };
        System.out.print(emoji + " ");
    }
    System.out.println();
}
// ๐ŸŸข ๐ŸŸข ๐ŸŸข ๐Ÿ”ต ๐Ÿ”ต ๐Ÿ”ต
// ๐ŸŸข ๐ŸŒฒ ๐ŸŸข ๐Ÿ”ต ๐Ÿ”ต ๐Ÿ”ต
// ๐ŸŸข ๐ŸŸข ๐Ÿง ๐ŸŸข ๐ŸŸข ๐ŸŸข

๐ŸŽฎ Example 3: RPG Stat Scaling Table

๐ŸŽฎ Game Dev Example
StatScaling.java
System.out.println("   STR:  5  10  15  20  25");
System.out.println("LVL  ---------------------");
for (int level = 1; level <= 5; level++) {
    System.out.printf("%-4d", level);
    for (int str : new int[]{5, 10, 15, 20, 25}) {
        int damage = level * str / 2;
        System.out.printf("%4d", damage);
    }
    System.out.println();
}
๐ŸŸก Medium Challenge

Dungeon Generator

Create a 10ร—10 dungeon map using nested loops:

  • Fill the border cells (row 0, row 9, col 0, col 9) with walls '#'
  • Fill interior cells with floor tiles '.'
  • Place a player '@' at position (5, 5)
  • Render it with nested loops, printing each row on its own line
6 of 8
Module 7Precision Control

Loop Control โ€” break, continue & Labels

Sometimes you need to exit a loop early or skip an iteration. break and continue give you precise control over loop flow โ€” and labeled versions let you escape nested loops entirely.

StatementEffectCommon Use
breakExit the loop immediatelyFound what you were searching for
continueSkip to next iterationSkip invalid/null items
label: + break labelExit outer (nested) loopsFound in 2D grid, stop all loops

๐ŸŽฎ Example 1: Search Inventory (break)

๐ŸŽฎ Game Dev Example
InventorySearch.java
String[] inventory = {"Sword", "Shield", "Potion", "Key", "Map"};
String target = "Key";

for (int i = 0; i < inventory.length; i++) {
    System.out.println("  Checking slot " + i + ": " + inventory[i]);
    if (inventory[i].equals(target)) {
        System.out.println("  โœ… Found at slot " + i + "!");
        break; // Stop searching โ€” we found it!
    }
}
// Checking slot 0: Sword
// Checking slot 1: Shield
// Checking slot 2: Potion
// Checking slot 3: Key
// โœ… Found at slot 3!

๐ŸŽฎ Example 2: Process Valid Items (continue)

๐ŸŽฎ Game Dev Example
LootProcessing.java
String[] loot = {"Gold", null, "Sword", "", "Potion", "Gem"};
int validCount = 0;

for (String item : loot) {
    if (item == null || item.trim().isEmpty()) {
        System.out.println("  โš ๏ธ Skipping empty slot");
        continue; // Skip to next item
    }
    System.out.println("  โœ… Added: " + item);
    validCount++;
}
System.out.println("Total valid: " + validCount);

๐ŸŽฎ Example 3: Labeled break (Find Player in Grid)

๐ŸŽฎ Game Dev Example
GridSearch.java
int[][] dungeon = {
    {0, 0, 0, 0},
    {0, 1, 0, 2}, // 1=Player, 2=Exit
    {0, 0, 0, 0}
};

int playerRow = -1, playerCol = -1;

searchLoop: // Label the OUTER loop
for (int r = 0; r < dungeon.length; r++) {
    for (int c = 0; c < dungeon[r].length; c++) {
        if (dungeon[r][c] == 1) {
            playerRow = r;
            playerCol = c;
            break searchLoop; // Breaks BOTH loops at once!
        }
    }
}
System.out.println("๐Ÿง Player at (" + playerRow + ", " + playerCol + ")");
โš ๏ธ
USE LABELS SPARINGLY

Labels can make code hard to read. In production, consider refactoring the nested loop into a separate method that returns early. But for grid searches and game map traversal, labels are perfectly valid.

Quick Check
What does continue do inside a loop body?
continue skips the remaining code in the current iteration and jumps to the update step (for for loops) or rechecks the condition (for while loops). The loop itself keeps going โ€” only that one iteration is cut short.
7 of 8
Module 8Capstone Project

Capstone โ€” Turn-Based Combat Prototype

Put it all together. This mini game engine uses every loop type you've learned โ€” while for the main game loop, do-while for combat rounds, nested while for input validation, and for-each to iterate enemies.

Architecture Overview

๐Ÿ”„
while โ€” Main Loop
Runs while game isn't over and there are enemies left
โš”๏ธ
do-while โ€” Combat
Each combat round โ€” always executes at least one turn
๐Ÿ–Š๏ธ
while โ€” Input
Validates menu choice, retries on invalid input
๐Ÿ“‹
for-each โ€” Enemies
Iterates enemy list for wave setup and status

Full Combat Engine

CombatDemo.java
import java.util.*;

public class CombatDemo {
    record Entity(String name, int hp, int maxHp, int atk, int def) {}
    
    public static void main(String[] args) {
        Entity player = new Entity("๐Ÿง™ Hero", 100, 100, 15, 5);
        List<Entity> enemies = Arrays.asList(
            new Entity("๐Ÿ€ Rat",    30,  30,  8,  2),
            new Entity("๐Ÿบ Wolf",   50,  50, 12,  4),
            new Entity("๐Ÿ‰ Dragon", 200, 200, 25, 10)
        );
        
        Scanner sc = new Scanner(System.in);
        boolean gameOver = false;
        int wave = 1;
        
        // โ•โ•โ•โ• MAIN GAME LOOP (while) โ•โ•โ•โ•
        while (!gameOver && wave <= enemies.size()) {
            Entity enemy = enemies.get(wave - 1);
            System.out.println("\nโ•โ•โ• WAVE " + wave + ": " + enemy.name() + " โ•โ•โ•");
            
            // โ•โ•โ•โ• COMBAT LOOP (do-while) โ•โ•โ•โ•
            do {
                printStatus(player, enemy);
                
                // โ•โ•โ•โ• INPUT VALIDATION (while) โ•โ•โ•โ•
                int choice = -1;
                while (choice < 1 || choice > 3) {
                    System.out.print("[1] Attack  [2] Heal  [3] Flee: ");
                    if (sc.hasNextInt()) choice = sc.nextInt();
                    else sc.next();
                }
                
                switch (choice) {
                    case 1 -> attack(player, enemy);
                    case 2 -> heal(player);
                    case 3 -> { System.out.println("๐Ÿƒ You fled!"); gameOver = true; }
                }
                
                if (enemy.hp() > 0 && !gameOver) enemyAttack(enemy, player);
                if (player.hp() <= 0) { System.out.println("โ˜ ๏ธ YOU DIED."); gameOver = true; }
                
            } while (enemy.hp() > 0 && player.hp() > 0 && !gameOver);
            
            if (!gameOver) { System.out.println("๐ŸŽ‰ Defeated! +50 XP"); wave++; }
        }
        
        if (!gameOver) System.out.println("\n๐Ÿ† VICTORY! All waves cleared!");
        sc.close();
    }
}

Quick Reference Cheatsheet

for (i; c; u)Known iteration count โ€” inventory, timers, levels
while (cond)Unknown count, check FIRST โ€” game loop, gathering
do { } whileRun ONCE minimum โ€” menus, retry, play-again
for (x : xs)Iterate collection/array โ€” inventory, enemies
breakExit loop NOW โ€” found target, player fled
continueSkip to next iteration โ€” skip null/empty items
label: breakBreak OUTER loop from INNER โ€” grid search

Practice Exercises

1
FizzBuzz โ€” Print 1-100 with game twist
for10 min
2
Guess the Number โ€” with hints (higher/lower)
whiledo-while15 min
3
Shopping Cart โ€” add/remove/view/checkout
for-eachwhile25 min
4
Chessboard โ€” print 8ร—8 with coordinates
nested for20 min
5
Find First Prime > 1000
forbreaklabel15 min
6
Text-based RPG โ€” fight 3 enemies, all loop types
ALL45 min
๐Ÿš€
NEXT STEPS

Now that you've mastered loops, move on to Arrays & ArrayLists โ€” loops are how you'll work with every collection. The combination is where real game code lives.

8 of 8
Roadmap