import Logger from "../utils/Logger.js"; import Config from "./GameConfig.js"; import Time from "../utils/Time.js"; import GameRenderer from "./GameRenderer.js"; import Enemy from "./objects/Enemy.js"; import World from "./objects/World.js"; var gameLoop, gameArea, lastUpdate, lastEnemySpawn, options, world, enemies, gazePoints; 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, frameRate: options.frameRate, objects: [...enemies, world], gazePoints: gazePoints, debug: options.debug, }; } function updateGazePoints(now) { for (let i = gazePoints.length - 1; i >= 0; i--) { let age = now - gazePoints[i].createdAt; if (age > Config.MAX_GAZE_POINT_AGE) { gazePoints.splice(i, 1); } else { gazePoints[i].relativeAge = age / Config.MAX_GAZE_POINT_AGE; } } } function updateEnemies(now, delta) { let currentGazePosition = gazePoints[gazePoints.length - 1]; if ((now - lastEnemySpawn) >= Config.ENEMEY_SPAWN_DELAY) { if (enemies.length < Config.MAX_NUMBER_OF_ENEMIES) { Logger.log("Add new enemy", "Game"); enemies.push(Enemy.createEnemy(gameArea.width, -50, gameArea.center.x, gameArea.center.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 (world.isHitBy(enemies[i])) { Logger.log(`Enemy hit target for ${enemies[i].damage} dmg`, "Game"); // Reduce world health after enemy has hit world.health -= enemies[i].damage; if (world.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 -= Config.DEFAULT_PLAYER_DAMAGE; // 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 ${world.health}]`, "Game"); } class GameManager { init(gameOptions) { options = gameOptions; gameArea = { width: options.width, height: options.height, center: { x: options.width / 2, y: options.height / 2, }, }; enemies = []; gazePoints = []; world = new World(gameArea.center.x, gameArea.center.y); lastEnemySpawn = 0; } start() { GameRenderer.init(options.canvas, options.width, options.height, options.version); lastUpdate = Date.now(); gameLoop = setInterval(onTick, (Time.ONE_SECOND_IN_MS / options.frameRate)); } addGazePoint(point) { gazePoints.push(point); } } export default new GameManager();