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
  1. Add speed to the initializeData(data = null) function and give it a default value.
  2. Add seed to the HTML output.
  3. Add speed to the JSON data.
  4. Test calling initializeData with no argument, and then using a data JSON object as an argument.
Popcorn Hack Part 1 - 2: Adding IJKL Key Conditions in handleKeyDown
  1. Add a case statement for each of the IJKL keys in the handleKeyDown({ keyCode }) switch statement.
  2. Send the key code for each IJKL key to the gameObject.handleKeyDown method.
  3. Use console.log() to output gameObject.

Popcorn Hack 2: Creating a Simple Attack System
  1. Add a boolean variable named canAttack, and set it to false.
  2. Use an if statement to check if the player can attack.
  3. If canAttack is false, output “Can’t attack.”
  4. Use Math.random() to determine if the player is allowed to attack. (Tip: Use ChatGPT for help with Math.random() if needed!)
  5. This will pick a random number to decide if the attack can happen.
  6. Use console.log() for all outputs.

Popcorn Hack 3: Level Requirement Check
  1. Use the ternary operator to create an output if the player meets the level requirements.
  2. If not, output a message telling the player they are under-leveled.
  3. Use console.log() to print your output.

Hack 1-1

%%html
<div id="speedOutput"></div>
<script>
function initializeData(data = null) {
    // Set a default value for speed if it's not provided in data
    const defaultSpeed = 1;
    const initializedData = {
        speed: data?.speed || defaultSpeed // Use the provided speed or default value
    };
    // Add to HTML output
    document.getElementById('speedOutput').textContent = Speed: ${initializedData.speed};
    // Output the JSON data to the console for testing
    console.log(JSON.stringify(initializedData, null, 2));
    return initializedData; // Return the initialized data object
}
// Test cases
initializeData(); // Call with no arguments to test default speed
initializeData({ speed: 5 }); // Call with a data JSON object as an argument
</script>


Hack 1-2

%%javascript
// Listens for speceific event to trigger function
document.addEventListener("keydown", handleKeyDown);
function handleKeyDown({ keyCode }) {
    const gameObject = {
        handleKeyDown: function (code) {
            console.log(Key pressed with code: ${code});
        }
    };
    // Tell it to handle keycodes
    switch (keyCode) {
        case 73: // I key
            gameObject.handleKeyDown(keyCode);
            break;
        case 74: // J key
            gameObject.handleKeyDown(keyCode);
            break;
        case 75: // K key
            gameObject.handleKeyDown(keyCode);
            break;
        case 76: // L key
            gameObject.handleKeyDown(keyCode);
            break;
        default:
            console.log("Other key pressed");
    }
    // Log the gameObject to the console
    console.log(gameObject);
}
<IPython.core.display.Javascript object>

Hack 2

%%javascript

const gameObject = {
    canAttack: false, // Boolean variable 
    // check if the player can attack
    checkAttack: function () {
        // generate a random number between 0 and 1
        const randomValue = Math.random();
        // Use the random value to determine if the player can attack
        if (randomValue < 0.5) { // if value is less than 0.5 then attack is true
            this.canAttack = true; 
        } else {
            this.canAttack = false; // Player cannot attack if number greater than 0.6
        }
        // Check if the player can attack
        if (this.canAttack) {
            console.log("Player can attack.");
        } else {
            console.log("Can't attack.");
        }
        // Output the random value for debugging
        console.log(`Random value: ${randomValue}`);
    }
};
// Call the checkAttack method to determine if the player can attack
gameObject.checkAttack();
<IPython.core.display.Javascript object>

Hack 3

%%javascript

const gameObject = {
    playerLevel: 9, // player level, you can change this to any number to get a different output :) 
    requiredLevel: 10, // Example required level
    //check if meets level requirement
    checkLevelRequirements: function () {
        // Use the ternary operator
        const message = this.playerLevel >= this.requiredLevel
            ? "Congratulations! You meet the level requirements."
            : "You are under-leveled. Level up to continue.";
        
        console.log(message);
    }
};
// Call the checkLevelRequirements method to check the player's level
gameObject.checkLevelRequirements();
<IPython.core.display.Javascript object>

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.

Homework

%%javascript
// Define a character class
class Character {
    constructor(Aditya, health, attackPower) {
        this.name = Aditya; // define the character name
        this.health = health; // how much health
        this.attackPower = attackPower; // damage per attack
    }
    // how attack other enemy
    attack(enemy) {
        console.log(`${this.name} attacks ${enemy.name} for ${this.attackPower} damage!`);
        enemy.takeDamage(this.attackPower);
    }
    // taking damage
    takeDamage(damage) {
        this.health -= damage; // Reduce health by damage amount
        console.log(`${this.name} has ${this.health} health remaining.`);
    }
    // Check if the character is still alive
    isAlive() {
        return this.health > 0;
    }
}
// create the character, and enemy
const player = new Character('Aditya', 100, 20);
const enemy = new Character('Monster', 50, 15);
// function using if else
function combat() {
    while (player.isAlive() && enemy.isAlive()) {
        player.attack(enemy); // Player attacks enemy
        
        if (enemy.isAlive()) {
            enemy.attack(player); // Enemy attacks player
        } else {
            console.log(`${enemy.name} has been defeated!`);
            break; // End combat if enemy is defeated
        }
    }
    // Check if the player is alive after the combat
    if (!player.isAlive()) {
        console.log(`${player.name} has been defeated! Game Over.`);
    }
}
// Start the combat
combat();
<IPython.core.display.Javascript object>