Back

Activity 1.26: Raylib Lab 6 — Drawing From Data

divider

What You're Building

Eight invaders scattered across the sky, a cannon on the ground, and this time an invader you hit stays gone. Clear all eight in as few shots as you can.

Four green invaders left in a black window, a yellow shot climbing toward one of them from a blue cannon on the ground, and the corners reading Invaders: 4 and Shots: 5

In Lab 5 every invader came back on the very next frame, because nothing in the program remembered that it had been hit. Activities 1.23 through 1.25 built the tool that fixes it: an array. Today the positions come from arrays, and so does the memory of which invaders are gone.

divider

Activity 1.26

Raylib Lab 6 — Drawing From Data

Key Concepts

Positions Stored, Not Worked Out

Two Arrays Have to Agree

An Array That Remembers

Counting What Is Left

Lab 5's Invaders Would Not Stay Shot

Activity 1.22 ended on an optional challenge: a cannon, a shot, and a counter for every hit. The shots landed and the counter climbed.

Before the next slide, remember what happened to an invader after you hit it. If you did not try the challenge, guess.

Lab 5's Invaders Would Not Stay Shot

Lab 5's full formation of thirty-two invaders with a cannon firing at it; the corner reads Invaders: 32 and Hits: 24

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

Every frame, the nested loop drew every invader again, because that was all it knew how to do. There was no variable anywhere that said “this one is gone.”

Fixing that takes one yes-or-no answer per invader, kept from one frame to the next. An array can hold exactly that, and today you build it.

A Formula Can Only Draw a Pattern

Lab 5 worked out every invader's x with one line, and that line is why the formation was a perfect grid:

int x = formationX + col * spacingX;

Every invader lands exactly one spacing from the last. That is what a formula does well, and it is also all it can do. No value of col puts an invader at 40, then 150, then 260 — those numbers follow no rule.

So store the positions instead. One array holds every x and another holds every y, in the same order. The loop reads them rather than working them out.

A Formula Can Only Draw a Pattern

Demo
int[] xs = { 40, 150, 260 };
int[] ys = { 70, 50, 100 };
for (int i = 0; i < xs.Length; i++)
{
Console.WriteLine($"Invader {i} at ({xs[i]}, {ys[i]})");
}
Demo
Invader 0 at (40, 70)
Invader 1 at (150, 50)
Invader 2 at (260, 100)

Invader 1 is xs[1] and ys[1] together. These are Activity 1.25's parallel arrays, holding positions instead of names and ages.

The Drawing Follows the Data

In Task 1, the same loop draws invaders instead of printing them. It runs xs.Length times, so it draws one invader per number in the array.

Predict: what happens if you add one more number to the end of xs and one more to the end of ys, and change nothing else?

The Drawing Follows the Data

Eight green invaders scattered unevenly across a black window, with Invaders: 8 in the corner

Eight numbers each

The same eight invaders plus a ninth near the middle, with Invaders: 9 in the corner

Nine numbers each

A ninth invader, and the counter says 9. Not one line of the loop changed. In Lab 5, a different picture needed a different formula; here it needs different data.

Two Arrays Have to Agree

xs[2] and ys[2] belong to the same invader only because they share an index. Nothing in C# connects the two arrays — you keep them in step yourself.

Predict: xs gets a fourth number, but ys still has three. The loop runs xs.Length times. What happens on the fourth pass?

Two Arrays Have to Agree

Demo
int[] xs = { 40, 150, 260, 370 };
int[] ys = { 70, 50, 100 };
for (int i = 0; i < xs.Length; i++)
{
Console.WriteLine($"Invader {i} at ({xs[i]}, {ys[i]})");
}
Demo
Invader 0 at (40, 70)
Invader 1 at (150, 50)
Invader 2 at (260, 100)
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Program.<Main>$(String[] args) in Program.cs:line 6

Three invaders print, then it crashes on line 6: on the fourth pass xs[3] exists and ys[3] does not. Activity 1.24's exception, from two arrays that stopped agreeing.

The Other Mismatch Makes No Noise

Now turn it around: ys has the extra number and xs has three. Predict again before the output appears.

Demo
int[] xs = { 40, 150, 260 };
int[] ys = { 70, 50, 100, 140 };
for (int i = 0; i < xs.Length; i++)
{
Console.WriteLine($"Invader {i} at ({xs[i]}, {ys[i]})");
}
Demo
Invader 0 at (40, 70)
Invader 1 at (150, 50)
Invader 2 at (260, 100)

No crash, no warning, and no fourth invader. The loop counts with xs.Length, so it never asks for ys[3], and the 140 is never read.

A Loop Trusts the Array Its Test Names

Both demos ran the same loop. The only difference was which array had the extra number.

If the other array is shorter, the program crashes — loudly, on the line that reached past its end, which at least tells you where to look.

If the other array is longer, the extra data is quietly ignored. Nothing crashes and nothing warns you; an invader you meant to add simply never appears.

That is why both arrays get their new number in the same edit, every time. Task 1 has you break the agreement on purpose.

One bool Per Invader

A single bool from Activity 1.11 can remember one yes-or-no answer. An array of bool remembers one per invader: hit[3] answers “has invader 3 been hit?”

Activity 1.25 showed that new int[4] starts as four zeros. Predict what new bool[4] starts as.

One bool Per Invader

Demo
bool[] hit = new bool[4];
for (int i = 0; i < hit.Length; i++)
{
Console.Write($"{hit[i]} ");
}
Demo
False False False False

Every element of a new bool array starts as false, which C# prints as False. At the start of the game no invader has been hit, so this is exactly the starting value you want, and you do not have to set any of it.

Mark One, and It Stays Marked

Writing to one element changes that element and nothing else — the way Activity 1.23 changed one cup. Predict the output.

Demo
bool[] hit = new bool[4];
hit[2] = true;
for (int i = 0; i < hit.Length; i++)
{
Console.Write($"{hit[i]} ");
}
Demo
False False True False

Only index 2 changed. In the game, a shot that lands on invader i runs hit[i] = true;, and that invader stays marked for the rest of the game.

Where It Is Declared Decides Whether It Remembers

Activity 1.22's Task 4 moved int drawn = 0; above the game loop, and the counter never reset. The same rule works in the other direction here.

Anything declared inside the game loop is created fresh on every frame. A hit array made there would be all false again sixty times a second, and every invader would come straight back — Lab 5's problem exactly.

So hit is declared once, above the game loop, next to the arrays it belongs with. Task 5 has you move it inside on purpose and watch.

Skip the Ones That Are Gone

The loop still visits every index, every frame. What changes is that it only draws an invader whose hit is still false. That is !hit[i], read as “not hit.”

for (int i = 0; i < xs.Length; i++)
{
int x = formationX + xs[i];
int y = ys[i];
if (!hit[i])
{
Raylib.DrawRectangle(x, y, invaderWidth, invaderHeight, Color.Green);
}
}

Skip the Ones That Are Gone

Four invaders left after four were shot, with a shot on its way to a fifth

Four were hit, so four are skipped. Their positions are still in xs and ys; the loop just does not draw them.

Nothing was removed from any array. In C# an array's length is fixed the moment it is made, so “gone” has to be recorded rather than deleted.

Count What Is Left

The game is over when no invader is left, and xs.Length cannot tell you that — it is still 8 after every invader is gone.

Count the false elements instead, with Activity 1.20's counter pattern: start at 0 above the loop, and add 1 for every invader that is not hit.

On the next slide, five invaders and three of them hit. Predict the count before the output appears.

Count What Is Left

Demo
bool[] hit = { false, true, false, true, true };
int left = 0;
for (int i = 0; i < hit.Length; i++)
{
if (!hit[i])
{
left = left + 1;
}
}
Console.WriteLine($"Left: {left}");
Demo
Left: 2

Two are false, so two are left. In the game this count restarts at 0 every frame, because it counts what is left now.

Every Invader Is Still Three Lines You Cannot Reuse

The invader's body and two eyes are three DrawRectangle calls, written once, inside the loop. That is fine while the loop is the only place an invader appears.

Draw one anywhere else — a title screen, a row of lives along the bottom — and you copy all three lines, then keep every copy in step whenever the invader changes. That is the same agreement problem as parallel arrays, only with code instead of data.

Quarter 2 starts by giving a block of code a name of its own, so it is written once and used anywhere.

Today's Objectives

  • Drawing one shape per element, with positions read from arrays
  • Keeping parallel arrays the same length, and recognizing what happens when they are not
  • Using a bool array to remember something about each element
  • Counting the elements that match a condition, every frame

Key Terms

Data-Driven Drawing
A picture whose shapes come from values stored in arrays, so changing the data changes the picture without changing the code.
Flag
A bool that records whether something has happened, like whether an invader has been hit.
Game State
The values a game keeps from one frame to the next, declared above the game loop so they are not created fresh every frame.

'F' → Fullscreen

divider

Build

Everything today goes in a new program named 1-26-invaders. Nothing carries over from Lab 5, although a lot of it will look familiar.

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 5. Close the window to end the program. Escape works too.


Task 1: Positions From Data

  • Write the code below and run it. You should get eight invaders scattered across the top half of the window, matching the picture, and a counter reading 8.
  • Add a ninth invader. Put , 330 at the end of xs and , 140 at the end of ys, then run it. Write down what changed, and which lines you did not have to touch.
  • Now take the , 140 back out of ys only, but predict first: will the program draw eight invaders, nine, or something else? Write your prediction down, run it, and record the exception and the line number it names.
  • Take the , 330 out of xs too, so both arrays are back to eight numbers.
Eight green invaders scattered unevenly across the top half of a black window, with Invaders: 8 in the corner

Eight invaders, from data

1-26-invaders
#:package Raylib-cs@8.0.0
using Raylib_cs;
int screenWidth = 640;
int screenHeight = 480;
int[] xs = { 40, 150, 260, 370, 440, 160, 270, 400 };
int[] ys = { 70, 50, 100, 60, 130, 170, 200, 210 };
int invaderWidth = 40;
int invaderHeight = 24;
Raylib.InitWindow(screenWidth, screenHeight, "Invaders");
Raylib.SetTargetFPS(60);
while (!Raylib.WindowShouldClose())
{
Raylib.BeginDrawing();
Raylib.ClearBackground(Color.Black);
for (int i = 0; i < xs.Length; i++)
{
int x = xs[i];
int y = ys[i];
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.DrawText($"Invaders: {xs.Length}", 10, 10, 20, Color.White);
Raylib.EndDrawing();
}
Raylib.CloseWindow();

Task 2: One Reference Point, Again

  • Add formationX, speedX, and sway, and the movement block at the top of the game loop. Then add formationX to every x.
  • This is Lab 5's reference point, with one difference: the offsets now come from an array instead of from col * spacingX. The formation sways from formationX 0 to formationX 160 and back.
  • Before you run it, work out how far right the invader at x 440 reaches at the far end of the sway: its x in the array, plus the largest formationX, plus invaderWidth. Then run it and watch that invader at the right wall.
  • Change the 440 in xs to 500 and run it. Describe what happens at the right side of the window, and say which number did not know about your change. Then put it back to 440.
1-26-invaders
#:package Raylib-cs@8.0.0
using Raylib_cs;
int screenWidth = 640;
int screenHeight = 480;
int[] xs = { 40, 150, 260, 370, 440, 160, 270, 400 };
int[] ys = { 70, 50, 100, 60, 130, 170, 200, 210 };
int invaderWidth = 40;
int invaderHeight = 24;
int formationX = 0;
int speedX = 1;
int sway = 160;
Raylib.InitWindow(screenWidth, screenHeight, "Invaders");
Raylib.SetTargetFPS(60);
while (!Raylib.WindowShouldClose())
{
formationX = formationX + speedX;
if (formationX >= sway || formationX <= 0)
{
speedX = 0 - speedX;
}
Raylib.BeginDrawing();
Raylib.ClearBackground(Color.Black);
for (int i = 0; i < xs.Length; i++)
{
int x = formationX + xs[i];
int y = ys[i];
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.DrawText($"Invaders: {xs.Length}", 10, 10, 20, Color.White);
Raylib.EndDrawing();
}
Raylib.CloseWindow();

Task 3: Fire Back, Again

  • Add the cannon, the shot, and the shot counter. This is Lab 5's optional challenge, given in full, so if you built it in Activity 1.22 most of it will look familiar.
  • The arrow keys move the cannon and Space fires. A new shot can only be fired once the last one has landed or left the top of the window, because of !shotFlying.
  • The hit check is inside the loop, because that is the only place x and y exist. Right now, all it does is stop the shot.
  • Play for thirty seconds. Write down your shot count and the invader count when you stop. You are about to fix exactly what you see.
1-26-invaders
#:package Raylib-cs@8.0.0
using Raylib_cs;
int screenWidth = 640;
int screenHeight = 480;
int[] xs = { 40, 150, 260, 370, 440, 160, 270, 400 };
int[] ys = { 70, 50, 100, 60, 130, 170, 200, 210 };
int invaderWidth = 40;
int invaderHeight = 24;
int formationX = 0;
int speedX = 1;
int sway = 160;
int groundY = 450;
int cannonWidth = 50;
int cannonHeight = 20;
int cannonX = 295;
int cannonY = groundY - cannonHeight;
int shotX = 0;
int shotY = 0;
bool shotFlying = false;
int shots = 0;
Raylib.InitWindow(screenWidth, screenHeight, "Invaders");
Raylib.SetTargetFPS(60);
while (!Raylib.WindowShouldClose())
{
formationX = formationX + speedX;
if (formationX >= sway || formationX <= 0)
{
speedX = 0 - speedX;
}
if (Raylib.IsKeyDown(KeyboardKey.Left))
{
cannonX = cannonX - 5;
}
if (Raylib.IsKeyDown(KeyboardKey.Right))
{
cannonX = cannonX + 5;
}
if (Raylib.IsKeyPressed(KeyboardKey.Space) && !shotFlying)
{
shotFlying = true;
shotX = cannonX + cannonWidth / 2;
shotY = cannonY;
shots = shots + 1;
}
if (shotFlying)
{
shotY = shotY - 8;
if (shotY < 0)
{
shotFlying = false;
}
}
Raylib.BeginDrawing();
Raylib.ClearBackground(Color.Black);
for (int i = 0; i < xs.Length; i++)
{
int x = formationX + xs[i];
int y = ys[i];
if (shotFlying && shotX >= x && shotX <= x + invaderWidth && shotY >= y && shotY <= y + invaderHeight)
{
shotFlying = false;
}
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.DrawRectangle(0, groundY, screenWidth, 4, Color.Gray);
Raylib.DrawRectangle(cannonX, cannonY, cannonWidth, cannonHeight, Color.SkyBlue);
if (shotFlying)
{
Raylib.DrawRectangle(shotX - 2, shotY, 4, 12, Color.Yellow);
}
Raylib.DrawText($"Invaders: {xs.Length}", 10, 10, 20, Color.White);
Raylib.DrawText($"Shots: {shots}", 520, 10, 20, Color.White);
Raylib.EndDrawing();
}
Raylib.CloseWindow();
All eight invaders still on screen with a shot in flight; the corners read Invaders: 8 and Shots: 11

Eleven shots, eight invaders


Task 4: Make It Stick

  • Add bool[] hit = new bool[xs.Length]; right under the two position arrays. It is made from xs.Length, so it always has one flag per invader.
  • The hit check gains two things: !hit[i] && at the front, so a dead invader cannot be hit again, and hit[i] = true; inside, so a hit is remembered.
  • Wrap the three drawing lines in if (!hit[i]), and count each invader you draw. The three DrawRectangle lines move one level in, so they are marked — you are re-indenting them, not retyping them.
  • The counter now shows left instead of xs.Length, and CLEARED appears when it reaches 0.
  • Before you run it, say what every element of hit holds when the game starts. Then play until you clear the screen, and write down your shot count. Eight is perfect.
1-26-invaders
#:package Raylib-cs@8.0.0
using Raylib_cs;
int screenWidth = 640;
int screenHeight = 480;
int[] xs = { 40, 150, 260, 370, 440, 160, 270, 400 };
int[] ys = { 70, 50, 100, 60, 130, 170, 200, 210 };
bool[] hit = new bool[xs.Length];
int invaderWidth = 40;
int invaderHeight = 24;
int formationX = 0;
int speedX = 1;
int sway = 160;
int groundY = 450;
int cannonWidth = 50;
int cannonHeight = 20;
int cannonX = 295;
int cannonY = groundY - cannonHeight;
int shotX = 0;
int shotY = 0;
bool shotFlying = false;
int shots = 0;
Raylib.InitWindow(screenWidth, screenHeight, "Invaders");
Raylib.SetTargetFPS(60);
while (!Raylib.WindowShouldClose())
{
formationX = formationX + speedX;
if (formationX >= sway || formationX <= 0)
{
speedX = 0 - speedX;
}
if (Raylib.IsKeyDown(KeyboardKey.Left))
{
cannonX = cannonX - 5;
}
if (Raylib.IsKeyDown(KeyboardKey.Right))
{
cannonX = cannonX + 5;
}
if (Raylib.IsKeyPressed(KeyboardKey.Space) && !shotFlying)
{
shotFlying = true;
shotX = cannonX + cannonWidth / 2;
shotY = cannonY;
shots = shots + 1;
}
if (shotFlying)
{
shotY = shotY - 8;
if (shotY < 0)
{
shotFlying = false;
}
}
Raylib.BeginDrawing();
Raylib.ClearBackground(Color.Black);
int left = 0;
for (int i = 0; i < xs.Length; i++)
{
int x = formationX + xs[i];
int y = ys[i];
if (!hit[i] && shotFlying && shotX >= x && shotX <= x + invaderWidth && shotY >= y && shotY <= y + invaderHeight)
{
hit[i] = true;
shotFlying = false;
}
if (!hit[i])
{
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);
left = left + 1;
}
}
Raylib.DrawRectangle(0, groundY, screenWidth, 4, Color.Gray);
Raylib.DrawRectangle(cannonX, cannonY, cannonWidth, cannonHeight, Color.SkyBlue);
if (shotFlying)
{
Raylib.DrawRectangle(shotX - 2, shotY, 4, 12, Color.Yellow);
}
Raylib.DrawText($"Invaders: {left}", 10, 10, 20, Color.White);
Raylib.DrawText($"Shots: {shots}", 520, 10, 20, Color.White);
if (left == 0)
{
Raylib.DrawText("CLEARED", 226, 220, 40, Color.Green);
}
Raylib.EndDrawing();
}
Raylib.CloseWindow();
An empty black window with CLEARED in green across the middle; the corners read Invaders: 0 and Shots: 8

Cleared in eight shots


Task 5: Break It on Purpose

Three changes, one at a time. Write down exactly what you see each time, and put each one back before the next.

  1. Move bool[] hit = new bool[xs.Length]; from line 10 to inside the game loop, just above int left = 0;. Play, and watch an invader you hit, and the counter.
  2. Put it back. Now change hit[i] = true; on line 82 to hit[0] = true;. Shoot three or four invaders that are not the one at the far left. Record which ones disappear, and what the counter does.
  3. Put it back. Now delete !hit[i] && from the start of the hit check on line 80. Shoot the invader that sits just below another one — it is 160 in xs and 170 in ys, under the one at 150 and 50 — and then try to shoot the one above it. Record what happens to your shots.

All three compile, none of them warns you, and none of them crashes. For each one, say what the hit array held that it should not have, or did not hold that it should.

There is no code block for this task. When it is over, your program is exactly what it was at the end of Task 4.


Challenge (Optional): Let the Data Set the Sway

  • Task 2 showed that sway is a typed-in 160 that knows nothing about the positions in xs. Move one invader further right and the formation walks it off the screen.
  • Work it out from the data instead. Before sway is declared, find the index of the largest number in xs with Activity 1.25's best-arrow pattern.
  • Then set sway to screenWidth - invaderWidth - xs[widest], where widest is that index. With the page's positions it should still come out as 160.
  • Test it the way Task 2 broke it: change 440 to 500. The rightmost invader should now reach the right wall exactly and turn around, with no other edit.
divider

Checkpoint

Your Task 5 change 2 should look like this after a while.

Seven invaders still on screen, a shot stopping at one of them, and the corners reading Invaders: 7 and Shots: 23

Task 5, change 2 — twenty-three shots in

The counter went to 7 and never moved again. Every hit marked index 0, so the invader at the far left vanished on the first one and every invader you actually aimed at stayed. The shots really were landing; the program was writing them down against the wrong invader.

  • Eight invaders drawn from xs and ys, and you can point to the two numbers that place any one of them
  • Your Task 1 prediction is written next to the real result, with the exception and its line number
  • Your Task 2 working for the right edge is written down, with what happened at 500
  • An invader you hit stays gone, the counter goes down, and CLEARED appears at 0
  • All three Task 5 results are recorded, with what hit held in each
divider

Reflection

Answer the following questions before submitting your work.

  1. Lab 5 worked out every x from a formula; this lab read every x from an array. Explain what the array let you draw that the formula could not, and why adding a ninth invader took no change to the loop.
  2. In Task 5's first change, an invader you hit came back on the very next frame, the same thing that happened in Lab 5. Explain why where hit is declared decides whether the game remembers a hit.
  3. In Task 5's third change, some shots stopped in empty space. Explain what they were hitting, and why !hit[i] has to be in the hit check as well as around the drawing.
divider

Submit

Submit four things to the dropbox:

  1. Your 1-26-invaders program file, with eight invaders and xs back to its starting numbers.
  2. Your Task 1 prediction and crash record, your Task 2 right-edge working and what happened at 500, your Task 3 numbers, and the shot count you cleared the screen in.
  3. All three Task 5 results, with what hit held in each.
  4. Your three reflection answers.

Activity Complete