Let’s make sure we understand the key ideas of using conditionals in JavaScript by using them in a miniature project.
As with all challenges, do this work in pairs and in class. This means you will both submit the same work and should work together on one computer to produce the project. You can take turns typing stuff in.
To start up you should:
events-challengecart253 repositoryWith your partner(s):
Do nothing
We’re going to start with some example code for you to modify, so start paste the following code into your script.js:
/**
* The Only Move Is Not To Play
* Pippin Barr
*
* A game where your score increases so long as you do nothing.
*/
"use strict";
// Current score
let score = 0;
// Is the game over?
let gameOver = false;
/**
* Create the canvas
*/
function setup() {
createCanvas(400, 400);
}
/**
* Update the score and display the UI
*/
function draw() {
background("#87ceeb");
// Only increase the score if the game is not over
if (!gameOver) {
// Score increases relatively slowly
score += 0.05;
}
displayUI();
}
/**
* Show the game over message if needed, and the current score
*/
function displayUI() {
if (gameOver) {
push();
textSize(48);
textStyle(BOLD);
textAlign(CENTER, CENTER);
text("You lose!", width/2, height/3);
pop();
}
displayScore();
}
/**
* Display the score
*/
function displayScore() {
push();
textSize(48);
textStyle(BOLD);
textAlign(CENTER, CENTER);
text(floor(score), width/2, height/2);
pop();
}
lose() functionWe’ll want a function that handles losing. All it really needs to do is set the gameOver variable to true.
Note that it’s not enough to just have a keyPressed() event that loses, right? Any keyboard event should call lose().
Again, think about the possibilities here. Mouse movement, clicking, mouse wheel. Call lose() for all of them.
Good old online and offline. You might need to do a web search for something like “online offline event javascript” if you’re not too sure how they work. You could also check the examples for this week. Note that p5 doesn’t help you out here, you’ll need to use a Plain JavaScript approach to events for this.
Check out the Page Visibility API for this one! Looks like visibilitychange is our friend here. Again, this will have to be Plain JavaScript
This will allow all your events to call the same event handler (lose()) that sets the game to be over. Neat and tidy.
When you’re finished, show the instructor or teaching assistant your work and they will confirm you’ve passed the challenge and can submit it on the Moodle.
This challenge is pass/fail and is worth 1% of your final grade.
Once you’re cleared to submit, go to the Moodle and both submit your work. You should all separately submit:
Note: It’s fine if the project is only in one of your repositories, but it’s not a bad idea to make sure you both have it for your own reference.