const windowX = window.innerWidth;
const windowY = window.innerHeight;
// Player
var playerX = windowX / 2;
var playerY = windowY / 2;
var playerSize = 20;
var playerSpeed = 7;
// Enemy
const enemyCount = 5;
let enemies = [];
class Enemy {
x = 0;
y = 0;
size = 10;
speed = 5;
constructor(x, y) {
this.x = x;
this.y = y;
}
logic() {
this.x += random(-5, 5) * this.speed;
this.y += random(-5, 5) * this.speed;
// Boundary conditions
if (this.y < 0) this.y = windowY;
if (this.y > windowY) this.y = 0;
if (this.x < 0) this.x = windowX;
if (this.x > windowX) this.x = 0;
// Collision logic
if (
this.x < playerX + playerSize &&
this.x + this.size > playerX &&
this.y < playerY + playerSize &&
this.y + this.size > playerY
) {
gameoverFlag = true;
fill(0, 255, 0);
} else {
fill(255, 0, 0);
}
square(this.x, this.y, this.size);
}
}
// Game Logic
let isPaused = false;
let startButton, pauseButton;
function setup() {
createCanvas(windowX, windowY);
setupDOM();
startGame();
}
function setupDOM() {
// Timer element
timerElement = createElement('h1', '');
timerElement.style('color', 'white');
timerElement.style('position', 'absolute');
timerElement.style('right', '5vw');
timerElement.style('top', '5vh');
// Start button
startButton = createButton('Start Game');
startButton.position(20, 20);
startButton.mousePressed(startGame);
// Pause button
pauseButton = createButton('Pause');
pauseButton.position(20, 60);
pauseButton.mousePressed(togglePause);
}
function startGame() {
isPaused = false;
gameoverFlag = false;
playerX = windowX / 2;
playerY = windowY / 2;
timer = 0;
enemies = [];
for (let i = 0; i < enemyCount; i++) {
let xRand = random(0, windowX);
let yRand = random(0, windowY);
enemies.push(new Enemy(xRand, yRand));
}
}
function togglePause() {
isPaused = !isPaused;
if (isPaused) {
pauseButton.html('Resume');
} else {
pauseButton.html('Pause');
}
}
function draw() {
background(0); // Set the background to black
if (!gameoverFlag && !isPaused) {
fill(255);
square(playerX, playerY, playerSize);
for (let enemy of enemies) {
enemy.logic();
}
// Update timer
timerElement.html('Time Survived: ' + timer);
timer++;
} else if (gameoverFlag) {
// Game Over logic
textSize(32);
fill(255);
text("Game Over", windowX / 2, windowY / 2);
}
}
function keyPressed() {
if (keyCode === LEFT_ARROW) {
playerX -= playerSpeed;
} else if (keyCode === RIGHT_ARROW) {
playerX += playerSpeed;
} else if (keyCode === UP_ARROW) {
playerY -= playerSpeed;
} else if (keyCode === DOWN_ARROW) {
playerY += playerSpeed;
}
}