xxxxxxxxxx
103
let bacteria = [];
let lives = [];
let frameofLastDeath;
let frameofGameOver;
let gameOver;
function setup() {
createCanvas(windowWidth, windowHeight);
reset();
frameofGameOver = 0;
}
function draw() {
// check if player has lives
if (gameOver) {
frameofGameOver = frameCount;
background(0);
textSize(48);
textAlign(CENTER, CENTER);
text("GAME OVER", width / 2, height / 2);
textSize(24);
text("\n\n\nClick to Restart", width / 2, height / 2);
gameOver = true;
noLoop();
} else {
background("firebrick");
// diplay, movement, collision of bacteria
for (let i = 0; i < bacteria.length; i++) {
bacteria[i].display();
bacteria[i].move();
// to prevent multiple deaths in same frame
if (frameCount - frameofLastDeath > 30) {
if (bacteria[i].collide(lives[0])) {
bacteria.splice(i, 1);
if (lives.length > 1){
lives.splice(0, 1);
} else{
gameOver = true;
}
frameofLastDeath = frameCount;
}
}
}
// check when bacteria leave the screen (separate loop for logic purpose)
for (let i = 0; i < bacteria.length; i++) {
if (bacteria[i].wallCollide()) {
bacteria.splice(i, 1);
}
}
// immune cell display
lives[0].display();
//immune cell movement control
if (keyIsDown(LEFT_ARROW) || keyIsDown(65)) {
lives[0].x -= 10;
}
if (keyIsDown(RIGHT_ARROW) || keyIsDown(68)) {
lives[0].x += 10;
}
}
if ((frameCount - frameofGameOver) % 120 == 0){
for (let i = 0; i < 10; i++) {
bacGen = new Bacteria(
int(random(20, width - 20)),
-15,
10,
int(random(2, 4))
);
bacteria.push(bacGen);
}
}
}
// Reset Game State
function reset(){
gameOver = false;
bacteria = [];
lives = [];
for (let i = 0; i < 4; i++) {
immune = new ImmuneCell(width / 2, height - 50, 20);
lives.push(immune);
}
for (let i = 0; i < 10; i++) {
bacGen = new Bacteria(
int(random(20, width - 20)),
-15,
10,
int(random(2, 4))
);
bacteria.push(bacGen);
}
frameofLastDeath = 0;
}
// Trigger reset on clicking on Game Over Screen
function mouseClicked(){
if (gameOver){
clear();
reset();
loop();
}
}