Mathematical ยท String Operations ยท Boolean Expressions
Operators are the actual computations that run every frame to produce the game's behavior. The boss physically moves because of += (dx/distance) * moveSpeed. The laser system works because of vector math. The fight logic branches because of boolean comparisons.
Every frame, mathematical operators update positions, calculate distances, and clamp values. The boss's chase AI is entirely arithmetic โ subtract centers, divide by distance, multiply by speed.
// Boss movement โ normalize direction vector, scale by speed
const dx = (target.position.x + target.width / 2) - myCenterX; // -
const dy = (target.position.y + target.height / 2) - myCenterY; // -
const distance = Math.hypot(dx, dy); // โ(dxยฒ + dyยฒ)
this.position.x += (dx / distance) * this.moveSpeed; // / * +=
this.position.y += (dy / distance) * this.moveSpeed; // / * +=
// Laser position update each frame (+= velocity)
L.x += L.vx; // +=
L.y += L.vy; // +=
L.life -= 1; // -=
// Math.max() prevents health from going negative
this.health = Math.max(0, this.health - amount); // - inside max()
// Score calculation โ time bonus + HP bonus
const score = baseScore + (timeRemaining * 10) + (playerHealth * 25); // + *
Math.hypot(dx, dy) calculates the straight-line distance. Dividing by it normalizes the direction to length 1, so the boss always moves exactly moveSpeed pixels per frame regardless of distance.
Run this to see the boss chase math. Try moving the player position and see how velocity changes.
String operators build file paths, construct console messages, and create the CSS values that control visual effects. Template literals are the primary tool โ they concatenate strings and variable values in one readable expression.
// Template literals โ build asset paths dynamically
src: `${path}/images/gamify/${config.enemyImage}`
// String concatenation in HUD messages
hudText = `${config.enemyName} โ HP: ${boss.health}/${boss.maxHealth}`;
// Template literal for console debug output
console.log(`[Boss] Hit! HP: ${this.health}/${this.maxHealth}`);
console.log(`[Hitbox] pos=(${Math.round(this.position.x)},${Math.round(this.position.y)})`);
// String used as CSS filter value
this.canvas.style.filter = 'grayscale(1) brightness(0.8)';
// encodeURIComponent() โ string operation for API URL building
const url = `https://itunes.apple.com/search?term=${encodeURIComponent(searchTerm)}&entity=song`;
`${}`) are cleaner than 'text' + variable + 'text'. The asset path template is especially important โ one wrong character and the sprite fails to load.
Run this to see template literals and string operations. Try changing the enemy name and image.
Boolean expressions combine comparison operators (===, <, >, <=) with logical operators (&&, ||, !) to create compound conditions. The AABB collision check is the most complex: four comparisons joined by && to detect rectangle overlap.
// AABB collision โ all FOUR conditions must be true simultaneously with &&
if (hitLeft < boss.position.x + boss.width && // left edge
hitLeft + hitW > boss.position.x && // right edge
hitTop < boss.position.y + boss.height && // top edge
hitTop + hitH > boss.position.y) { // bottom edge
boss.takeDamage(1);
this.lasers.splice(i, 1);
}
// || โ fallback value, prevents divide-by-zero
const len = Math.hypot(dx, dy) || 1;
// ! โ invert boolean flag to check "not defeated"
if (!boss.isDefeated && now - this.lastAttackAt >= cooldown) {
this.spawnLaser();
}
// === comparison for exact equality checks
if (this.health === 0) { this.isDefeated = true; }
if (event.code === 'Space') { this.attackRequested = true; }
&& conditions because all four must be true for a collision. If the laser flew past the right side of the boss, condition 2 fails and && short-circuits โ the rest aren't checked and no damage is dealt. || 1 is a defensive boolean expression: if Math.hypot returns 0 (player and boss are perfectly overlapping), dividing by zero would produce Infinity for velocity, which would break movement. The || 1 falls back to 1 to prevent that.
| Operator Type | Operators | Where Used in the Game |
|---|---|---|
| Mathematical | + - * / Math.hypot() Math.max() |
Boss chase movement, laser velocity, health clamping, score calculation |
| String Operations | Template literals `${}`, encodeURIComponent() |
Asset paths, HUD text, console logs, API URL building |
| Boolean Expressions | && || ! === < > <= >= |
Collision detection, win/lose conditions, cooldown checks, attack gating |
| Assignment | = += -= |
Position updates every frame, health changes, timestamp resets |
| Nullish / Optional | ?? ?. |
Safe config reading โ prevents crash if data properties are missing |
Mathematical Expressions Homework โ Shows understanding of mathematical operations used in position calculations, collision detection, and score computations.
Run the code below to see all three operator types in action โ vector math for boss movement, a template literal HUD string, and a boolean AABB collision check.
Modify values and run to see how operators change game behavior. Try changing moveSpeed, the player/boss positions, or the laser hitbox dimensions.