1. Reference Guide

What are Arrays?

An array is a collection of elements (values) stored in a single variable. Each element in an array can be accessed by its index (position), starting from 0.

Think of an array like a row of boxes, each containing a value:

  • Box 0 contains the first element
  • Box 1 contains the second element
  • Box 2 contains the third element
  • And so on…

Why Use Arrays?

  • Store multiple values in one variable
  • Easy to access values by position
  • Useful for loops (process many items at once)
  • Organize related data together

Modifying Arrays

This is reference about how to create and modify arrays. Run it to do stuff. You can change, add, or remove elements from an array:

Code Runner Challenge

modifying arrays by changing, adding, and removing elements

View IPYNB Source
%%js

// CODE_RUNNER: modifying arrays by changing, adding, and removing elements

// Start with an array
let colors = ["red", "blue", "green"];
console.log(colors);
console.log();

// Change an element
colors[1] = "yellow";
console.log(colors);
console.log();

// Add an element
colors.push("purple");
console.log(colors);
console.log();

// Remove an element
colors.splice(colors.indexOf("red"), 1);
console.log(colors);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Looping Through Arrays

This is reference for how to looping through arrays to process each element. Arrays are powerful when combined with loops. You can process each element without writing it by hand. You can use loops to update multiple things in an array

Code Runner Challenge

Looping Through Arrays

View IPYNB Source
%%js
// CODE_RUNNER: Looping Through Arrays

// Array of enemy positions in a level
let enemyPositions = [150, 300, 450, 600];

// Example 1: Move every enemy forward by 10 pixels
console.log("Updating enemy positions:");
for (let pos of enemyPositions) {
    let newPos = pos + 10;
    console.log("Enemy moved to position: " + newPos);
}


// Example 2: Count how many enemies exist
console.log("Total active enemies: " + enemyPositions.length);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

2. LxD Cycle Process

Empathize:
Students who are new to arrays might understand regular variables but not understand why they would need an array. They might also mix up the index and the value in an array, forget that arrays start at index 0, or have trouble changing, adding, and removing values. Since arrays are used a lot in games, students need a simple way to understand how arrays can store and manage multiple related values.

Define:

  • POV: Introductory CSSE students need to understand how arrays can store multiple related values in one variable because arrays make it easier to organize and work with groups of data.

  • Learning Goal: Students will be able to create arrays in JavaScript, access values using indexes, change values, add and remove values, and use simple loops to go through an array.

Ideate:

  • HMW Question: How might we help students understand when they should use an array instead of making a bunch of separate variables?

  • HMW Question: How might we make it easier for students to remember that array indexes start at 0?

  • Activity: Students will make simple arrays using game development ideas. They will then practice accessing values, changing them, adding values with push(), removing values, and using a for...of loop. After that, they will use arrays in complex game code examples using game runner. For homework they will modify arrays in games for enemy positions, player inventories, and health.

Prototype:

  • A reference section explaining what arrays are, how indexes work, and common array commands.
  • Simple JavaScript examples that students can run and change.
  • Examples using familiar information before moving into game-related examples.
  • Game challenges where students use arrays to store and manage different objects.
  • Practice hacks that start with basic arrays and gradually become more difficult.
  • A short-response question where students explain why an array would be useful.
  • A grading rubric that checks if students can create, modify, add/remove, and loop through arrays.

Test:

  • Have other students try the activities without giving them extra instructions.
  • See if students understand that the first item in an array is at index 0.
  • Check if students can tell the difference between an index and the value at that index.
  • See if students can access, change, add, and remove values on their own.
  • Check if students can use a loop instead of writing the same code multiple times.
  • Look at the results from the coding challenges and short-response question.
  • Record which parts of the lesson students found confusing.
  • Use the feedback to change the examples, instructions, or activities that were not clear.
  • After teaching the lesson, make another round of changes based on what worked and what did not.

3. Course Requirements

This lesson covers introductory array concepts from MiraCosta College CS 111. The lesson teaches students how arrays can be used to store and work with multiple related values in JavaScript.

The CS 111 concepts covered in this lesson include:

  • Creating and using arrays: Students create arrays to store multiple related values, such as colors, enemy positions, player inventories, and health values.
  • Accessing array elements: Students learn that arrays use indexes to access individual elements and that the first element is at index 0.
  • Modifying arrays: Students practice changing an existing value in an array using its index.
  • Adding elements: Students use push() to add new values to an existing array.
  • Removing elements: Students practice removing values from an array.
  • Looping through arrays: Students use for...of loops to go through each element in an array and perform an action on each value.
  • Using arrays in programs: Students apply arrays to game-related situations, such as managing enemies, player inventories, health values, and game objects.
  • Recognizing when arrays are useful: Students explain why an array is better than using separate variables when a program needs to store and manage multiple related values.

These requirements are taught through the reference examples, Tech Talk, class challenges, Popcorn Hack, and the three array coding exercises. The final short-response exercise also checks whether students understand why an array should be used in a given situation, rather than only being able to write the syntax.

The lesson is intended to introduce these CS 111 concepts before students move on to more advanced array operations and data structures.

4. Lesson Plan

Learning Objective: Understand how arrays are immensely useful in developing games, and leanr how to modify, access, and loop through arrays.

Success Criteria: You can understand when an array is the best data type to use when faced with a coding challenge/situation, and can correctly write code to use arrays in a game/other scenario.

Tech Talk: Arrays in Games

The most important use of arrays in code is to hold objects (sprites) for the game engine to render, so you don’t have to repeat rendering every single opject, you only have to render once at the end.

Brainstorm

Come up with some other ideas of where arrays are used in games.

Take a few minutes.

Other Uses

Game Boards and Maps

  • Two-dimensional arrays are perfect for representing grid-based games like chess, tic-tac-toe, or tile-based maps in platformers. Each cell in the array can store information about what is currently at that position, such as a wall, a floor, or a game piece.

Entity Management

  • Arrays are used to keep track of multiple game objects at once, such as a group of enemies, active projectiles, or items scattered across a level. This allows the game to loop through the array and update the state of every object simultaneously.

Player Inventories

  • An array can act as a player’s backpack, storing a list of collected items, weapons, or resources. Methods like push() and pop() make it easy to add new items or remove them when used.

State Tracking

  • Arrays can separate the underlying logic of a game from what is drawn on the screen. For example, an array can track whether a pellet has been eaten in a Pac-Man game, ensuring the score remains accurate even the user can’t see the visual pellet.

5. Code Examples and Class Challenges

Accessing Arrays

Think of an array like a row of boxes, each containing a value:

  • Box 0 contains the first element
  • Box 1 contains the second element
  • Box 2 contains the third element
  • And so on…

Now look through the code example to learn how to modify an array.

Note: Keep in mind you need the 1 when you delete an object

Code Runner Challenge

modifying arrays by changing, adding, and removing player items in inventory

View IPYNB Source
%%js

// CODE_RUNNER: modifying arrays by changing, adding, and removing player items in inventory

// Start with an array of items in the player's inventory
// To define an array use the templete below. An array can store anything, and can store both words and numbers at the same time. You can name the array whatever you want.
let playerInventory = ["Sword", "Shield", 5, "Potion"];
console.log(playerInventory);

// Accessing an element using its index (0 is the first item)
let firstItem = playerInventory[0]; 
console.log("First item:", firstItem);

// You can also change an element in an array using its index
playerInventory[1] = "Armor";
console.log(playerInventory);

// Next, to add something to an array use the .push() function.
// Add an element to the end 
playerInventory.push("Magic Scroll");
console.log(playerInventory);

// Remove an element by finding its index first
// the 1 should always be there!!!
// it means you are removing 1 object at the index!
playerInventory.splice(playerInventory.indexOf("Sword"), 1); 
console.log(playerInventory);

// or if you know the index, you can remove an element directly
// this removes the first element
playerInventory.splice(0, 1); 

console.log(playerInventory);

Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Looping Through Arrays

Arrays are useful since they store multiple objects. They are also useful to reuse code on the objects in the arrays. For example, in a game where you need to update the healths of multiple enemies, you can just loop through the array of enemy healths and reuse the same code to modify the objects.

In this example, we want to move all the enemies forward 10 spaces. We could write the whole thing out,

Code Runner Challenge

Without Looping

View IPYNB Source
%%js
// CODE_RUNNER: Without Looping

// Array of enemy positions in a level
let enemyPositions = [150, 300, 450, 600];
enemyPositions[0] = enemyPositions[0] + 10;
enemyPositions[1] = enemyPositions[1] + 10;
enemyPositions[2] = enemyPositions[2] + 10;
enemyPositions[3] = enemyPositions[3] + 10;

console.log("Enemy moved to position: " + enemyPositions[0]);
console.log("Enemy moved to position: " + enemyPositions[1]);
console.log("Enemy moved to position: " + enemyPositions[2]);
console.log("Enemy moved to position: " + enemyPositions[3]);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

or you can just use a for...of loop.

To use a for of loop, use this template.

You can name Object anything. You write the array you are using instead of Array.

Put the code you want to repeat inside the curly braces {}.

for (let Object in Array) {}

Code Runner Challenge

Looping Through Arrays

View IPYNB Source
%%js
// CODE_RUNNER: Looping Through Arrays

// Array of enemy positions in a level
let enemyPositions = [150, 300, 450, 600];
for (let pos of enemyPositions) {
    let newPos = pos + 10;
    console.log("Enemy moved to position: " + newPos);
}
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

You can also use a regular for loop. i is a counter for the index of the array you are using. If you don’t know the number of objects in the array, using Array.length, where Array is the array you are using. This can actually modify the elements of the array in place since it keeps the index, unlike a for of loop. for (let i = 0; i < NumberOfObjectsInArray; i++)

Code Runner Challenge

Looping Through Arrays Using regular for loop

View IPYNB Source
%%js
// CODE_RUNNER: Looping Through Arrays Using regular for loop

// Array of enemy positions in a level
let enemyPositions = [150, 300, 450, 600];

for (let i = 0; i < enemyPositions.length; i++) {
    console.log("Enemy number: " + i + " of " + enemyPositions.length);
    enemyPositions[i] = enemyPositions[i] + 10;
    console.log("Enemy moved to position: " + enemyPositions[i]);
}

// This can actually modify the elements of the array in place since it keeps the index, unlike a for of loop.
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Class Challenge 1

The people who wrote the code below don’t know how to use arrays to render the objects :(. With your immense coding skills, we’re going fix the game below to have all characters rendered.

Fix the game below to have all characters and the background object rendered. There are 5 in total. Scroll to the end for the code to change.

Challenge

Class Challenge #1

Lines: 1 Characters: 0
Game Status: Not Started

Key Takeaways

  • You need to use arrays to write code for your games.
  • You need to learn how to use arrays.
  • Arrays are important and stuff.

✅ Arrays store multiple values in a single variable
✅ Index starts at 0 for the first element
✅ Access elements using array[index]
✅ Use loops to process all elements
✅ Common operations: append, remove, change, loop, sum, average

6. Arrays Hacks

Welcome to the Arrays homework! These exercises will help you practice the key array concepts from the lesson: accessing elements, modifying arrays, looping through arrays, and performing calculations.

Complete all exercises below. Good luck! 💪

Popcorn Hack #1

Use the code below to find some arrays.

EXAMPLE ARRAY for rendering objects

this.classes = [ { class: GameEnvBackground, data: bgData }, { class: Player, data: playerData } ];

Challenge: Find ALL of the arrays in the game code, and add a comment. This should take around a minute, and two at most.

Challenge

Popcorn Hack

Lines: 1 Characters: 0
Game Status: Not Started

Popcorn Hack #2

We are now going to practice modifying arrays.

In this game, we are trying to update the player’s item in their inventory to lose some durability.

  1. Create a for loop that goes through the array.
  2. Reduce the durability of each item by ten
  3. Print the durability using console.log(what you want to print goes here)

Look back at the looping section for referencing loops

Code Runner Challenge

Popcorn Hack 2

View IPYNB Source
%%js
// CODE_RUNNER: Popcorn Hack 2 

let itemDurabilities = [40, 30, 50];

// TODO:
// 1. Create a for loop that goes through the array.
///2. Reduce the durability of each item by ten
// 3. Print the durability using console.log()

Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Hack 1: Array Basics - Use Arrays in a Game

  1. Create a loop that goes through enemySpeeds ([4, 3, 5]).
  2. Multiply each speed by 2 to activate “rage mode”.
  3. Print the new speed for each enemy using console.log().

Code Runner Challenge

Exercise 1 - Enemy Speeds

View IPYNB Source
%%js
// CODE_RUNNER: Exercise 1 - Enemy Speeds

let enemySpeeds = [4, 3, 5];

// TODO:
// 1. Create a loop that goes through enemySpeeds.
// 2. Multiply each speed by 2 to activate "rage mode".
// 3. Print the new speed for each enemy using console.log().
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Hack 2: Player Inventory

The player originally has a sword, a shield, a health potion, and a key

  1. Add “Magic Ring” to the player’s inventory.
  2. Change “Health Potion” to “Empty Bottle” (simulating using the item).
  3. Go through the player’s inventory using and print each item.

Code Runner Challenge

Exercise 2 - Modify Arrays

View IPYNB Source
%%js
// CODE_RUNNER: Exercise 2 - Modify Arrays

// intial inventory --> Sword, Shield, Health Potion, Key


// TODO:
// 1. Add "Magic Ring" to the player's inventory.
// 2. Change "Health Potion" to "Empty Bottle" (simulating using the item).
// 3. Go through the player's inventory using and print each item.

Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Hack 3: Player Healths

We want to update the health values of players in a game

  1. Go through the health of the players in a game (intial player healths –> 20, 50, 80, 45)
  2. Add 25 bonus health to each player.
  3. Print the new health value for each player.

Code Runner Challenge

Exercise 3 - Looping and Modifying

View IPYNB Source
%%js
// CODE_RUNNER: Exercise 3 - Looping and Modifying

// intial player health --> 20, 50, 80, 45

// TODO:
// 1. Go through each of the players's healths
// 2. Add 25 bonus points to each player's health
// 3. Print each updated health score using console.log()

Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Hack 4: Short Response

Explain why arrays are useful. Use two specific examples of how they help make code shorter/easier to write (hint: try explaining why you likely chose to use an array in exercises 2 and 3).

Homework Grading

100 percent for a perfect submission. Broken down in table. Scaled to 1 point.

Exercise # Able to create an array Able to modify an array in place Able to add/delete elements Able to loop through an array
Popcorn 1 5 for identifying all arrays      
Popcorn 2 n/a 5 n/a 10
1 n/a 5 n/a 10
2 5 5 5 10
3 5 5 n/a 10
4 20 for identifying the need for an array in two example situations      

7. Lesson Revision

  • Revision Made:

8. Feedback Evidence

Feedback Recieved:

9. References

Submit Assignment

Your code will be saved as a Gist and reviewed automatically. You must be logged in to submit.

Need to update a submission later? Open the submissions dashboard.