diff --git a/model/gameModel.js b/model/gameModel.js index 53db5c8..925776b 100644 --- a/model/gameModel.js +++ b/model/gameModel.js @@ -5,8 +5,9 @@ var schema = new mongoose.Schema( user0: mongoose.Schema.Types.Mixed, user1: mongoose.Schema.Types.Mixed, caseArray: [mongoose.Schema.Types.Mixed], - currentPlayer: Number - + currentPlayer: Number, + wonBy: Number, + wonColor: String, } ); @@ -28,7 +29,48 @@ schema.methods.initGame = function(user0, user1) { } }; +schema.methods.checkWinners = function() { + let map = {}; + + for (var i = 0; i < this.caseArray.length; i++) { + + const currentCase = this.caseArray[i]; + const currentCasePosition = currentCase.caseName.replace('case', ''); + + const currentPosX = currentCasePosition[0]; + const currentPosY = currentCasePosition[1]; + if (!map[currentPosX]) { + map[currentPosX] = {}; + } + map[currentPosX][currentPosY] = currentCase.userId; + } + for (var key in map) { + const currentLine = map[key]; + console.log(currentLine); + if (Object.keys(currentLine).length !== 3) { + continue; + } + let lastPlayerCase = null; + let totalSuccess = 0; + console.log(currentLine); + for (var keyLine in currentLine) { + if (lastPlayerCase && lastPlayerCase !== currentLine[keyLine]) { + continue; + } + lastPlayerCase = currentLine[keyLine]; + totalSuccess++; + } + if (totalSuccess === 3) { + return lastPlayerCase; + } + } + return null; +} + schema.methods.gameAction = function(userId, caseName) { + if (this.wonBy) { + return; + } if (userId === parseInt(this.currentPlayer)) { if (!this.caseArray) { this.caseArray = []; @@ -42,6 +84,10 @@ schema.methods.gameAction = function(userId, caseName) { caseName: caseName, userId: userId }); + this.wonBy = this.checkWinners(); + if (this.wonBy) { + this.wonColor = this.wonBy === this.user0.id ? this.user0.color : this.user1.color; + } if (this.currentPlayer) { if (parseInt(this.currentPlayer) === this.user0.id) { this.currentPlayer = this.user1.id; diff --git a/routes/index.js b/routes/index.js index 1c04869..59a7bd0 100644 --- a/routes/index.js +++ b/routes/index.js @@ -1,9 +1,44 @@ var express = require('express'); var router = express.Router(); +var Game = require('./../model/gameModel'); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Formation Node', h1 : "Node JS && WebSocket" }); }); +router.get('/games', function(req, res, next) { + const total = Game.find().limit(10); + total.exec((err, game) => { + if (err) { + res.end("error"); + return; + } + res.send(game); + }); +}); + + +router.get('/total', function(req, res, next) { + const count = Game.aggregate([ + {"$match": { + "wonColor": { + "$eq": "red" + } + }} + ,{ + "$count": "wonColor" + }]); + count.exec((err, game) => { + console.log(game); + if (err) { + res.end("error"); + return; + } + res.send(game); + }); +}); + + + module.exports = router;