Back

Activity 1.22: Raylib Lab 5 — The Invasion Is a Grid

HomeworkBuilt at home. Verified in class at the start of the next session.

divider

What You're Building

Thirty-two invaders in formation, marching side to side and dropping closer to the ground every time they reach a wall. These are three moments from the same running program.

Four rows of eight green invaders near the top of a black window, a counter reading Invaders: 32 in the corner, and a gray ground line along the bottom

The first frame

The same formation partway down the window, shifted toward the left

Seven bounces in

The formation's bottom row resting on the gray ground line against the left wall, with THEY LANDED in red across the middle of the window

They landed

Nothing on this page is a new kind of code. You have nested loops from Activity 1.21, for from Activity 1.19, the game loop from Activity 1.18, and the idea of one number driving a whole drawing from Lab 2. What is new is putting them together: the loop counters stop being counts and start being positions.

divider

Activity 1.22

Raylib Lab 5 — The Invasion Is a Grid

Key Concepts

Loop Counters Become Coordinates

A Loop Inside a Loop Draws a Grid

One Reference Point Moves Everything

Activity 1.21's Grid Could Not Aim

for (int row = 1; row <= 4; row++)
{
for (int col = 1; col <= 6; col++)
{
Console.Write("* ");
}
Console.WriteLine();
}

This is the grid from Activity 1.21, Task 2: four rows of six stars. You ran it, so you already know what it prints.

Activity 1.21's Grid Could Not Aim

Terminal window
* * * * * *
* * * * * *
* * * * * *
* * * * * *

Every star landed wherever the one before it left off. You could ask for six in a row, but you could never ask for a star at 200 pixels — the terminal decided where each one went, not you.

A Raylib window has no “next spot.” Every rectangle needs its own x and y, so today the loop has to work them out.

The Column Number Becomes an x

Activity 1.19 taught you to read col = 0; col < 8 as “eight times.” Today the counter does a second job as well.

Multiply it by the spacing, add the left edge, and every pass of the loop gets its own position — one spacing further right than the pass before it.

The Column Number Becomes an x

for (int col = 0; col < cols; col++)
{
int x = formationX + col * spacingX;
Raylib.DrawRectangle(x, formationY, invaderWidth, invaderHeight, Color.Green);
}
Value Trace
formationX = 60, spacingX = 56
col 0 x = 60 + 0 * 56 = 60
col 1 x = 60 + 1 * 56 = 116
col 2 x = 60 + 2 * 56 = 172
...
col 7 x = 60 + 7 * 56 = 452

Why the First Invader Is Column 0

Look at column 0 in that trace again: 60 + 0 * 56 is just 60, which is formationX exactly.

The first invader sits on the formation's own corner, with no adjustment and no “minus one” anywhere. The first item is zero steps from the start, so its number is zero.

That is the reason Activity 1.19 said programmers start at zero. Task 1 has you start at 1 instead, and asks you to predict which invader disappears.

Put the Row Inside Another Loop

for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
int x = formationX + col * spacingX;
int y = formationY + row * spacingY;
Raylib.DrawRectangle(x, y, invaderWidth, invaderHeight, Color.Green);
}
}

The row number does for y exactly what the column number does for x. Before you look: with 4 rows and 8 columns, how many invaders does this draw?

Put the Row Inside Another Loop

Four rows of eight green invaders near the top of a black window, with Invaders: 32 in the corner

Thirty-two. Four passes of the outer loop, and the inner loop runs all eight columns on every one of them.

That is the same multiplication as Activity 1.21's rows and seats. The counter in the corner counts them for you in Task 2.

Thirty-Two Invaders, One Number That Moves

No invader has a position of its own. There is no variable anywhere that holds “invader 14’s x.”

Every x is worked out from formationX again on every frame, so changing that one number moves all thirty-two at once. That is Lab 2's gap again: one number, and everything drawn from it follows.

Thirty-Two Invaders, One Number That Moves

while (!Raylib.WindowShouldClose())
{
formationX = formationX + speedX;
// ...then draw all 32 from it
}
The formation partway down the window after several bounces

One line moves the formation — the same “change a variable inside the game loop” that made Activity 1.18's ball fall.

The Formation Has to Know How Wide It Is

To turn around at the right wall, the program has to know where the formation's right edge is. That edge is the left edge plus the formation's width.

int formationWidth = (cols - 1) * spacingX + invaderWidth;

Why cols - 1 and not cols? Decide before the next slide.

The Formation Has to Know How Wide It Is

Value Trace
cols = 8, spacingX = 56, invaderWidth = 40
formationWidth = (8 - 1) * 56 + 40
= 7 * 56 + 40
= 392 + 40
= 432

Eight invaders have seven gaps between them. Seven spacings reach the left edge of the last invader, and one more invaderWidth reaches its right edge. Lab 2's housing counted two gaps between three lamps for the same reason.

Because it is worked out from cols, it stays right when cols changes. Task 4 shows you what happens when the picture and this number stop agreeing.

You Still Cannot Shoot One

A blue cannon on the ground firing a yellow shot up at the full formation; the corner reads Invaders: 32 and Hits: 24

This is the optional challenge at the bottom of the page: a cannon, a shot, and a hit counter.

Twenty-four hits, and thirty-two invaders still standing.

Every frame, the loop draws all thirty-two, because nothing in the program remembers that one of them was hit. You could write thirty-two separate bool variables, and nobody would.

Activity 1.23 gives one name to a whole list of values — which is exactly what a formation that can lose an invader needs.

Today's Objectives

  • Drawing a grid with a loop inside a loop
  • Turning loop counters into screen coordinates
  • Moving a whole formation by changing one reference point
  • Working out a size from the values it depends on

Key Terms

Grid
Items arranged in rows and columns, drawn here by a loop inside a loop.
Reference point
The one position everything else is measured from. Here, that is formationX and formationY.
Offset
A distance measured from the reference point, like col * spacingX.

'F' → Fullscreen

divider

Build

Everything today goes in a new program named 1-22-invaders. Nothing carries over from Lab 4.

How to read the code blocks. Each task's code block shows your whole program, from line 1, as it should look when that task is finished.

The green lines marked with a + are the ones you add or change for that task — everything else is already in your file. Do not type the + sign.

This lab needs the workspace, not Juicemind — same as Labs 1 through 4. Close the window to end the program. Escape works too.


Task 1: One Row

  • Write the code below and run it. You should get one row of eight invaders across the top of the window, matching the picture.
  • Find the x of the last invader by hand using formationX + col * spacingX. The last column is 7, not 8.
  • Change int col = 0 to int col = 1, but predict first: how many invaders will there be, and does the one on the left or the one on the right disappear? Write your prediction down, run it, then put it back.
  • Change spacingX to 40 — the same as invaderWidth — and run it. Say what happened to the gaps and why, then put it back to 56.
One row of eight green invaders with black eyes across the top of a black window

One row of eight

1-22-invaders
#:package Raylib-cs@8.0.0
using Raylib_cs;
int screenWidth = 640;
int screenHeight = 480;
int cols = 8;
int invaderWidth = 40;
int invaderHeight = 24;
int spacingX = 56;
int formationX = 60;
int formationY = 50;
Raylib.InitWindow(screenWidth, screenHeight, "Invaders");
Raylib.SetTargetFPS(60);
while (!Raylib.WindowShouldClose())
{
Raylib.BeginDrawing();
Raylib.ClearBackground(Color.Black);
for (int col = 0; col < cols; col++)
{
int x = formationX + col * spacingX;
int y = formationY;
Raylib.DrawRectangle(x, y, invaderWidth, invaderHeight, Color.Green);
Raylib.DrawRectangle(x + 8, y + 6, 6, 6, Color.Black);
Raylib.DrawRectangle(x + 26, y + 6, 6, 6, Color.Black);
}
Raylib.EndDrawing();
}
Raylib.CloseWindow();

Task 2: The Formation

  • Add rows and spacingY, then put your row loop inside a new loop over the rows. Every line of your Task 1 loop moves one level in, so the whole block is marked — you are re-indenting it, not retyping it.
  • y now uses row the same way x uses col.
  • Predict the number on the counter before you run it. Then run it and check.
  • Look at where int drawn = 0; sits: inside the game loop, so it starts again from zero on every frame. Task 4 moves it.
1-22-invaders
#:package Raylib-cs@8.0.0
using Raylib_cs;
int screenWidth = 640;
int screenHeight = 480;
int rows = 4;
int cols = 8;
int invaderWidth = 40;
int invaderHeight = 24;
int spacingX = 56;
int spacingY = 40;
int formationX = 60;
int formationY = 50;
Raylib.InitWindow(screenWidth, screenHeight, "Invaders");
Raylib.SetTargetFPS(60);
while (!Raylib.WindowShouldClose())
{
Raylib.BeginDrawing();
Raylib.ClearBackground(Color.Black);
int drawn = 0;
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
int x = formationX + col * spacingX;
int y = formationY + row * spacingY;
Raylib.DrawRectangle(x, y, invaderWidth, invaderHeight, Color.Green);
Raylib.DrawRectangle(x + 8, y + 6, 6, 6, Color.Black);
Raylib.DrawRectangle(x + 26, y + 6, 6, 6, Color.Black);
drawn = drawn + 1;
}
}
Raylib.DrawText($"Invaders: {drawn}", 10, 10, 20, Color.White);
Raylib.EndDrawing();
}
Raylib.CloseWindow();
Four rows of eight invaders, with Invaders: 32 in the top corner

The full formation


Task 3: March and Land

  • Add the formation's width and height, the speed, the drop, the ground, and landed, then the movement block at the top of the game loop.
  • speedX = 0 - speedX; flips the direction: 2 becomes -2, and -2 becomes 2 again. Every time it flips, the formation also drops by dropAmount.
  • Before you run it, work out how many bounces it takes to land. The bottom of the formation starts at formationY + formationHeight, each bounce drops it 16 pixels, and the ground is at 450. Then run it and count the bounces as you watch.
  • Change rows to 6 and cols to 5 and run it. The formation still turns around exactly at both walls. Say which line made that true — you did not touch it. Then put both back.
1-22-invaders
#:package Raylib-cs@8.0.0
using Raylib_cs;
int screenWidth = 640;
int screenHeight = 480;
int rows = 4;
int cols = 8;
int invaderWidth = 40;
int invaderHeight = 24;
int spacingX = 56;
int spacingY = 40;
int formationX = 60;
int formationY = 50;
int formationWidth = (cols - 1) * spacingX + invaderWidth;
int formationHeight = (rows - 1) * spacingY + invaderHeight;
int speedX = 2;
int dropAmount = 16;
int groundY = 450;
bool landed = false;
Raylib.InitWindow(screenWidth, screenHeight, "Invaders");
Raylib.SetTargetFPS(60);
while (!Raylib.WindowShouldClose())
{
if (!landed)
{
formationX = formationX + speedX;
if (formationX + formationWidth >= screenWidth || formationX <= 0)
{
speedX = 0 - speedX;
formationY = formationY + dropAmount;
}
if (formationY + formationHeight >= groundY)
{
landed = true;
}
}
Raylib.BeginDrawing();
Raylib.ClearBackground(Color.Black);
int drawn = 0;
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
int x = formationX + col * spacingX;
int y = formationY + row * spacingY;
Raylib.DrawRectangle(x, y, invaderWidth, invaderHeight, Color.Green);
Raylib.DrawRectangle(x + 8, y + 6, 6, 6, Color.Black);
Raylib.DrawRectangle(x + 26, y + 6, 6, 6, Color.Black);
drawn = drawn + 1;
}
}
Raylib.DrawRectangle(0, groundY, screenWidth, 4, Color.Gray);
Raylib.DrawText($"Invaders: {drawn}", 10, 10, 20, Color.White);
if (landed)
{
Raylib.DrawText("THEY LANDED", 174, 220, 40, Color.Red);
}
Raylib.EndDrawing();
}
Raylib.CloseWindow();
The formation's bottom row resting on the ground line, with THEY LANDED across the middle

The bottom row lands exactly on the ground


Task 4: Break It on Purpose

Two changes, one at a time. Screenshot or describe what you see each time, and put it back before the next.

  1. Move int drawn = 0; so it sits above the while line instead of inside the loop, and run it. Watch the counter for a few seconds, and work out how much it goes up on each frame.
  2. Put it back. Now change the inner loop's col < cols to col <= row, and run it. Record the shape, the counter, and where the formation turns around at the right side of the window.

Neither one is an error. Both compile, and neither warns you about anything. In the first, the picture is perfect and the number is wrong. In the second, the picture changed and one number did not. Say which number, in each case.


Challenge (Optional): Fire Back

  • Add a cannon on the ground that moves with the arrow keys. It sits at groundY - cannonHeight, and the arrow keys work exactly like Activity 1.18's paddle.
  • Space fires one shot straight up from the middle of the cannon, but only when no shot is already flying. A bool shotFlying keeps track, and IsKeyPressed from Lab 3 is the right key check here.
  • The shot moves up a few pixels every frame and stops flying when it leaves the top of the window.
  • The hit check goes inside the inner loop, because that is the only place x and y exist. It is the same kind of && chain as Activity 1.18's catch, with four parts instead of three:
Inside the inner loop, after drawing
if (shotFlying && shotX >= x && shotX <= x + invaderWidth && shotY >= y && shotY <= y + invaderHeight)
{
hits = hits + 1;
shotFlying = false;
}
  • Show hits on screen next to the invader counter, and play it.
  • Write a comment explaining why the invader you hit is back on the very next frame.
divider

Checkpoint

Your two broken versions from Task 4 should look like this.

The full formation looking completely normal, but the counter in the corner reads Invaders: 3840

Task 4, change 1 — two seconds in

A staircase of invaders, one in the top row up to four in the bottom row, with the counter reading Invaders: 10. The formation has turned around far from the right wall

Task 4, change 2 — turning around at the right side

Look at where the staircase turned around. Its right edge is more than 200 pixels from the wall, because formationWidth was worked out before the loop ever ran and still says eight columns. The picture changed; the number the bounce believes did not.

  • The formation is four rows of eight, the counter says 32, and you can say where 32 comes from without counting
  • It marches, bounces, drops, and lands exactly on the ground line
  • Your bounce prediction is written down next to the count you actually saw
  • Both Task 4 results are recorded, with which number was wrong in each
  • Be ready for this in class: you will be asked to make one change to the formation on the spot.
divider

Reflection

Answer the following questions before submitting your work.

  1. No invader has a position of its own, yet changing formationX moves all thirty-two. Explain how, and compare it to what gap did in Lab 2.
  2. In Task 4's first change, the counter climbed into the thousands while the picture stayed exactly right. Explain what that tells you about where drawn has to start, and why the game loop is what makes that matter.
  3. In Task 4's second change, the formation turned around far from the right wall. Explain why, using formationWidth, and describe what would have to change for the bounce to match the picture again.
divider

Submit

Submit four things to the dropbox:

  1. Your 1-22-invaders program file, with rows at 4 and cols at 8.
  2. Your Task 1 prediction with what really happened, and your Task 3 bounce prediction with the count you saw.
  3. Your two Task 4 results, with which number was wrong in each.
  4. Your three reflection answers.

Activity Complete