var EventEmitter = require('events').EventEmitter; var util = require('util'); /** * * @constructor */ var Board = function() { this.cups = []; this.players = []; this.currentTurn = 0; this.ready = false; this.init(); }; Board.events = { PLAYER_CONNECTED: 'playerConnected', GAME_READY: 'gameReady', CUP_MARKED: 'cupMarked', CHANGE_TURN: 'changeTurn', WINNER: 'winner' }; util.inherits(Board, EventEmitter); /** * */ Board.prototype.init = function() { for (var i = 0; i <= 9; i++) { this.cups.push({}); } }; Board.prototype.disableAll = function() { this.cups.forEach(function(cup) { cup.active = false; }); }; Board.prototype.enableAll = function() { this.cups.forEach(function(cup) { cup.active = true; }); }; /** * * @param cupId */ Board.prototype.mark = function(cupId) { var cup = this.cups[cupId]; if (!cup) { return false; } if (this.ready && cup.active) { var player = this.players[this.currentTurn]; cup.value = player.label; cup.active = false; this.emit(Board.events.CUP_MARKED, {cupId: cupId, player: player}); var res = this.checkWinner(); if (res.win) { this.disableAll(); this.emit(Board.events.WINNER, {player: this.players[this.currentTurn]}); } else { this.currentTurn = (this.currentTurn + 1) % 2; this.emit(Board.events.CHANGE_TURN, this.players[this.currentTurn]); } } }; /** * * @param playerId * @returns {boolean} */ Board.prototype.checkTurn = function(playerId) { return this.players[this.currentTurn].id == playerId; }; /** * * @returns {{win: boolean, pos: Array}} */ Board.prototype.checkWinner = function() { var win = false; var counter=0; this.cups.forEach(function(cup) { if(cup.active == false) { counter++; } }); if(counter == 10) { win = true; } /* var winPosition = [ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ]; var player = this.players[this.currentTurn]; var pos = []; var win = winPosition.some(function(win) { if (this.cups[win[0]].textContent === player.label) { var res = this.cups[win[0]].textContent === this.cups[win[1]].textContent && this.cups[win[1]].textContent === this.cups[win[2]].textContent; if (res) { pos = win; return true; } } return false; }, this);*/ return { win: win }; }; /** * * @param player */ Board.prototype.addPlayer = function(player) { if (this.players.length < 2) { var isNew = this.players.filter(function(p) { return p.id == player.id; }).length === 0; if (isNew) { this.players.push(player); this.ready = this.players.length === 2; this.emit(Board.events.PLAYER_CONNECTED, player); if (this.ready) { this.enableAll(); this.emit(Board.events.GAME_READY, this.players[0]); } } } }; module.exports = Board;