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.

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.

%%html

<h3>Popcorn Hack 1.1<h3/>

<output id="output"></output>

<script>
function intializeData(data = null) {
    // Define default values
    let scaleFactor = 9/16;
    let animationRate = 1.5;
    let position = [10, 100];
    let speed = 1000000000

    // 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: 1000000000
}

// Uncomment one of the following lines to test the if statement in the function
//intializeData();
intializeData(data);

</script>
%%html

<h3>Popcorn Hack 1.2</h3>

<output id="output"></output>

<script>

    class GameObject {
        constructor() {
            this.velocity = { x: 0, y: 0 };
            this.direction = '';
            this.xVelocity = 1;
            this.yVelocity = 1;
        }

        handleKeyDown({ keyCode }) {
            switch (keyCode) {
                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 usage
const gameObject = new gameObject();
console.log('Initial State:', 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);
</script>

Popcorn Hack 1.2

%%html

<h3>Popcorn Hack 2</h3>

<output id="output"></output>

<script>
    const playerLevel = 10; // Example player level
    const requiredLevel = 5; // Example required level

    const output = playerLevel >= requiredLevel 
        ? "Player meets the level requirements." 
        : "Player is underleveled.";

    console.log(output);

</script>

Popcorn Hack 2

%%html
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>NPC - Player Communication</title>
        <style>
            #dialogueBox {
                margin-top: 20px;
                padding: 20px;
                border: 1px solid black;
                width: 300px;
                background-color: #f0f0f0;
                color: black;  /* Text color set to black */
            }

            button {
                margin-top: 20px;
                padding: 10px 20px;
                cursor: pointer;
            }

            #responseBox {
                margin-top: 20px;
            }
        </style>
    </head>
    <body>
        <h1>NPC - Player Communication</h1>
        <button id="talkButton">Talk to NPC</button>

        <div id="dialogueBox" style="display: none;"></div>

        <div id="responseBox" style="display: none;">
            <label for="playerChoice">Enter your response (1-4): </label>
            <input type="number" id="playerChoice" min="1" max="4" />
            <button id="submitChoice">Submit Response</button>
        </div>

        <script>
            // Function to display the NPC's question and handle the player's response
            function askQuestionAndHandleResponse() {
                // Display the question and the four options
                document.getElementById("dialogueBox").textContent = 
                    "NPC: I need your help with something. What would you like to do?\n\n" +
                    "1. Help the NPC with their task\n" +
                    "2. Ask the NPC about the task\n" +
                    "3. Ignore the NPC and walk away\n" +
                    "4. Tell the NPC you're too busy";
                document.getElementById("dialogueBox").style.display = "block";

                // Show the input field and submit button for the player's response
                document.getElementById("responseBox").style.display = "block";
            }

            // Function to process the player's response after they submit it
            function processPlayerResponse() {
                // Get the player's choice from the input field
                let playerChoice = document.getElementById("playerChoice").value;
                let npcDialogue = "";

                // Handle the player's response based on their choice
                switch (playerChoice) {
                    case "1":
                        npcDialogue = "NPC: Thank you! I knew I could count on you. Let's get started!";
                        break;
                    case "2":
                        npcDialogue = "NPC: The task involves finding a rare herb in the forest. Will you help?";
                        break;
                    case "3":
                        npcDialogue = "NPC: Oh... okay. Maybe next time then.";
                        break;
                    case "4":
                        npcDialogue = "NPC: I understand, life gets busy. Let me know if you change your mind.";
                        break;
                    default:
                        npcDialogue = "NPC: Sorry, I didn't understand your response. Please choose a number between 1 and 4.";
                }

                // Show the NPC's response in the dialogue box
                document.getElementById("dialogueBox").textContent = npcDialogue;

                // Hide the input field and submit button after the response is processed
                document.getElementById("responseBox").style.display = "none";
            }

            // Event listener for the "Talk to NPC" button
            document.getElementById("talkButton").addEventListener("click", function() {
                askQuestionAndHandleResponse();
            });

            // Event listener for the "Submit Response" button
            document.getElementById("submitChoice").addEventListener("click", function() {
                processPlayerResponse();
            });
        </script>

    </body>
</html>

NPC - Player Communication

NPC - Player Communication