Commit d034852c by Alexander Bazo

Add global GameConfiguration

parent 0d39b6c7
var Config = {
GAZE_SERVER_URL: "ws://localhost:8001/gaze",
TARGET_FPS: 60,
SCREEN_WIDTH: screen.width,
SCREEN_HEIGHT: screen.height,
GAME_VERSION: "$VERSION",
};
Object.freeze(Config);
export default Config;
\ No newline at end of file
/* eslint-disable no-magic-numbers */
var version,
gazeServerURL,
fps,
fpsBufferLength,
screenWidth,
screenHeight,
maxGazePointAge,
gazePointRadius,
gazePointColor,
maxNumberOfEnemies,
enemySpawnDelay,
playerDamage,
worldBackgroundColor,
debugInfoPosition,
debugInfoFont,
debugInfoFonColor,
showDebugInfoOnScreen,
showVerboseDebugInfoInConsole,
useMouseInput;
class GameConfiguration {
constructor() {}
reset() {
version = "$VERSION";
gazeServerURL = "ws://localhost:8001/gaze";
fps = 60;
fpsBufferLength = 60;
screenWidth = screen.width;
screenHeight = screen.height;
maxGazePointAge = 500;
gazePointRadius = 15;
gazePointColor = "#4cd494";
maxNumberOfEnemies = 10;
enemySpawnDelay = 1000;
playerDamage = 15;
worldBackgroundColor = "#333";
debugInfoPosition = {
x: 10,
y: screenHeight - 10,
};
debugInfoFont = "16px ShareTech";
debugInfoFonColor = "#FFF";
}
setVersion(value) {
version = value;
}
getVersion() {
return version;
}
setGazeServerURL(value) {
gazeServerURL = value;
}
getGazeServerURL() {
return gazeServerURL;
}
setFPS(value) {
fps = value;
}
getFPS() {
return fps;
}
setFPSBufferLenght(value) {
fpsBufferLength = value;
}
getFPSBufferLenght() {
return fpsBufferLength;
}
setScreenWidth(value) {
screenWidth = value;
}
getScreenWidth() {
return screenWidth;
}
setScreenHeight(value) {
screenHeight = value;
}
getScreenHeight() {
return screenHeight;
}
setMaxGazePointAge(value) {
maxGazePointAge = value;
}
getMaxGazePointAge() {
return maxGazePointAge;
}
setGazePointRadius(value) {
gazePointRadius = value;
}
getGazePointRadius() {
return gazePointRadius;
}
setGazePointColor(value) {
gazePointColor = value;
}
getGazePointColor() {
return gazePointColor;
}
setMaxNumberOfEnemies(value) {
maxNumberOfEnemies = value;
}
getMaxNumberOfEnemies() {
return maxNumberOfEnemies;
}
setEnemySpawnDelay(value) {
enemySpawnDelay = value;
}
getEnemySpawnDelay() {
return enemySpawnDelay;
}
setPlayerDamage(value) {
playerDamage = value;
}
getPlayerDamage() {
return playerDamage;
}
setWorldBackgroundColor(value) {
worldBackgroundColor = value;
}
getWorldBackgroundColor() {
return worldBackgroundColor;
}
setDebugInfoPosition(value) {
debugInfoPosition = value;
}
getDebugInfoPosition() {
return debugInfoPosition;
}
setDebugInfoFont(value) {
debugInfoFont = value;
}
getDebugInfoFont() {
return debugInfoFont;
}
setDebugInfoFonColor(value) {
debugInfoFonColor = value;
}
getDebugInfoFonColor() {
return debugInfoFonColor;
}
setShowDebugInfoOnScreen(value) {
showDebugInfoOnScreen = value;
}
getShowDebugInfoOnScreen() {
return showDebugInfoOnScreen;
}
setShowVerboseDebugInfoInConsole(value) {
showVerboseDebugInfoInConsole = value;
}
getShowVerboseDebugInfoInConsole() {
return showVerboseDebugInfoInConsole;
}
setUseMouseInput(value) {
useMouseInput = value;
}
getUseMouseInput() {
return useMouseInput;
}
}
const Config = new GameConfiguration;
Config.reset();
export default Config;
\ No newline at end of file
var Config = {
MAX_GAZE_POINT_AGE: 500,
MAX_NUMBER_OF_ENEMIES: 10,
TARGET_RADIUS: 100,
DEFAULT_PLAYER_DAMAGE: 5,
ENEMEY_SPAWN_DELAY: 1000,
FPS_BUFFER_LENGTH: 50,
BACKGROUND_COLOR: "#333",
DEFAULT_GAZE_POINT_RADIUS: 15,
DEFAULT_GAZE_POINT_COLOR: "#4cd494",
DEBUG_POSITION_OFFSET: 10,
DEBUG_FONT: "16px ShareTech",
DEBUG_COLOR: "#ffffff",
};
Object.freeze(Config);
export default Config;
\ No newline at end of file
import GameConfig from "../config/GameConfiguration.js";
import Logger from "../utils/Logger.js"; import Logger from "../utils/Logger.js";
import Config from "./GameConfig.js";
import Time from "../utils/Time.js"; import Time from "../utils/Time.js";
import GameRenderer from "./GameRenderer.js"; import GameRenderer from "./GameRenderer.js";
import Enemy from "./objects/Enemy.js"; import Enemy from "./objects/Enemy.js";
import World from "./objects/World.js"; import Planet from "./objects/Planet.js";
var gameLoop, var gameLoop,
gameArea, stage,
lastUpdate, planet,
lastEnemySpawn,
options,
world,
enemies, enemies,
gazePoints; gazePoints,
lastUpdate,
lastEnemySpawn;
function onTick() { function onTick() {
let now = Date.now(), let now = Date.now(),
...@@ -26,31 +25,28 @@ function onTick() { ...@@ -26,31 +25,28 @@ function onTick() {
function getCurrentState(delta) { function getCurrentState(delta) {
return { return {
delta: delta, delta: delta,
frameRate: options.frameRate, objects: [...enemies, planet],
objects: [...enemies, world],
gazePoints: gazePoints, gazePoints: gazePoints,
debug: options.debug,
}; };
} }
function updateGazePoints(now) { function updateGazePoints(now) {
for (let i = gazePoints.length - 1; i >= 0; i--) { for (let i = gazePoints.length - 1; i >= 0; i--) {
let age = now - gazePoints[i].createdAt; let age = now - gazePoints[i].createdAt;
if (age > Config.MAX_GAZE_POINT_AGE) { if (age > GameConfig.getMaxGazePointAge()) {
gazePoints.splice(i, 1); gazePoints.splice(i, 1);
} else { } else {
gazePoints[i].relativeAge = age / Config.MAX_GAZE_POINT_AGE; gazePoints[i].relativeAge = age / GameConfig.getMaxGazePointAge();
} }
} }
} }
function updateEnemies(now, delta) { function updateEnemies(now, delta) {
let currentGazePosition = gazePoints[gazePoints.length - 1]; let currentGazePosition = gazePoints[gazePoints.length - 1];
if ((now - lastEnemySpawn) >= Config.ENEMEY_SPAWN_DELAY) { if ((now - lastEnemySpawn) >= GameConfig.getEnemySpawnDelay()) {
if (enemies.length < Config.MAX_NUMBER_OF_ENEMIES) { if (enemies.length < GameConfig.getMaxNumberOfEnemies()) {
Logger.log("Add new enemy", "Game"); Logger.log("Add new enemy", "Game");
enemies.push(Enemy.createEnemy(gameArea.width, -50, gameArea.center.x, enemies.push(Enemy.createEnemy(GameConfig.getScreenWidth(), -50, planet.x, planet.y));
gameArea.center.y));
lastEnemySpawn = now; lastEnemySpawn = now;
} }
} }
...@@ -58,11 +54,11 @@ function updateEnemies(now, delta) { ...@@ -58,11 +54,11 @@ function updateEnemies(now, delta) {
// Update enemy's position // Update enemy's position
enemies[i].update(delta); enemies[i].update(delta);
// Check if enemy has hit target // Check if enemy has hit target
if (world.isHitBy(enemies[i])) { if (planet.isHitBy(enemies[i])) {
Logger.log(`Enemy hit target for ${enemies[i].damage} dmg`, "Game"); Logger.log(`Enemy hit target for ${enemies[i].damage} dmg`, "Game");
// Reduce world health after enemy has hit // Reduce planet health after enemy has hit
world.health -= enemies[i].damage; planet.health -= enemies[i].damage;
if (world.health <= 0) { if (planet.health <= 0) {
onWorldDestroyed(); onWorldDestroyed();
} }
// Remove enemy after it has hit target // Remove enemy after it has hit target
...@@ -81,7 +77,7 @@ function updateEnemies(now, delta) { ...@@ -81,7 +77,7 @@ function updateEnemies(now, delta) {
y: currentGazePosition.targetY, y: currentGazePosition.targetY,
})) { })) {
// Update enemy's health // Update enemy's health
enemies[i].health -= Config.DEFAULT_PLAYER_DAMAGE; enemies[i].health -= GameConfig.getPlayerDamage();
// Remove enemy if destroyed // Remove enemy if destroyed
if (enemies[i].health <= 0) { if (enemies[i].health <= 0) {
Logger.log(`Enemy destroyed by player`, "Game"); Logger.log(`Enemy destroyed by player`, "Game");
...@@ -93,32 +89,23 @@ function updateEnemies(now, delta) { ...@@ -93,32 +89,23 @@ function updateEnemies(now, delta) {
} }
function onWorldDestroyed() { function onWorldDestroyed() {
Logger.log(`World destroyed [Current health ${world.health}]`, "Game"); Logger.log(`World destroyed [Current health ${planet.health}]`, "Game");
} }
class GameManager { class GameManager {
init(gameOptions) { init(canvasStage) {
options = gameOptions; stage = canvasStage;
gameArea = {
width: options.width,
height: options.height,
center: {
x: options.width / 2,
y: options.height / 2,
},
};
enemies = []; enemies = [];
gazePoints = []; gazePoints = [];
world = new World(gameArea.center.x, gameArea.center.y); planet = new Planet(GameConfig.getScreenWidth()/2, GameConfig.getScreenHeight());
lastEnemySpawn = 0; lastEnemySpawn = 0;
} }
start() { start() {
GameRenderer.init(stage);
GameRenderer.init(options.canvas, options.width, options.height, options.version);
lastUpdate = Date.now(); lastUpdate = Date.now();
gameLoop = setInterval(onTick, (Time.ONE_SECOND_IN_MS / options.frameRate)); gameLoop = setInterval(onTick, (Time.ONE_SECOND_IN_MS / GameConfig.getFPS()));
} }
addGazePoint(point) { addGazePoint(point) {
......
import Config from "./GameConfig.js"; import GameConfig from "../config/GameConfiguration.js";
import Time from "../utils/Time.js"; import Time from "../utils/Time.js";
var canvas, var canvas,
context, context,
gameVersion,
fpsBuffer, fpsBuffer,
currentFPS; currentFPS;
// TODO: Look for values to be copied and stored from GameConfig to reduce access time
function draw(state) { function draw(state) {
updateFPS(state.delta); updateFPS(state.delta);
context.clearRect(0, 0, canvas.width, canvas.height); context.clearRect(0, 0, canvas.width, canvas.height);
drawObjects(state.objects); drawObjects(state.objects);
drawGazePoints(state.gazePoints); drawGazePoints(state.gazePoints);
if (state.debug === true) { if (GameConfig.getShowDebugInfoOnScreen() === true) {
drawDebugInfo(); drawDebugInfo();
} }
} }
// Move fps callculation to manager since we need it there to use delta // TODO: Move fps callculation to manager since we need it there to use delta
function updateFPS(delta) { function updateFPS(delta) {
let fps = Time.ONE_SECOND_IN_MS / delta; let fps = Time.ONE_SECOND_IN_MS / delta;
fpsBuffer.push(fps); fpsBuffer.push(fps);
if (fpsBuffer.length === Config.FPS_BUFFER_LENGTH) { if (fpsBuffer.length === GameConfig.getFPSBufferLenght()) {
currentFPS = parseInt(fpsBuffer.reduce((a, b) => a + b, 0) / currentFPS = parseInt(fpsBuffer.reduce((a, b) => a + b, 0) /
fpsBuffer.length); fpsBuffer.length);
fpsBuffer.shift(); fpsBuffer.shift();
...@@ -35,7 +35,7 @@ function drawObjects(objects) { ...@@ -35,7 +35,7 @@ function drawObjects(objects) {
} }
function drawGazePoints(gazePoints) { function drawGazePoints(gazePoints) {
context.fillStyle = Config.DEFAULT_GAZE_POINT_COLOR; context.fillStyle = GameConfig.getGazePointColor();
for (let i = 0; i < gazePoints.length; i++) { for (let i = 0; i < gazePoints.length; i++) {
drawSingleGazePoint(gazePoints[i]); drawSingleGazePoint(gazePoints[i]);
} }
...@@ -43,7 +43,7 @@ function drawGazePoints(gazePoints) { ...@@ -43,7 +43,7 @@ function drawGazePoints(gazePoints) {
function drawSingleGazePoint(gazePoint) { function drawSingleGazePoint(gazePoint) {
let inversedAge = 1 - gazePoint.relativeAge, let inversedAge = 1 - gazePoint.relativeAge,
radius = inversedAge * Config.DEFAULT_GAZE_POINT_RADIUS; radius = inversedAge * GameConfig.getGazePointRadius();
context.save(); context.save();
context.globalAlpha = inversedAge; context.globalAlpha = inversedAge;
context.beginPath(); context.beginPath();
...@@ -56,26 +56,24 @@ function drawSingleGazePoint(gazePoint) { ...@@ -56,26 +56,24 @@ function drawSingleGazePoint(gazePoint) {
function drawDebugInfo() { function drawDebugInfo() {
context.beginPath(); context.beginPath();
context.font = Config.DEBUG_FONT; context.font = GameConfig.getDebugInfoFont();
context.fillStyle = Config.DEBUG_COLOR; context.fillStyle = GameConfig.getDebugInfoFonColor();
context.fillText(`${gameVersion} | ${currentFPS}fps`, Config.DEBUG_POSITION_OFFSET, context.fillText(`${GameConfig.getVersion()} | ${currentFPS}fps`, GameConfig.getDebugInfoPosition().x, GameConfig.getDebugInfoPosition().y);
canvas.height - Config.DEBUG_POSITION_OFFSET);
context.closePath(); context.closePath();
} }
class GameRenderer { class GameRenderer {
init(gameCanvas, width, height, version) { init(gameCanvas) {
fpsBuffer = []; fpsBuffer = [];
currentFPS = 0; currentFPS = 0;
gameVersion = version;
canvas = gameCanvas; canvas = gameCanvas;
canvas.width = width; canvas.width = GameConfig.getScreenWidth();
canvas.height = height; canvas.height = GameConfig.getScreenHeight();
canvas.style.width = `${width}px`; canvas.style.width = `${GameConfig.getScreenWidth()}px`;
canvas.style.height = `${height}px`; canvas.style.height = `${GameConfig.getScreenHeight()}px`;
context = canvas.getContext("2d", { alpha: false }); context = canvas.getContext("2d", { alpha: false });
canvas.style.backgroundColor = Config.BACKGROUND_COLOR; canvas.style.backgroundColor = GameConfig.getWorldBackgroundColor();
} }
render(state) { render(state) {
......
import Logger from "../utils/Logger.js"; import Logger from "../utils/Logger.js";
import GameManager from "./GameManager.js"; import GameManager from "./GameManager.js";
var canvas, provider; var stage, provider;
function init(options) { function init(options) {
Logger.log("Starting StarGazer game", "Game"); Logger.log("Starting StarGazer game", "Game");
canvas = options.canvas; stage = options.canvas;
GameManager.init({ GameManager.init(stage);
canvas: canvas,
frameRate: options.fps,
version: options.version,
debug: options.showDebug,
width: options.width,
height: options.height,
});
GameManager.start(); GameManager.start();
provider = options.gazeDataProvider; provider = options.gazeDataProvider;
provider.addEventListener("dataavailable", onGazeUpdate); provider.addEventListener("dataavailable", onGazeUpdate);
...@@ -21,7 +14,7 @@ function init(options) { ...@@ -21,7 +14,7 @@ function init(options) {
function onGazeUpdate(event) { function onGazeUpdate(event) {
let gazePoint = event.data; let gazePoint = event.data;
gazePoint.linkTo(canvas); gazePoint.linkTo(stage);
if (gazePoint.hasLink) { if (gazePoint.hasLink) {
GameManager.addGazePoint(gazePoint); GameManager.addGazePoint(gazePoint);
} }
......
import GameObject from "./GameObject.js"; import GameObject from "./GameObject.js";
const DEFAULT_HEALTH = 100, const DEFAULT_HEALTH = 100,
DEFAULT_WIDTH = 200, DEFAULT_WIDTH = 500,
DEFAULT_HEIGHT = 200, DEFAULT_HEIGHT = 500,
DEFAULT_HIT_BOX_RADIUS = 100, DEFAULT_HIT_BOX_RADIUS = 270,
DEFAULT_WORLD_COLOR = "#0d396f", DEFAULT_PLANET_COLOR = "#5bbe61",
DEFAULT_WORLD_BORDER_COLOR = "#dafffe", DEFAULT_PLANET_BORDER_COLOR = "#dafffe",
DEFAULT_WORLD_BORDER_WIDTH = "10"; DEFAULT_PLANET_BORDER_WIDTH = "20";
class World extends GameObject { class Planet extends GameObject {
constructor(x, y) { constructor(x, y) {
super(x, y, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_HIT_BOX_RADIUS, super(x, y, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_HIT_BOX_RADIUS,
0, 0, DEFAULT_WORLD_COLOR); 0, 0, DEFAULT_PLANET_COLOR);
this.health = DEFAULT_HEALTH; this.health = DEFAULT_HEALTH;
this.borderColor = DEFAULT_WORLD_BORDER_COLOR; this.borderColor = DEFAULT_PLANET_BORDER_COLOR;
this.borderWidth = DEFAULT_WORLD_BORDER_WIDTH; this.borderWidth = DEFAULT_PLANET_BORDER_WIDTH;
} }
draw(context) { draw(context) {
...@@ -34,4 +34,4 @@ class World extends GameObject { ...@@ -34,4 +34,4 @@ class World extends GameObject {
} }
export default World; export default Planet;
\ No newline at end of file \ No newline at end of file
import Config from "./Config.js"; import GameConfig from "./config/GameConfiguration.js";
import Logger from "./utils/Logger.js"; import Logger from "./utils/Logger.js";
import StarGazer from "./game/StarGazer.js"; import StarGazer from "./game/StarGazer.js";
import FakeGazeDataProvider from "./gaze/FakeGazeDataProvider.js"; import FakeGazeDataProvider from "./gaze/FakeGazeDataProvider.js";
import GazeDataProvider from "./gaze/GazeDataProvider.js"; import GazeDataProvider from "./gaze/GazeDataProvider.js";
var canvas = document.querySelector("canvas"), var canvas = document.querySelector("canvas"),
starScreen = document.querySelector("#startScreen"), starScreen = document.querySelector("#startScreen");
options = {
useMouse: false, // Defauls set in HTML document with checked attribute
showDebug: false, // Defauls set in HTML document with checked attribute
logToConsole: false, // Defauls set in HTML document with checked attribute
};
function init() { function init() {
loadOptions(); loadOptions();
if (options.logToConsole === true) { if (GameConfig.getShowVerboseDebugInfoInConsole() === true) {
Logger.enable(); Logger.enable();
} }
document.querySelector("#versionInfo").innerHTML = `build ${Config.GAME_VERSION}`; document.querySelector("#versionInfo").innerHTML =
`build ${GameConfig.getVersion()}`;
document.querySelector("#startButton").addEventListener("click", document.querySelector("#startButton").addEventListener("click",
prepareGame); prepareGame);
} }
function loadOptions() { function loadOptions() {
options.useMouse = document.querySelector("#useMouseInput").checked; let useMouse = document.querySelector("#useMouseInput").checked,
options.showDebug = document.querySelector("#showDebugInfo").checked; showDebug = document.querySelector("#showDebugInfo").checked,
options.logToConsole = document.querySelector("#logToConsole").checked; logToConsole = document.querySelector("#logToConsole").checked;
GameConfig.setUseMouseInput(useMouse);
GameConfig.setShowDebugInfoOnScreen(showDebug);
GameConfig.setShowVerboseDebugInfoInConsole(logToConsole);
} }
function prepareGame() { function prepareGame() {
loadOptions(); loadOptions();
StarGazer.init({ StarGazer.init({
canvas: canvas, canvas: canvas,
fps: Config.TARGET_FPS,
version: `Star Gazer, build ${Config.GAME_VERSION}`,
showDebug: options.showDebug,
width: Config.SCREEN_WIDTH,
height: Config.SCREEN_HEIGHT,
gazeDataProvider: getDataProvider(), gazeDataProvider: getDataProvider(),
}); });
canvas.requestFullscreen().then(startGame); canvas.requestFullscreen().then(startGame);
} }
function startGame() { function startGame() {
starScreen.classList.add("hidden"); starScreen.classList.add("hidden");
canvas.classList.remove("hidden"); canvas.classList.remove("hidden");
} }
function getDataProvider() { function getDataProvider() {
let provider; let provider;
if (options.useMouse === true) { if (GameConfig.getUseMouseInput() === true) {
provider = new FakeGazeDataProvider(); provider = new FakeGazeDataProvider();
} else { } else {
provider = new GazeDataProvider(); provider = new GazeDataProvider();
} }
provider.start(Config.GAZE_SERVER_URL); provider.start(GameConfig.getGazeServerURL());
return provider; return provider;
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment