Example of a number catching game based on a quiz question. The game uses a class file.
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js"
integrity="sha512-DWtDo/6AXxH1t9p7GCWqmC4XTVK/eje94XTV6QYB39rGllLN8Tr3izDf6lkmebgqRnYh4wtSFm4CvBoA9SrdpA=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/addons/p5.sound.js"
integrity="sha512-TU9AWtV5uUZPX8dbBAH8NQF1tSdigPRRT82vllAQ1Ke28puiqLA6ZVKxtUGlgrH6yWFnkKy+sE6luNEGH9ar0A=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://unpkg.com/p5.collide2d"></script>
<!--Other class files go here >>>>-->
<script src="number.js"></script>
<script src="sketch.js"></script>
</head>
<body>
</body>
</html>
var numbers = [];
var questions = [
{ q: "1+1", ans: 2, arr: [1, 2, 3, 4, 5, 7, 11] },
{ q: "1+2", ans: 3, arr: [1, 2, 3, 4, 5, 7, 11] },
{ q: "1+4", ans: 5, arr: [1, 2, 3, 4, 5, 7, 11] }];
var count = 0;
var roundStarted = false;
playerx = 300;
playery = 400;
score = 0;
function preload() {
}
function setup() {
createCanvas(640, 480);
setInterval(makeNumbers, 3000);
}
function draw() {
background(100);
//display question
text(questions[count].q, 100, 50)
//update and display score
//loop and draw numbers falling usin gthe class
for (var i = 0; i < numbers.length; i++) {
numbers[i].move();
numbers[i].display();
}
//draw the player
playerMove();
//check for player and number collisions
checkNumbers();
}
function makeNumbers() {
if (roundStarted == false) {
for (var i = 0; i < questions[count].arr.length; i++) {
var n = new number(questions[count].arr[i], random(3, 5));
numbers.push(n);
}
roundStarted = true;
}
}
//collsision check numbers with players.
function checkNumbers() {
for (var i = numbers.length - 1; i >= 0; i--) {
//check collision
let hit = false;
hit = collideRectCircle(playerx, playery, 40, 40, numbers[i].x, numbers[i].y, 40);
if (hit == true) {
if (numbers[i].val == questions[count].ans) {
score++;
numbers.splice(i, 1); //delete
nextRound();
} else {
numbers.splice(i, 1); //delete
//could lose a life
}
}
}
}
function nextRound() {
//remove all numbers from array
for (var i = numbers.length - 1; i >= 0; i--) {
numbers.splice(i, 1); //delete
}
//increase count - need create a check to see if reach end of the gae
count++;
//reset round started = fasle
roundStarted = false
//recreate the numbers
makeNumbers();
}
//player movement function
function playerMove() {
if (keyIsDown(LEFT_ARROW)) {
playerx -= 5;
}
if (keyIsDown(RIGHT_ARROW)) {
playerx += 5;
}
fill(10);
rect(playerx, playery, 40, 40);
}
class number {
constructor(val, speed) {
this.x = random(600);
this.y = 0;
this.speed = speed;
this.val = val;
}
move() {
if (this.y < 480) {
this.y += this.speed;
} else {
//begin
this.x = random(600);
this.y = 0;
}
}
display() {
fill(10)
circle(this.x, this.y, 40);
stroke(color(100, 50, 100));
textSize(14)
text(this.val, this.x, this.y);
}
}