import GameConfig from "../config/GameConfiguration.js"; import Logger from "../utils/Logger.js"; import Time from "../utils/Time.js"; import GameRenderer from "./GameRenderer.js"; import Enemy from "./objects/Enemy.js"; import Planet from "./objects/Planet.js"; var gameLoop, stage, planet, enemies, gazePoints, lastUpdate, lastEnemySpawn; function onTick() { let now = Date.now(), delta = now - lastUpdate; updateGazePoints(now); updateEnemies(now, delta); GameRenderer.render(getCurrentState(delta)); lastUpdate = Date.now(); } function getCurrentState(delta) { return { delta: delta, objects: [...enemies, planet], gazePoints: gazePoints, }; } function updateGazePoints(now) { for (let i = gazePoints.length - 1; i >= 0; i--) { let age = now - gazePoints[i].createdAt; if (age > GameConfig.getMaxGazePointAge()) { gazePoints.splice(i, 1); } else { gazePoints[i].relativeAge = age / GameConfig.getMaxGazePointAge(); } } } function updateEnemies(now, delta) { let currentGazePosition = gazePoints[gazePoints.length - 1]; if ((now - lastEnemySpawn) >= GameConfig.getEnemySpawnDelay()) { if (enemies.length < GameConfig.getMaxNumberOfEnemies()) { Logger.log("Add new enemy", "Game"); enemies.push(Enemy.createEnemy(GameConfig.getScreenWidth(), -50, planet.x, planet.y)); lastEnemySpawn = now; } } for (let i = enemies.length - 1; i >= 0; i--) { // Update enemy's position enemies[i].update(delta); // Check if enemy has hit target if (planet.isHitBy(enemies[i])) { Logger.log(`Enemy hit target for ${enemies[i].damage} dmg`, "Game"); // Reduce planet health after enemy has hit planet.health -= enemies[i].damage; if (planet.health <= 0) { onWorldDestroyed(); } // Remove enemy after it has hit target enemies.splice(i, 1); // Skip other checks if enemy has hit target // TODO: Add exposion at last position continue; } // Skip other checks if no gaze data is available if (currentGazePosition === undefined) { continue; } // Check if enemy was hit if (enemies[i].isHitBy({ x: currentGazePosition.targetX, y: currentGazePosition.targetY, })) { // Update enemy's health enemies[i].health -= GameConfig.getPlayerDamage(); // Remove enemy if destroyed if (enemies[i].health <= 0) { Logger.log(`Enemy destroyed by player`, "Game"); enemies.splice(i, 1); // TODO: Add exposion at last position } } } } function onWorldDestroyed() { Logger.log(`World destroyed [Current health ${planet.health}]`, "Game"); } class GameManager { init(canvasStage) { stage = canvasStage; enemies = []; gazePoints = []; planet = new Planet(GameConfig.getScreenWidth()/2, GameConfig.getScreenHeight()); lastEnemySpawn = 0; } start() { GameRenderer.init(stage); lastUpdate = Date.now(); gameLoop = setInterval(onTick, (Time.ONE_SECOND_IN_MS / GameConfig.getFPS())); } addGazePoint(point) { gazePoints.push(point); } } export default new GameManager();