diff options
Major Game Mechanics implementation
12 files changed, 490 insertions, 130 deletions
| -rw-r--r-- | scripts/app.js | 18 | ||||
| -rw-r--r-- | scripts/core/config.js | 10 | ||||
| -rw-r--r-- | scripts/core/game.js | 261 | ||||
| -rw-r--r-- | scripts/core/home.js | 8 | ||||
| -rw-r--r-- | scripts/game-chat.js | 49 | ||||
| -rw-r--r-- | scripts/gameObjects/baseGameObject.js | 29 | ||||
| -rw-r--r-- | scripts/gameObjects/tank.js | 55 | ||||
| -rw-r--r-- | scripts/gameObjects/tankShell.js | 32 | ||||
| -rw-r--r-- | scripts/services/eventService.js | 19 | ||||
| -rw-r--r-- | scripts/services/socketService.js | 96 | ||||
| -rw-r--r-- | scripts/services/userService.js | 2 | ||||
| -rw-r--r-- | scripts/utility/shellContainer.js | 41 |
diff --git a/scripts/app.js b/scripts/app.js index 2406bb9..93b999a 100644 --- a/scripts/app.js +++ b/scripts/app.js @@ -1,5 +1,20 @@ var app = app || {}; +const gameEvents = (() => { + app.eventService.addEventHandler('GameEnd', (result) => { + if(result) { + const message = result.result; + const user = 'PUSG'; + + app.socketService.send('home', 'SendMessage', user, message); + } + + app.Game.reset(); + app.socketService.disconnectGame(); + window.location.hash = '#/home'; + }); +})(); + const handleRouting = () => { const path = window.location.hash.substr(window.location.hash.indexOf('#') + 1); @@ -11,7 +26,7 @@ const handleRouting = () => { app.htmlService.clearElement('#app'); app.htmlService.attachElement(compliedTemplate, '#app'); - app.Game.init(); + app.socketService.initHome(); app.Home.init(); }); @@ -24,6 +39,7 @@ const handleRouting = () => { app.htmlService.attachElement(compliedTemplate, '#app'); app.Game.init(); + app.Game.load(app.config.USER.COLOR); }); break; diff --git a/scripts/core/config.js b/scripts/core/config.js new file mode 100644 index 0000000..4f06f7b --- /dev/null +++ b/scripts/core/config.js @@ -0,0 +1,10 @@ +var app = app || {}; + +const config = (function () { + return { + SERVICE_URL: 'https://localhost:44385', + USER: {}, + }; +}()); + +app.config = config; diff --git a/scripts/core/game.js b/scripts/core/game.js index 2d846e9..6d0646c 100644 --- a/scripts/core/game.js +++ b/scripts/core/game.js @@ -2,12 +2,17 @@ var app = app || {}; class Game { constructor() { + this.isLoaded = false; + this.playerColor = null; this.appStage = null; this.pixiApplication = null; - this.gameObjects = []; + this.isRunning = false; + this.gameObjects = []; // TODO: Make into player container + this.shells = new ShellContainer(); this.config = { sprites: {}, sounds: {}, + state: {}, }; } @@ -37,40 +42,211 @@ class Game { this.config.sprites["giga-tank-red"] = new PIXI.Sprite(PIXI.loader.resources["images/giga-tank-red.png"].texture); this.config.sprites["laser-tank-red"] = new PIXI.Sprite(PIXI.loader.resources["images/laser-tank-red.png"].texture); this.config.sprites["basic-tank-red"] = new PIXI.Sprite(PIXI.loader.resources["images/basic-tank-red.png"].texture); - this.config.sprites["shell"] = new PIXI.Sprite(PIXI.loader.resources["images/shell.png"].texture); + this.config.sprites["shell"] = () => new PIXI.Sprite(PIXI.loader.resources["images/shell.png"].texture); - // Giga Tank - this.config.sprites["giga-tank-blue"].width = 100; - this.config.sprites["giga-tank-blue"].height = 80; - this.config.sprites["giga-tank-red"].width = 100; - this.config.sprites["giga-tank-red"].height = 80; + callback(); + }); + } - // Laser Tank - this.config.sprites["laser-tank-blue"].width = 75; - this.config.sprites["laser-tank-blue"].height = 60; - this.config.sprites["laser-tank-red"].width = 75; - this.config.sprites["laser-tank-red"].height = 60; + getCurrentPlayerTank() { + return this.gameObjects + .filter(go => go instanceof Tank) + .find(go => go.color === this.playerColor); + } - // Basic Tank - this.config.sprites["basic-tank-blue"].width = 50; - this.config.sprites["basic-tank-blue"].height = 40; - this.config.sprites["basic-tank-red"].width = 50; - this.config.sprites["basic-tank-red"].height = 40; + getOtherPlayerTank() { + return this.gameObjects + .filter(go => go instanceof Tank) + .find(go => go.color !== this.playerColor); + } - // Shells - this.config.sprites["shell"].width = 25; - this.config.sprites["shell"].height = 25; + dispatch(command) { + const currentPlayerTank = this.getCurrentPlayerTank(); + let result = false; - callback(); - }); + switch (command) { + case "left": { + result = true; + break; + } + case "up": { + result = true; + break; + } + case "right": { + result = true; + break; + } + case "down": { + result = true; + break; + } + case "rotate-left": { + currentPlayerTank.rotateLeft(); + result = true; + break; + } + case "rotate-right": { + currentPlayerTank.rotateRight(); + result = true; + break; + } + case "pew": { + this.config.sounds.pew.play(); + result = true; + break; + } + default: + alert('Invalid command!') + } + + if (result) { + app.socketService.send('game', 'Update', command); + } + + return result; + } + + updateShells() { + this.shells.each(shell => { + if (!this.config.state.shells?.some(stateShell => stateShell.id === shell.id)) { + shell.isDestroyed = true; + } + }); + + this.config.state.shells?.forEach(stateShell => { + if (!this.shells.contains(stateShell.id)) { + const shell = new TankShell( + stateShell.id, + this.config.sprites["shell"].call(), + {width: 25, height: 25}, + {x: stateShell.x, y: stateShell.y}, + stateShell.direction, + ); + + this.shells.add(shell); + } else { + const currentShell = this.shells.get(stateShell.id); + currentShell.x = stateShell.x; + currentShell.y = stateShell.y; + } + }); + + this.shells.update(); + } + + updatePlayers() { + const currentTank = this.getCurrentPlayerTank(); + const otherTank = this.getOtherPlayerTank(); + if(currentTank && otherTank && this.playerColor === 'blue') { + currentTank.x = this.config.state.blue.x; + currentTank.y = this.config.state.blue.y; + otherTank.x = this.config.state.red.x; + otherTank.y = this.config.state.red.y; + } else if(currentTank && otherTank && this.playerColor === 'red') { + currentTank.x = this.config.state.red.x; + currentTank.y = this.config.state.red.y; + otherTank.x = this.config.state.blue.x; + otherTank.y = this.config.state.blue.y; + } } update() { - // this.gameObjects.forEach(gameObject => gameObject.update()); + app.socketService.send('game', 'GetState'); + + this.updateShells(); + this.updatePlayers(); + + this.gameObjects.forEach(gameObject => gameObject.update()); } draw() { - // this.gameObjects.forEach(gameObject => gameObject.draw()); + this.gameObjects.forEach(gameObject => this.pixiApplication.stage.addChild(gameObject.draw())); + this.shells.each(shell => this.pixiApplication.stage.addChild(shell.draw())); + } + + initGameObjects() { + const bluePlayer = new Tank( + 'blue', + 'basic', + this.config.sprites['basic-tank-blue'], + { + width: 50, + height: 40 + }, + { + x: 50, + y: 384 + }, + 'right'); + + const redPlayer = new Tank( + 'red', + 'basic', + this.config.sprites['basic-tank-red'], + { + width: 50, + height: 40 + }, + { + x: 1266, + y: 384 + }, + 'left'); + + this.gameObjects.push(bluePlayer); + this.gameObjects.push(redPlayer); + }; + + initEvents() { + app.eventService.addEventHandler('OtherUp', () => { + this.getOtherPlayerTank().moveUp(); + }); + + app.eventService.addEventHandler('OtherRight', () => { + this.getOtherPlayerTank().moveRight(); + }); + + app.eventService.addEventHandler('OtherDown', () => { + this.getOtherPlayerTank().moveDown(); + }); + + app.eventService.addEventHandler('OtherLeft', () => { + this.getOtherPlayerTank().moveLeft(); + }); + + app.eventService.addEventHandler('OtherRotateLeft', () => { + this.getOtherPlayerTank().rotateLeft(); + }); + + app.eventService.addEventHandler('OtherRotateRight', () => { + this.getOtherPlayerTank().rotateRight(); + }); + + app.eventService.addEventHandler('GameState', (state) => { + this.config.state = state; + }); + } + + gameLoop() { + if (this.isRunning) { + setTimeout(() => { + }, 17); + requestAnimationFrame(() => this.update()); + requestAnimationFrame(() => this.draw()); + requestAnimationFrame(() => this.gameLoop()); + } + } + + loadResources(callback) { + if (!this.isLoaded) { + this.isLoaded = true; + this.loadSounds(() => { + }); + this.loadSprites(callback); + } else { + callback(); + } } init() { @@ -91,17 +267,42 @@ class Game { this.pixiApplication = new PIXI.Application(appOptions); this.pixiApplication.renderer.autoResize = true; - this.loadSounds(() => {}); - this.loadSprites(this.draw); - - this.pixiApplication.ticker.add((delta) => { - this.update(); + this.loadResources(() => { + this.initGameObjects(); + this.draw(); }); + + this.initEvents(); + this.isRunning = true; + this.gameLoop(); } - load() { + reset() { + this.appStage.innerHTML = ''; + this.playerColor = null; + this.appStage = null; + this.pixiApplication = null; + this.isRunning = false; + this.gameObjects = []; // TODO: Make into player container + this.shells = new ShellContainer(); + this.config.state = {}; + } + + // -> move to init + load(playerColor) { + this.playerColor = playerColor; this.appStage = app.htmlService.getElement('.app-stage'); this.appStage.appendChild(this.pixiApplication.view); + + app.htmlService.addEventHandler('#chat', 'keyup', (e) => { + if (e.key === 'Enter' || e.keyCode === 13) { + const command = e.target.value; + + if (this.dispatch(command)) { + e.target.value = ""; + } + } + }); } } diff --git a/scripts/core/home.js b/scripts/core/home.js index 625d3ad..b9c4ea8 100644 --- a/scripts/core/home.js +++ b/scripts/core/home.js @@ -2,7 +2,11 @@ var app = app || {}; const supportedCommands = { '-play': { - invoke: () => {}, + invoke: () => { + app.socketService.initGame().finally(() => { + app.socketService.send('game', 'Login', app.userService.user); + }); + }, help: 'Initiate matchmaking to find an opponent and play the game.', }, '-help': { @@ -55,7 +59,7 @@ class Home { if(this.isCommand(message)) { this.dispatch(message); } else { - app.socketService.send('SendMessage', app.userService.user, message); + app.socketService.send('home', 'SendMessage', app.userService.user, message); } } } diff --git a/scripts/game-chat.js b/scripts/game-chat.js deleted file mode 100644 index c9ab957..0000000 --- a/scripts/game-chat.js +++ /dev/null @@ -1,49 +0,0 @@ -var app = app || {}; - -function dispatch(command) { - switch(command) { - case "left": { - app.config.sprites['basic-tank-blue'].x -= 20; - return true; - } - case "up": { - app.config.sprites['basic-tank-blue'].y -= 20; - return true; - } - case "right": { - app.config.sprites['basic-tank-blue'].x += 20; - return true; - } - case "down": { - app.config.sprites['basic-tank-blue'].y += 20; - return true; - } - case "rotate-left": { - app.config.sprites['basic-tank-blue'].rotation -= 0.5; - app.config.sprites['basic-tank-blue'].rotation -= 0.5; - return true; - } - case "rotate-right": { - app.config.sprites['basic-tank-blue'].rotation += 0.75; - app.config.sprites['basic-tank-blue'].rotation += 0.75; - return true; - } - case "pew": { - app.config.sounds.pew.play(); - return true; - } - default: alert('Invalid command!') - } - - return false; -} - -htmlService.addEventHandler('#chat', 'keyup', function (e) { - if (e.key === 'Enter' || e.keyCode === 13) { - const command = e.target.value; - - if(dispatch(command)) { - e.target.value = ""; - } - } -}); diff --git a/scripts/gameObjects/baseGameObject.js b/scripts/gameObjects/baseGameObject.js new file mode 100644 index 0000000..91ec11f --- /dev/null +++ b/scripts/gameObjects/baseGameObject.js @@ -0,0 +1,29 @@ +var app = app || {}; + +class BaseGameObject { + constructor(id, sprite, size, position) { + this.id = id; + this.sprite = sprite; + this.container = new PIXI.Container(); + this.sprite.width = size.width; + this.sprite.height = size.height; + this.container.width = size.width; + this.container.height = size.height; + this.container.x = position.x; + this.container.y = position.y; + this.container.addChild(this.sprite); + this.container.pivot.x = this.container.width / 2; + this.container.pivot.y = this.container.height / 2; + } + + update() {} + + draw() { + return this.container; + } + + destroy() { + this.container.parent.removeChild(this.container); + this.container.destroy({children: false, texture: false, baseTexture: false}); + } +} diff --git a/scripts/gameObjects/tank.js b/scripts/gameObjects/tank.js index 2cd3b1c..7469ba1 100644 --- a/scripts/gameObjects/tank.js +++ b/scripts/gameObjects/tank.js @@ -1,18 +1,57 @@ var app = app || {}; -class Tank { - constructor(color, type, sprite, position, direction) { +const DIRECTION_STATE = { + 'up': { + next: 'right', + previous: 'left', + }, + 'right': { + next: 'down', + previous: 'up', + }, + 'down': { + next: 'left', + previous: 'right', + }, + 'left': { + next: 'up', + previous: 'down', + }, +}; + +class Tank extends BaseGameObject { + constructor(color, type, sprite, size, position, direction) { + super(null, sprite, size, position); this.color = color; this.type = type; - this.sprite = sprite; - this.sprite.x = position.x; - this.sprite.y = position.y; this.direction = direction; } - update() { } + get x (){ + return this.container.x; + } + + get y (){ + return this.container.y; + } + + set x (value) { + this.container.x = value; + } + + set y (value) { + this.container.y = value; + } + + rotateLeft() { + this.direction = DIRECTION_STATE[this.direction].previous; + + this.container.rotation -= 1.57079633; + } + + rotateRight() { + this.direction = DIRECTION_STATE[this.direction].next; - draw() { - app.pixiApplication.stage.addChild(this.sprite); + this.container.rotation += 1.57079633; } } diff --git a/scripts/gameObjects/tankShell.js b/scripts/gameObjects/tankShell.js index 5f87143..1fffa23 100644 --- a/scripts/gameObjects/tankShell.js +++ b/scripts/gameObjects/tankShell.js @@ -1,31 +1,19 @@ var app = app || {}; -class TankShell { - constructor(sprite, position, direction) { - this.sprite = sprite; - this.sprite.x = position.x; - this.sprite.y = position.y; +class TankShell extends BaseGameObject { + constructor(id, sprite, size, position, direction) { + super(id, sprite, size, position); this.direction = direction; + this.isDestroyed = false; } - update() { - switch(this.direction) { - case "up": - this.sprite.y--; - break; - case "right": - this.sprite.x++; - break; - case "down": - this.sprite.y++; - break; - case "left": - this.sprite.x--; - break; - } + set x (value) { + this.container.x = value; } - draw() { - app.pixiApplication.stage.addChild(this.sprite); + set y (value) { + this.container.y = value; } + + update() {} } diff --git a/scripts/services/eventService.js b/scripts/services/eventService.js new file mode 100644 index 0000000..7a15903 --- /dev/null +++ b/scripts/services/eventService.js @@ -0,0 +1,19 @@ +var app = app || {}; + +class EventService { + constructor() { + this.events = {}; + } + + addEventHandler(event, handler) { + this.events[event] = handler; + } + + triggerEvent(event, args) { + if(this.events[event]) { + this.events[event].call(null, args); + } + } +} + +app.eventService = new EventService(); diff --git a/scripts/services/socketService.js b/scripts/services/socketService.js index 4c328d7..89bbd45 100644 --- a/scripts/services/socketService.js +++ b/scripts/services/socketService.js @@ -2,22 +2,83 @@ var app = app || {}; class SocketService { constructor() { - this.connection = null; - this.init(); + this.homeConnection = null; + this.gameConnection = null; } - async initConnection() { - this.connection = await new signalR.HubConnectionBuilder() - .withUrl("https://pusg-api.herokuapp.com/home") + async initGameConnection() { + this.gameConnection = await new signalR.HubConnectionBuilder() + .withUrl(`${app.config.SERVICE_URL}/game`) .build(); } - initReceivers() { - this.connection.on('OnConnected', ([message]) => { + disconnectGame() { + this.gameConnection.stop(); + this.gameConnection = null; + } + + initGameReceivers() { + this.gameConnection.on('OnConnected', ([message]) => { + console.log(message); + }); + + this.gameConnection.on('StartGame', ([color]) => { + window.location.hash = '#/play'; + app.config.USER.COLOR = color; + }); + + this.gameConnection.on('OtherUp', () => { + app.eventService.triggerEvent('OtherUp'); + }); + + this.gameConnection.on('OtherRight', () => { + app.eventService.triggerEvent('OtherRight'); + }); + + this.gameConnection.on('OtherDown', () => { + app.eventService.triggerEvent('OtherDown'); + }); + + this.gameConnection.on('OtherLeft', () => { + app.eventService.triggerEvent('OtherLeft'); + }); + + this.gameConnection.on('OtherRotateLeft', () => { + app.eventService.triggerEvent('OtherRotateLeft'); + }); + + this.gameConnection.on('OtherRotateRight', () => { + app.eventService.triggerEvent('OtherRotateRight'); + }); + + this.gameConnection.on('GameState', (state) => { + app.eventService.triggerEvent('GameState', state); + }); + + this.gameConnection.on('GameEnd', (result) => { + app.eventService.triggerEvent('GameEnd', result); + }); + } + + initGame() { + return this.initGameConnection().then(() => { + this.initGameReceivers(); + return this.start(this.gameConnection); + }); + } + + async initHomeConnection() { + this.homeConnection = await new signalR.HubConnectionBuilder() + .withUrl(`${app.config.SERVICE_URL}/home`) + .build(); + } + + initHomeReceivers() { + this.homeConnection.on('OnConnected', ([message]) => { console.log(message); }); - this.connection.on('ReceiveMessage', ([user, message]) => { + this.homeConnection.on('ReceiveMessage', ([user, message]) => { const messageNode = app.htmlService .getElementFromTemplate('message', { user: user, @@ -29,27 +90,28 @@ class SocketService { }); } - init() { - this.initConnection().then(() => { - this.initReceivers(); - this.start(); + initHome() { + return this.initHomeConnection().then(() => { + this.initHomeReceivers(); + return this.start(this.homeConnection); }); } - start() { + start(connection) { const starting = async () => { try { - await this.connection.start(); + await connection.start(); } catch (e) { console.log(e); } }; - starting().then(() => {}); + return starting().then(() => {}); } - send(method, ...args) { - this.connection.invoke(method, ...args); + send(location, method, ...args) { + if(location === 'home') this.homeConnection.invoke(method, ...args); + if(location === 'game') this.gameConnection.invoke(method, ...args); } } diff --git a/scripts/services/userService.js b/scripts/services/userService.js index 103e156..03bb313 100644 --- a/scripts/services/userService.js +++ b/scripts/services/userService.js @@ -10,7 +10,7 @@ class UserService { const username = prompt('Please, enter a Username:'); if (username) { - app.socketService.send('Login', username); + app.socketService.send('home', 'Login', username); this.user = username; } } diff --git a/scripts/utility/shellContainer.js b/scripts/utility/shellContainer.js new file mode 100644 index 0000000..9153a90 --- /dev/null +++ b/scripts/utility/shellContainer.js @@ -0,0 +1,41 @@ +var app = app || {}; + +class ShellContainer { + constructor() { + this.shells = []; + } + + add(shell) { + this.shells.push(shell); + } + + remove(id) { + this.shells.remove(this.shells.find(shell => shell.id === id)); + } + + contains(id) { + return !!this.shells.find(shell => shell.id === id); + } + + get(id) { + return this.shells.find(shell => shell.id === id); + } + + each(action) { + this.shells.forEach(shell => action(shell)); + } + + find(predicate) { + return this.shells.find(predicate); + } + + update() { + this.each(shell => { + if(shell.isDestroyed) { + shell.destroy(); + } + }); + this.shells = this.shells.filter(shell => !shell.isDestroyed); + this.each(shell => shell.update()); + } +} |