conditionals lesson hacks
conditionals hacks
%%html
<output id="output"></output>
<script>
function initializeData(data = null) {
let speed = 5;
if (data !== null && data.speed !== undefined) {
speed = data.speed;
}
document.getElementById("output").innerText = "Speed: " + speed;
console.log("Speed:", speed);
}
initializeData();
const jsonData = { speed: 10 };
initializeData(jsonData);
</script>
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
speedto theinitializeData(data = null)function and give it a default value. - Add
seedto the HTML output. - Add
speedto the JSON data. - Test calling
initializeDatawith no argument, and then using adataJSON object as an argument.
Popcorn Hack Part 1 - 2: Adding IJKL Key Conditions in handleKeyDown
- Add a
casestatement for each of the IJKL keys in thehandleKeyDown({ keyCode })switch statement. - Send the key code for each IJKL key to the
gameObject.handleKeyDownmethod. - Use
console.log()to outputgameObject.
Popcorn Hack 2: Creating a Simple Attack System
- Add a
booleanvariable namedcanAttack, and set it tofalse. - Use an
ifstatement to check if the player can attack. - If
canAttackisfalse, 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 operatorto 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.
%%js
<div id="output2"></div>
<script>
function code(){
let level = "100";
let output = document.getElementById("output2");
let message = (level === "100") ? "Great, you are on the perfect level!" : "Eugh, go away noob you are under-leveled!";
output.innerHTML = message;
console.log("ran");
console.log(level, output, message);
console.log(message);
}
code();
</script>
<IPython.core.display.Javascript object>
%%js
let gameObject = {
handleKeyDown: function(event) {
const keyCode = event.keyCode || event.which;
console.log('Key Pressed:', String.fromCharCode(keyCode), 'Code:', keyCode);
}
};
const keyEvents = [
new KeyboardEvent('keydown', { keyCode: 73 }), // i
new KeyboardEvent('keydown', { keyCode: 74 }), // j
new KeyboardEvent('keydown', { keyCode: 75 }), // k
new KeyboardEvent('keydown', { keyCode: 76 }) // l
];
keyEvents.forEach(event => gameObject.handleKeyDown(event));
console.log(gameObject);
<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.
%%js
const npcDialogue = [
"Hello traveler, what brings you here?",
"The road ahead is dangerous. Do you need supplies?",
"I haven't seen anyone around here in days. Be careful!",
"Good luck on your journey! May the winds be in your favor."
];
const dialogueOptions = [
"1. Who are you?",
"2. Can you help me with directions?",
"3. Do you have any supplies?",
"4. Goodbye."
];
function displayDialogue() {
console.log("You approach the NPC. They look at you and speak...");
console.log("\nChoose your response:");
dialogueOptions.forEach(option => console.log(option));
const playerChoice = 2;
console.log(`\nYou chose option ${playerChoice}: "${dialogueOptions[playerChoice - 1]}"`);
if (playerChoice >= 1 && playerChoice <= 4) {
console.log("\nNPC says: " + npcDialogue[playerChoice - 1]);
} else {
console.log("Invalid choice.");
}
}
displayDialogue();
<IPython.core.display.Javascript object>