xxxxxxxxxx
186
let player;
let missiles = [];
let enemies = [];
let gameStarted = false;
let gameOver = false;
function setup() {
createCanvas(400, 600);
textAlign(CENTER);
textSize(32);
player = new Player();
}
function draw() {
background(0);
if (!gameStarted) {
showTitleScreen();
return;
}
if (gameOver) {
showGameOverScreen();
return;
}
player.update();
player.show();
if (frameCount % 60 === 0) {
enemies.push(new Enemy());
}
for (let i = missiles.length - 1; i >= 0; i--) {
missiles[i].update();
missiles[i].show();
if (missiles[i].hits(enemies)) {
missiles[i].explode();
missiles.splice(i, 1);
} else if (missiles[i].offscreen()) {
missiles.splice(i, 1);
}
}
for (let i = enemies.length - 1; i >= 0; i--) {
enemies[i].update();
enemies[i].show();
if (enemies[i].hits(player)) {
gameOver = true;
}
if (enemies[i].offscreen()) {
enemies.splice(i, 1);
}
}
}
function keyPressed() {
if (!gameStarted && keyCode === 32) {
gameStarted = true;
}
if (gameOver && keyCode === 32) {
resetGame();
}
if (keyCode === 77) { // 'm' key
missiles.push(new Missile(player.x, height - 40));
}
if (keyCode === LEFT_ARROW) {
player.setDir(-1);
} else if (keyCode === RIGHT_ARROW) {
player.setDir(1);
}
}
function keyReleased() {
if (keyCode === LEFT_ARROW || keyCode === RIGHT_ARROW) {
player.setDir(0);
}
}
function showTitleScreen() {
fill(255);
text("ORPHE Shooting", width / 2, height / 2);
text("Press SPACE to start", width / 2, height / 2 + 50);
}
function showGameOverScreen() {
fill(255);
text("Game Over", width / 2, height / 2);
text("Press SPACE to restart", width / 2, height / 2 + 50);
}
function resetGame() {
gameOver = false;
player = new Player();
missiles = [];
enemies = [];
}
class Player {
constructor() {
this.x = width / 2;
this.dir = 0;
}
setDir(dir) {
this.dir = dir;
}
update() {
this.x += this.dir * 5;
this.x = constrain(this.x, 30, width - 30);
}
show() {
fill(0, 255, 0);
rectMode(CENTER);
rect(this.x, height - 20, 20, 40);
}
}
class Missile {
constructor(x, y) {
this.x = x;
this.y = y;
}
update() {
this.y -= 5;
}
show() {
fill(255);
rectMode(CENTER);
rect(this.x, this.y, 5, 10);
}
hits(enemies) {
for (let i = enemies.length - 1; i >= 0; i--) {
let enemy = enemies[i];
if (dist(this.x, this.y, enemy.x, enemy.y) < 15) {
return true;
}
}
return false;
}
explode() {
// Add explosion effect here
}
offscreen() {
return this.y < 0;
}
}
class Enemy {
constructor() {
this.x = random(width);
this.y = -30;
}
update() {
this.y += 3;
}
show() {
fill(255, 0, 0);
rectMode(CENTER);
rect(this.x, this.y, 30, 30);
}
hits(player) {
return dist(this.x, this.y, player.x, height - 20) < 25;
}
offscreen() {
return this.y > height;
}
}