xxxxxxxxxx
143
// @AminAhmadAhmadi
// Coding Challenge #5: Space Invaders
// https://youtu.be/biN3v3ef-Y0
var ship;
var flowers = [];
var drops = [];
var gameover = false;
var score = 0;
var Hscore = 0;
var scl=2;
function setup() {
createCanvas(640*scl, 400*scl);
rectMode(CENTER);
ship = new Ship();
for (let i = 0; i < 5; i++) {
flowers[i] = new Flower(i * 80 + 80, 60);
}
}
function draw() {
if (!gameover) {
background(60);
for (let i = drops.length - 1; i >= 0; i--) {
drops[i].show();
drops[i].move();
if (drops[i].x < -10) {
drops.splice(i, 1);
}
for (let j = flowers.length - 1; j >= 0; j--) {
if (drops[i].hits(flowers[j])) {
flowers[j].heart -= 15;
drops.splice(i, 1);
break;
}
}
}
let ouT = false;
for (let j = flowers.length - 1; j >= 0; j--) {
flowers[j].show();
flowers[j].move();
if (flowers[j].y > height) {
gameover = true;
}
if (flowers[j].x > width - flowers[j].w - 20 || flowers[j].x < flowers[j].w + 20) {
ouT = true;
}
if (flowers[j].dead()) {
flowers.push(new Flower(this.flowers[j].x, 60))
flowers.splice(j, 1);
score++;
}
}
if (ouT) {
for (let j = flowers.length - 1; j >= 0; j--) {
flowers[j].shiftDown();
}
}
ship.move();
ship.show();
drawScore();
} else {
if (score > Hscore) {
Hscore = score;
}
background(255, 0, 0);
textAlign(CENTER);
fill(255);
noStroke();
textSize(48);
if (score == Hscore) {
text('High Score: ' + Hscore, width / 2, height / 2 + 50)
} else {
text('Your Score: ' + score, width / 2, height / 2 + 50);
textSize(20);
text('High Score: ' + Hscore, width / 2, height / 2 + 80);
}
textSize(72);
text('GAMEOVER!', width / 2, height / 2 - 20)
textSize(12);
text('Press spacebar to start again', width / 2, height - 15)
}
}
function drawScore() {
textAlign(LEFT);
noStroke();
textSize(16);
if (Hscore == 0) {
fill(255);
text('Score: ' + score, 10, 20)
} else if (score <= Hscore) {
fill(255);
text('Score: ' + score, 10, 20)
fill(128);
text('High Score: ' + Hscore, 10, 40)
} else if (score > Hscore) {
fill(255);
text('New High Score: ' + score, 10, 20)
}
}
function keyReleased() {
if (key !== ' ') {
ship.setDir(0);
}
}
function keyPressed() {
if (key === ' ') {
var drop = new Drop(ship.x, ship.y);
drops.push(drop);
}
if (gameover && key === ' ') {
gameover = false;
score = 0;
flowers = [];
drops = [];
for (let i = 0; i < 5; i++) {
flowers[i] = new Flower(i * 80 + 80, 60);
}
}
if (keyCode === RIGHT_ARROW) {
ship.setDir(1);
} else if (keyCode === LEFT_ARROW) {
ship.setDir(-1);
}
}