Popcorn Hacks:
Develop a basic combat system that allows characters to engage in battles with enemies. This will help you practice using functions, conditionals, and basic game mechanics in JavaScript.
Popcorn Hack Part 1 - 1: Using initializeData
Function
- Add
speed
to theinitializeData(data = null)
function and give it a default value. - Add
seed
to the HTML output. - Add
speed
to the JSON data. - Test calling
initializeData
with no argument, and then using adata
JSON object as an argument.
Popcorn Hack Part 1 - 2: Adding IJKL Key Conditions in handleKeyDown
- Add a
case
statement for each of the IJKL keys in thehandleKeyDown({ keyCode })
switch statement. - Send the key code for each IJKL key to the
gameObject.handleKeyDown
method. - Use
console.log()
to outputgameObject
.
Popcorn Hack 2: Creating a Simple Attack System
- Add a
boolean
variable namedcanAttack
, and set it tofalse
. - Use an
if
statement to check if the player can attack. - If
canAttack
isfalse
, output “Can’t attack.” - Use
Math.random()
to determine if the player is allowed to attack. (Tip: Use ChatGPT for help withMath.random()
if needed!) - This will pick a random number to decide if the attack can happen.
- Use
console.log()
for all outputs.
Popcorn Hack 3: Level Requirement Check
- Use the
ternary operator
to create an output if the player meets the level requirements. - If not, output a message telling the player they are under-leveled.
- Use
console.log()
to print your output.
Homework:
Objectives
Option 1: Create a simple combat system.
- Allow characters to fight enemies.
- Use basic functions and conditionals in JavaScript.
- Focus on making it easy to understand how battles work.
Option 2: Make a dialogue system for your NPC (Non-Player Character).
- Use the
prompt()
function to ask the player for a response (choose a number from 1 to 4). - This dialogue should appear when the player gets close to the NPC and presses a button.
</span>
Additional Tips:
- For Option 1:
- Start by writing down what the characters and enemies will be. Create simple names and attributes (like health).
- Use
console.log()
to print out what's happening at each step. This will help you understand the flow of your code. - Look for example code online to see how others have created combat systems. Don't be afraid to borrow ideas!
- For Option 2:
- Plan out the dialogue options before you start coding. Write them down in a list.
- Use comments in your code to remind yourself what each part does. For example,
// Ask the player for a response
. - Test your code frequently. After writing a few lines, run it to see if it works before adding more.
POPCORN HACK 1
%%html
<output id="output"></output>
<script>
function intializeData(data = null) {
// Define default values
let scaleFactor = 9/16;
let animationRate = 1;
let position = [0, 0];
let speed = 17;
// Check if data is provided
if (data) {
scaleFactor = data.SCALE_FACTOR || scaleFactor;
animationRate = data.ANIMATION_RATE || animationRate;
position = data.INIT_POSITION || position;
speed = data.SPEED || speed;
}
document.getElementById("output").innerHTML = `
<p>Scale Factor: ${scaleFactor}</p>
<p>Animation Rate: ${animationRate}</p>
<p>Initial Position: ${position}</p>
<p>Speed: ${speed}<p>
`;
}
var data = {
SCALE_FACTOR: 1/1,
ANIMATION_RATE: 25,
INIT_POSITION: [100, 100],
SPEED: 20
}
// Uncomment one of the following lines to test the if statement in the function
//intializeData();
intializeData(data);
</script>
POPCORN HACK 1 PART 2
%%js
// Popcorn Hack 1 - 2
class GameObject {
constructor() {
this.velocity = { x: 0, y: 0 };
this.direction = '';
this.xVelocity = 1;
this.yVelocity = 1;
}
handleKeyDown({ keyCode }) {
switch (keyCode) {
case 87: // 'W' key
this.direction = 'up';
break;
case 65: // 'A' key
this.direction = 'left';
break;
case 83: // 'S' key
this.direction = 'down';
break;
case 68: // 'D' key
this.direction = 'right';
break;
case 73: // 'I' key
this.direction = 'up';
break;
case 74: // 'J' key
this.direction = 'left';
break;
case 75: // 'K' key
this.direction = 'down';
break;
case 76: // 'L' key
this.direction = 'right';
break;
}
}
}
// Example of how to use it
const gameObject = new GameObject();
console.log('Initial State:', gameObject);
gameObject.handleKeyDown({ keyCode: 87 }); // Simulate 'W' key press
console.log('After W Key Press:', gameObject);
gameObject.handleKeyDown({ keyCode: 65 }); // Simulate 'A' key press
console.log('After A Key Press:', gameObject);
gameObject.handleKeyDown({ keyCode: 83 }); // Simulate 'S' key press
console.log('After S Key Press:', gameObject);
gameObject.handleKeyDown({ keyCode: 68 }); // Simulate 'D' key press
console.log('After D Key Press:', gameObject);
gameObject.handleKeyDown({ keyCode: 73 }); // Simulate 'I' key press
console.log('After I Key Press:', gameObject);
gameObject.handleKeyDown({ keyCode: 74 }); // Simulate 'J' key press
console.log('After J Key Press:', gameObject);
gameObject.handleKeyDown({ keyCode: 75 }); // Simulate 'K' key press
console.log('After K Key Press:', gameObject);
gameObject.handleKeyDown({ keyCode: 76 }); // Simulate 'L' key press
console.log('After L Key Press:', gameObject);
<IPython.core.display.Javascript object>
POPCORN HACK 2
%%js
let canAttack = false;
if (!canAttack) {
console.log("Can't attack.");
} else {
if (Math.random() > 0.5) {
console.log("Attack successful.");
} else {
console.log("Attack failed.");
}
}
<IPython.core.display.Javascript object>
POPCORN HACK 3
%%js
let playerLevel = 7; //Sample player level
let requiredLevel = 10; //Sample required level
let message = playerLevel >= requiredLevel ? "Player meets the level requirements." : "Player is under-leveled.";
console.log(message);
Homework (Chose Option 1 and incorporated random values so every attack has a different amount of damage)
%%js
// Set up a character class
class Character {
constructor(name, health, attackPower) {
this.name = name;
this.health = health;
this.attackPower = attackPower;
}
// Sample method of how to launch an attack on enemy
attack(enemy) {
if (this.health > 0) {
let randomAttackPower = Math.floor(Math.random() * this.attackPower) + 1;
console.log(`${this.name} attacks ${enemy.name} for ${randomAttackPower} damage.`);
enemy.health -= randomAttackPower;
if (enemy.health <= 0) { // Check if the enemy is defeated
console.log(`${enemy.name} has been defeated!`);
} else {
console.log(`${enemy.name} has ${enemy.health} health remaining.`);
}
} else {
console.log(`${this.name} cannot attack because they are defeated.`);
}
}
}
// Create characters
let hero = new Character('Hero', 100, 10);
let monster = new Character('Monster', 50, 5);
// Simulate a battle through the previous classes I set up
hero.attack(monster); // Hero attacks monster
monster.attack(hero); // Monster attacks hero
hero.attack(monster); // Hero attacks monster again
monster.attack(hero); // Monster attacks hero again
hero.attack(monster); // Hero attacks monster again
<IPython.core.display.Javascript object>