xxxxxxxxxx
133
let playerX, playerY;
let playerSize = 100;
let bulletSize = 5;
let bullets = [];
let enemies = [];
let asteroids = [];
let spawnEnemyInterval, spawnAsteroidInterval;
let spaceship;
function preload(){
spaceship = loadImage("spaceShip.png");
}
function setup() {
createCanvas(400, 600);
playerX = width / 2;
playerY = height - 50;
spawnEnemyInterval = setInterval(spawnEnemy, 1500);
spawnAsteroidInterval = setInterval(spawnAsteroid, 2000);
}
function draw() {
background(0);
// move the player with arrow keys and wrap around the screen
if (keyIsDown(LEFT_ARROW)) {
playerX -= 5;
if (playerX < 0) {
playerX = width;
}
}
if (keyIsDown(RIGHT_ARROW)) {
playerX += 5;
if (playerX > width) {
playerX = 0;
}
}
// draw the player
fill(255);
image(spaceship, playerX - playerSize / 2, playerY - playerSize / 2, playerSize, playerSize);
// move and draw the bullets
for (let i = bullets.length - 1; i >= 0; i--) {
bullets[i].y -= 10;
fill(255, 255, 0);
ellipse(bullets[i].x, bullets[i].y, bulletSize);
// remove the bullet if it goes off the screen
if (bullets[i].y < 0) {
bullets.splice(i, 1);
} else {
// check for collisions between bullet and enemy
for (let j = enemies.length - 1; j >= 0; j--) {
if (dist(bullets[i].x, bullets[i].y, enemies[j].x, enemies[j].y) < playerSize) {
// bullet hit an enemy, remove both
bullets.splice(i, 1);
enemies.splice(j, 1);
break;
}
}
}
}
// move and draw the enemies
for (let i = enemies.length - 1; i >= 0; i--) {
enemies[i].y += 5;
fill(255, 0, 0);
ellipse(enemies[i].x, enemies[i].y, playerSize/4);
// remove the enemy if it goes off the screen
if (enemies[i].y > height) {
enemies.splice(i, 1);
} else {
// check for collisions between player and enemy
if (dist(playerX, playerY, enemies[i].x, enemies[i].y) < playerSize/4) {
// game over
textSize(32);
textAlign(CENTER);
fill(255);
text("GAME OVER", width / 2, height / 2);
noLoop();
clearInterval(spawnEnemyInterval);
clearInterval(spawnAsteroidInterval);
}
}
}
// move and draw the asteroids
for (let i = asteroids.length - 1; i >= 0; i--) {
asteroids[i].y += 3;
fill(255);
ellipse(asteroids[i].x, asteroids[i].y, playerSize/4);
// remove the asteroid if it goes off the screen
if (asteroids[i].y > height) {
asteroids.splice(i, 1);
} else {
// check for collisions between player and asteroid
if (dist(playerX, playerY, asteroids[i].x, asteroids[i].y) < playerSize/4) {
//player hit an asteroid, reduce player size and remove asteroid
playerSize -= 5;
asteroids.splice(i, 1);
}
}
}
}
function keyPressed() {
if (keyCode === 32) { // spacebar
bullets.push({
x: playerX,
y: playerY - playerSize / 2 - bulletSize / 2
});
}
}
function spawnEnemy() {
enemies.push({
x: random(width),
y: -playerSize
});
setTimeout(spawnEnemy, random(1500, 2000));
}
function spawnAsteroid() {
asteroids.push({
x: random(width),
y: -playerSize
});
setTimeout(spawnAsteroid, random(2000, 3000));
}
spawnEnemy();
spawnAsteroid();