Constellators - Conditionals HW
Categories: JavaScript HomeworkThese are the homework problems and popcorn hacks, created by Team Constellators.
Conditionals
Popcorn Hack 1 - Simple Conditionals
Instructions: Finish the code in the cell below (fill in underlines and add lines of code) so it becomes a functioning conditional. What you make is up to you!
Examples of conditionals you could use:
1) Define your mood today and give yourself ice cream if you’re happy
- challenge 1: add “else if” conditionals that echo different strings based on different moods
- challenge 2: add user input to define a “mood” variable
2) Define the weather today and echo “It’s sunny outside!” if it’s sunny
- challenge 1: add “else if” conditionals that define other weather
- challenge 2: let the user input today’s weather and respond automatically
3) Define your age as a variable and check whether you are an adult or a child.
- challenge 1: expand to add other categories using “else if” conditionals
- challenge 2: create a random age generator and test the conditional multiple times to see different results
The code is currently NOT functional. When you have completed this popcorn hack, the code should work. Have fun!
%%html
<p>Mood: happy, sad, or angry</p>
<input type="text" id="ph1mood" placeholder="Enter your mood">
<p>Weather: sunny, rainy, or cloudy</p>
<input type="text" id="ph1weather" placeholder="Enter the weather outside">
<p>Age</p>
<input type="number" id="ph1age" placeholder="Enter your current age">
<button id="ph1Button">Submit</button>
<div id="outputPH1">Results will appear here:<br></div>
<script>
(() => {
const output = document.getElementById("outputPH1");
const moodInput = document.getElementById("ph1mood");
const weatherInput = document.getElementById("ph1weather");
const ageInput = document.getElementById("ph1age");
function writeOutput(message){
console.log(message);
output.innerText += "\n" + message;
}
const submitButton = document.getElementById("ph1Button");
submitButton.addEventListener("click", () => {
output.innerText = "";
writeOutput("------ Mood ------");
let mood = moodInput.value;
if (mood == "happy") { //
writeOutput("You ate ice cream because you're happy"); // eat ice cream if happy
} else if (mood == "sad") {
writeOutput("You're sad but you decided to eat ice cream anyway"); // eat ice cream if sad
} else if (mood == "angry") {
writeOutput("You decide to cool off your anger with... i c e c r e a m"); // eat even more ice cream if angry
} else {
writeOutput(`You're feeling ${mood}... but you decide to eat ice cream :)`); // there is no such thing as too much ice cream
}
writeOutput("------ Weather ------");
let weather = weatherInput.value;
if (weather == "sunny") {
writeOutput("It is sunny outside, so you put on a hat");
} else if (weather == "rainy") {
writeOutput("It is raining so you use an umbrella (but you still can't skip swim PE)");
} else if (weather == "cloudy") {
writeOutput("It is cloudy outside, it might start raining soon");
} else {
writeOutput(`It is ${weather} outside`);
}
writeOutput("------ Age ------");
let age = ageInput.value;
if (age >= 18){
writeOutput("You are an adult");
} else {
writeOutput("You are not an adult");
}
writeOutput("------ Random Age ------");
let randomAge = Math.floor(Math.random() * 99) + 1;
writeOutput(`Random Age: ${randomAge}`);
if (randomAge >= 18){
writeOutput("(Random) You are an adult");
} else {
writeOutput("(Random) You are not an adult");
}
})
})();
</script>
Mood: happy, sad, or angry
Weather: sunny, rainy, or cloudy
Age
Popcorn Hack 2 - Vending Machine
Instructions: This hack is a bit more complicated than the first. Points will be awarded based on effort and completion.
Analyze the block of code below. Then, complete the following instructions:
You’re hungry, so you go to your nearest vending machine for a snack. It makes you wonder if you’d be able to build your own. You can!… Digitally. Below, fill in the blanks so that when someone is prompted with food options, there are sub options within each food. (ex: Chocolate > Milk Chocolate)
1) Create variables:
- snackChoice -> user input (prompt) to determine which random snack is chosen (number from 1-3)
2) Add basic conditionals determining what type of snack was chosen
3) Add nested if statements for extra behavior
- Inside your chocolate condition:
- Add user input to determine what type of chocolate the user wants
- Inside your candy condition:
- Add user input to determine what color candy the user wants
4) Challenge (OPTIONAL):
- Make it so that there is a 10% chance of the vending machine giving you an extra cookie!
%%html
<div id="outputPH2">Results will appear here:<br></div>
<script>
(() => {
const output = document.getElementById("outputPH2");
let snackChoice = prompt("Choose a number: 1, 2, or 3 to get a snack! (10% chance of a free cookie!)");
if (snackChoice == "1") { // Fill in the condition for chocolate bar
let chocolateType = prompt("You got a chocolate bar! Choose your type: milk or dark?");
// Nested condition for chocolate type
if (chocolateType.toLowerCase() === "milk") { // Fill in milk
output.innerText += "\nYou got chocolate milk"; // Fill in message for milk chocolate
} else if (chocolateType.toLowerCase() === "dark") { // Fill in dark
output.innerText += "\nYou chose dark chocolate because you have horrible taste in chocolate"; // Fill in message for dark chocolate
} else {
output.innerText += "\nNo chocolate for you because you didn't say milk or dark smh"; // Fill in message for unknown type
}
} else if (snackChoice == "2") { // Fill in the condition for chips
output.innerText += "\nYou got chips"; // Fill in message for chips
} else if (snackChoice == "3") { // Fill in the condition for candy
let candyColor = prompt("You got candy! Choose your color: red, green, or yellow?");
// Nested condition for candy color
if (candyColor.toLowerCase() === "red") { // Fill in red
output.innerText += "\nYou ate a cherry Starbust (goated flavor ngl)"; // Fill in message for red candy
} else if (candyColor.toLowerCase() === "green") { // Fill in green
output.innerText += "\nYou got lettuce flavored candy (why would you choose green?)"; // Fill in message for green candy
} else if (candyColor.toLowerCase() === "yelow") { // Fill in yellow
output.innerText += "\nYou ate three bags of peanut M&Ms"; // Fill in message for yellow candy
} else {
output.innerText += "\nYou decide that candy is too unhealthy and you already eat too much sugar"; // Fill in message for unknown candy color
}
} else {
output.innerText += "\nYou don't get food (invalid snack choice)"; // Fill in message for invalid snack choice
}
// Challenge: 10% chance of extra cookie
if (Math.random() <= .1) { // How would you create a random number with a 10% chance of fitting some criteria?
output.innerText += "Bonus treat! The machine gives you an extra cookie!\n";
}
})();
</script>
Homework
Complete the following questions in the next code block.
1) Create a variable called “temperature” that defines a temperature. If it’s above 80 degrees, print “It’s hot outside!”. Otherwise, print “It’s nice outside.”
2) Create a variable called “score”. If score >= 90 print “A”, 80-89 print “B”, 70-79 print “C”, otherwise print “Needs improvement.”
3) Add a function to your “score” variable that prompts the user to input their score.
4) Define a variable “number”. If it’s even, print “Even Number”; otherwise, print “Odd number.”
5) Instead of defining the variable “number,” make the number a random integer from 1-10.
6) Define a variable called “day” (like ‘Monday’, ‘Tuesday’, etc.) and use a switch statement to print a message for that day.
7) Add statements to the previous conditional: If today is ‘Saturday’ or ‘Sunday’, print “Weekend!”; else print “Weekday!”.
8) Create a boolean called “loggedIn” (true or false). If true, print “Welcome back!”, otherwise print “Please log in.”
9) Define a variable “weather”. If it’s raining, print “It’s raining.” Else, print “Go outside, it’s a nice day today!”
10) Extra Credit: Submit the original OOP Breakout Game Code (found on OpenCS) after making the following edits:
- Add a conditional to the game that changes the color of the ball every time it hits the wall or another brick.
- Try making the ball do something different when it collides (ex: speed up, shrink, glow).
- Make sure your code is functional before you submit!
- Have fun!
%%html
<input type="number" id="hwScoreInput" placeholder="Enter your test score">
<button id="submitHW">Show results</button>
<div id="outputHW">Results will appear here:<br></div>
<script>
(() => {
const output = document.getElementById("outputHW");
function writeOutput(msg){
console.log(msg);
output.innerText += "\n" + msg;
}
const submitButton = document.getElementById("submitHW");
submitButton.addEventListener("click", () => {
output.innerText = "";
// 1
let randTemp = Math.floor(Math.random() * 100);
writeOutput(`Random temperature: ${randTemp}`);
if (randTemp > 80){
writeOutput("It's hot outside!");
} else if (randTemp > 60){
writeOutput("It's nice outside");
} else if (randTemp > 20){
writeOutput("It is absolutely freezing outside");
} else {
writeOutput("It's joever :(");
}
// 2+3
let score = document.getElementById("hwScoreInput").value;
writeOutput(`\nScore: ${score}`)
if (score >= 90){
writeOutput("You got a A");
} else if (score >= 80) {
writeOutput("You got a B");
} else if (score>=70) {
writeOutput("You got a C");
} else {
writeOutput("Needs improvement");
}
// 4+5
let randomNumber = Math.floor(Math.random() * 10);
writeOutput(`\nRandom number: ${randomNumber}`);
if (randomNumber % 2 == 0){
writeOutput("Even Number");
} else {
writeOutput("Odd Number");
}
// 6 and... SIX SE-
const possibleDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
let randomDay = possibleDays[Math.floor(Math.random() * 7)];
writeOutput(`\nRandom day: ${randomDay}`);
let dayMessage;
let isWeekend;
switch (randomDay) {
case "Monday":
dayMessage = "weekend's over :(";
isWeekend = false;
break;
case "Tuesday":
dayMessage = "swim PE for me...";
isWeekend = false;
break;
case "Wednesday":
dayMessage = "school starts late";
isWeekend = false;
break;
case "Thursday":
dayMessage = "AKA Friday Eve";
isWeekend = false;
break;
case "Friday":
dayMessage = "LETS GOOOO";
isWeekend = false;
break;
case "Saturday":
dayMessage = "zzzzz";
isWeekend = true;
break;
case "Sunday":
dayMessage = "weekend's already over??";
isWeekend = true;
break;
}
writeOutput(`${randomDay} - ${dayMessage} - ${isWeekend ? "Weekend" : "Weekday"}`);
// 8
let loggedIn = Math.floor(Math.random()) >= .5;
writeOutput(`\nLogged in: ${loggedIn}`);
writeOutput(loggedIn ? "Welcome back!":"Please log in");
// 9
const possibleWeather = ["rainy", "sunny", "clear"];
let weather = possibleWeather[Math.floor(Math.random() * 3)];
writeOutput(`\nRandom weather: ${weather}`);
writeOutput(weather=="rainy" ? "It's rainy outside" : "Go outside, it's a nice day today! (Touch gr*ss)");
// 10
// no
})
})();
</script>