JavaScript Variables and HTML DOM Homework
Perform variables and HTML DOM homework using this notebook.
JavaScript Variables: Homework Notebook`
Use this Notbook to perform JavaScript Variable Homework Hacks.
Code Runner Challenge
Class definition with properties, methods, and default values
View IPYNB Source
%%js
/*
Add-Lives Homework Instructions:
- Add a reaction message for the enemy when it reacts (e.g., "Enemy reacts!").
- Add lives to player
- Reflect: Did adding lives impact the enemy? Why or why not?
- Add lives to enemy
- Reflect: How can values be the same for both player and enemy? Without duplicating assignments?
- Reflect: How can you have default values for lives, but also allow for custom values?
*/
// CODE_RUNNER: Class definition with properties, methods, and default values
let gameSpeed = 10; // Global game speed variable
// Example of a class representing a game object
class GameObject {
constructor(data) {
// Using 'this' to define properties of the class instance
this.image = data.image;
this.width = data.width;
this.height = data.height;
this.speedRatio = data.speedRatio;
// Position coordinates of the object are set to default values if arguments are not provided
this.x = data.x;
this.y = data.y;
// Speed is calculated based on the global game speed and the speed ratio
this.speed = gameSpeed * this.speedRatio;
// Store the react callback if provided
this.react = data.react || function() {
console.log('No reaction defined');
};
}
}
const player_data = {
image: 'player.png',
width: 50,
height: 50,
speedRatio: 1.5,
x: 0,
y: 0,
react: function() {
console.log(`${this.image} is reacting at position (${this.x}, ${this.y})!`);
}
};
const player = new GameObject(player_data);
console.log("Player Object (Class Instance):", player, "Type:", typeof player);
// Object reference
console.log("Player Image:", player.image);
// Activate the react callback
player.react();
const enemy_data = {
image: 'enemy.png',
width: 40,
height: 40,
speedRatio: 1.0,
x: 100,
y: 150
};
const enemy = new GameObject(enemy_data);
console.log("Enemy Object (Class Instance):", enemy, "Type:", typeof enemy);
// Object reference
console.log("Enemy Position:", `(${enemy.x}, ${enemy.y})`);
enemy.x += enemy.speed; // Move enemy based on its speed
console.log("Enemy New Position after moving:", `(${enemy.x}, ${enemy.y})`);
enemy.react(); // Enemy has default reaction
Lines: 1
Characters: 0
Output
Click "Run" in code control panel to see output ...