🔢

Data Types

This page covers numbers, strings, booleans, arrays, and objects from my game code.

Learning Objective Project Evidence Required Assessment Method
Numbers Section 1 explains numbers for health, score, speed, cooldowns, positions, and coin values. Code review of numeric properties.
Strings Section 2 explains strings for game mode, player names, sprite paths, and HUD messages. Review string usage and template literals.
Booleans Section 3 explains boolean flags such as battleEnded, attackRequested, and isDefeated. Review boolean logic.
Arrays Section 4 explains arrays that store lasers, coins, classes, power-ups, and leaderboard entries. Review array operations.
Objects / JSON Section 5 explains objects / JSON for configuration objects, sprite data, spawn points, and stored score data. Review object literals and JSON-style data.
🧩

Specific Code Definitions


This section makes the blog stronger because it does not only say that the game uses arrays, numbers, booleans, and objects. It explains the exact variables that are defined in my code, what each one stores, and why each one matters during gameplay.

Important Variables Defined in the Battle Level

Most of the important game state is defined inside the constructor of PeppaBattleLevelBase. These definitions are important because the constructor runs once when the level starts, so it sets the starting rules for health, lasers, coins, multiplayer mode, cooldowns, score, and the leaderboard.

this.gameMode = config.gameMode ?? localStorage.getItem('peppaGameMode') ?? 'singlePlayer';

this.playerMaxHealth = config.playerHealth ?? 5;
this.playerHealth = this.playerMaxHealth;
this.player2MaxHealth = config.playerHealth ?? 5;
this.player2Health = this.player2MaxHealth;

this.attackCooldownMs = config.attackCooldownMs ?? 450;
this.lastAttackAt = 0;
this.lastPlayer2AttackAt = 0;
this.enemyLaserIntervalMs = config.enemyLaserIntervalMs ?? 1100;

this.lasers = [];
this.coins = [];
this.coinCount = 0;
this.coinValue = config.coinValue ?? 25;
this.leaderboard = [];
this.battleEnded = false;
Definition Type What It Controls Why It Matters
this.gameMode String Stores whether the game is in singlePlayer or twoPlayer mode. This controls whether the level creates only Player 1 and the boss, or creates both Player 1 and Player 2 for multiplayer.
this.playerHealth and this.player2Health Number Stores the current HP for Player 1 and Player 2. These values decide when a player loses. When health reaches 0, the lose screen or multiplayer winner message is triggered.
this.attackCooldownMs Number Stores the required delay between laser attacks. This prevents the player from holding the attack key and firing unlimited lasers every frame.
this.lastAttackAt and this.lastPlayer2AttackAt Number Stores the timestamp of the last attack for each player. The code compares Date.now() to these timestamps to decide whether the cooldown has passed.
this.enemyLaserIntervalMs Number Controls how often the boss fires a laser. Lower values make the boss attack faster, which makes the level harder without changing the rest of the code.
this.lasers Array Stores every active laser projectile currently moving across the screen. Each laser is pushed into this array when fired, updated every frame, and removed when it expires or hits something.
this.coins Array Stores every coin object placed in the level. The game loops through this array to draw coins and check whether the player collected one.
this.coinCount and this.coinValue Number Tracks how many coins were collected and how much each coin is worth. These values are used in the final score calculation: health points plus coin bonus.
this.leaderboard Array Stores score entries loaded from an API or from localStorage. This lets the HUD display top scores without hard-coding them into the page.
this.battleEnded Boolean Stores whether the current fight is already over. This stops the update loop from continuing after a win or loss, preventing extra lasers, damage, or repeated transitions.

How this.lasers Actually Works

The this.lasers array is one of the most important definitions in the project. It starts empty, but every time a player or boss fires, a new laser object is added with its position, velocity, owner, and lifetime.

this.lasers.push({
  x: fromX,
  y: fromY,
  vx: (dx / len) * this.laserSpeed,
  vy: (dy / len) * this.laserSpeed,
  isPlayerLaser,
  source: sourceId,
  life: 60,
  maxLife: 60
});

Each laser object stores everything the game needs to move and draw the laser. x and y are the current position. vx and vy are the movement speed in the x and y directions. source tells the game who fired it, such as player1, player2, or boss. life counts down every frame so old lasers disappear instead of staying forever.

Specific Variables in the Boss Enemy Class

The PeppaBossEnemy constructor defines boss-specific state. These variables make the boss different from a normal engine enemy because the boss can chase the player, take damage, and become defeated.

this.health = data?.health ?? 3;
this.maxHealth = this.health;
this.moveSpeed = data?.moveSpeed ?? 0.8;
this.isDefeated = false;
Boss Variable What It Does
this.health Stores how many hits the boss can still take before losing.
this.maxHealth Stores the original health value so the HUD can show health as current HP out of max HP.
this.moveSpeed Controls how many pixels the boss moves toward the player each frame.
this.isDefeated Acts as a boolean state flag. When it becomes true, the boss stops moving and the level can transition to the next stage.

Specific Variables in the Power-Up Menu

The power-up menu also has important definitions. This class does not control lasers directly, but it controls the player's choice before the next battle.

this.selectedOption = 0;
this.options = [
  { name: 'Extra Speed', description: 'Move faster in battle' },
  { name: 'Extra Health', description: 'Start with more health' },
  { name: 'Extra Damage', description: 'Deal more damage per laser' }
];
this.chosenPower = null;

this.selectedOption stores which menu option is currently highlighted. this.options is an array of objects, where each object has a name and description. this.chosenPower starts as null because the player has not picked anything yet. After pressing Enter, the selected power-up is stored in this.gameEnv.gameControl.chosenPower so the game can remember the choice across levels.


Specific Data Type Requirements


1. Numbers

Requirement: Use numbers for health, score, speed, cooldowns, positions, and coins

Numbers are used throughout the game for values that can be counted, measured, compared, or calculated. In my game, numbers control player health, boss health, attack cooldowns, laser speed, coin value, score, position, and movement.

this.playerMaxHealth = config.playerHealth ?? 5;
this.playerHealth = this.playerMaxHealth;
this.attackCooldownMs = config.attackCooldownMs ?? 450;
this.laserSpeed = config.laserSpeed ?? 14;
this.coinValue = config.coinValue ?? 25;
this.levelScore = 0;

This proves the numbers requirement because the game uses numeric values to control health, timing, projectile movement, coin rewards, and score calculation.

2. Strings

Requirement: Use strings for names, modes, paths, and messages

Strings are text values. In my game, strings are used for the selected game mode, player names, sprite image paths, localStorage keys, enemy names, and HUD messages.

this.gameMode = config.gameMode ?? localStorage.getItem('peppaGameMode') ?? 'singlePlayer';
this.playerName = config.playerName || 'Ishan';

const p1CharImage = localStorage.getItem('peppaPlayer1CharImage') || 'ishan-jha.png';
const p2CharName = localStorage.getItem('peppaPlayer2CharName') || 'Player 2';

this.updateHud(`Coin collected! +${this.coinValue} score`);

This proves the strings requirement because the game uses text values to store modes, names, file paths, browser storage keys, and player-facing messages.

3. Booleans

Requirement: Use true / false flags for game state

Booleans are values that are either true or false. In my game, booleans are used as flags to track whether the battle is over, whether an attack was requested, whether a laser belongs to a player, whether a coin was collected, and whether the boss has been defeated.

this.battleEnded = false;
this.attackRequested = false;
this.player2AttackRequested = false;

this.lasers.push({
    x: fromX,
    y: fromY,
    isPlayerLaser,
    life: 60
});

this.isDefeated = false;

This proves the booleans requirement because the game uses true-or-false values to control decisions, stop repeated actions, and track whether events have happened.

4. Arrays

Requirement: Store multiple related values in lists

Arrays are lists of values. In my game, arrays store active lasers, coins, game classes, power-up options, and leaderboard entries. This lets the game handle many objects without creating a separate variable for every single laser, coin, or leaderboard score.

this.lasers = [];
this.coins = [];
this.leaderboard = [];

this.classes = [
    { class: GameEnvBackground, data: image_data_background },
    { class: Player, data: sprite_data_ishan }
];

this.options = [
    { name: 'Extra Speed', description: 'Move faster in battle' },
    { name: 'Extra Health', description: 'Start with more health' },
    { name: 'Extra Damage', description: 'Deal more damage per laser' }
];

This proves the arrays requirement because the game uses arrays to store and update collections of lasers, coins, class definitions, leaderboard scores, and power-up choices.

5. Objects / JSON

Requirement: Use object literals and JSON-style data

Objects store related information using key-value pairs. In my game, objects are used for configuration settings, sprite data, laser data, character data, spawn positions, leaderboard entries, and power-up data. These objects are similar to JSON because they organize data with property names and values.

const charData = {
    image: char.image,
    name: char.name,
    accentColor: accentColor
};

this.playerSpawn = {
    x: width * 0.12,
    y: height * 0.72
};

this.lasers.push({
    x: fromX,
    y: fromY,
    vx,
    vy,
    isPlayerLaser,
    source: sourceId,
    life: 60,
    maxLife: 60
});

This proves the objects / JSON requirement because the game uses object literals to group related data together and pass structured information between different parts of the game.


🔢

Data Types


this.gameMode = config.gameMode ?? localStorage.getItem('peppaGameMode') ?? 'singlePlayer'; // String
this.playerMaxHealth = config.playerHealth ?? 5;      // Number
this.player2Health = this.player2MaxHealth;          // Number
this.attackRequested = false;                      // Boolean
this.player2AttackRequested = false;               // Boolean
this.lasers = [];                                     // Array
this.coins = [];                                      // Array
this.playerSpawn = { x: width * 0.12, y: height * 0.72 }; // Object

The updated game uses many JavaScript data types. Strings store the game mode and player names, numbers store health and score values, booleans track whether attacks were requested, arrays store lasers and coins, and objects store spawn positions and sprite data.

A strong example is this.gameMode. It can be 'singlePlayer' or 'twoPlayer', and the rest of the code changes behavior based on that string.


🔁

Arrays and Collections


Arrays are used to store multiple game objects, lasers, coins, and leaderboard entries. This lets the game update many items every frame without needing separate variables for each one.

this.classes = [
    { class: GameEnvBackground, data: image_data_background },
    { class: Player, data: sprite_data_ishan }
];

if (this.gameMode === 'twoPlayer') {
    this.classes.push({ class: Player, data: sprite_data_player2 });
} else {
    this.classes.push({ class: PeppaBossEnemy, data: sprite_data_enemy });
}

This is important because the game builds a different class list depending on the selected mode. Two-player mode adds a second player, while single-player mode adds the boss enemy.

this.lasers.push({
    x: fromX,
    y: fromY,
    vx,
    vy,
    isPlayerLaser,
    source: sourceId,
    life: 60,
    maxLife: 60
});

The source property makes the laser system more flexible. A laser can come from player1, player2, or the boss, so the collision system knows who should be damaged.

← Back to College Ready Blog