summaryrefslogtreecommitdiff
path: root/src/api/stream
diff options
context:
space:
mode:
Diffstat (limited to 'src/api/stream')
-rw-r--r--src/api/stream/othello-game.ts91
1 files changed, 54 insertions, 37 deletions
diff --git a/src/api/stream/othello-game.ts b/src/api/stream/othello-game.ts
index 17cdd3a9e7..59d964777d 100644
--- a/src/api/stream/othello-game.ts
+++ b/src/api/stream/othello-game.ts
@@ -19,51 +19,68 @@ export default function(request: websocket.request, connection: websocket.connec
switch (msg.type) {
case 'set':
if (msg.pos == null) return;
- const pos = msg.pos;
+ set(msg.pos);
+ break;
+ }
+ });
- const game = await Game.findOne({ _id: gameId });
+ async function set(pos) {
+ const game = await Game.findOne({ _id: gameId });
- const o = new Othello();
+ if (game.is_ended) return;
- game.logs.forEach(log => {
- o.set(log.color, log.pos);
- });
+ const o = new Othello();
- const myColor = game.black_user_id.equals(user._id) ? 'black' : 'white';
- const opColor = myColor == 'black' ? 'white' : 'black';
+ game.logs.forEach(log => {
+ o.set(log.color, log.pos);
+ });
- if (!o.canReverse(myColor, pos)) return;
- o.set(myColor, pos);
+ const myColor = game.black_user_id.equals(user._id) ? 'black' : 'white';
+ const opColor = myColor == 'black' ? 'white' : 'black';
- let turn;
- if (o.getPattern(opColor).length > 0) {
- turn = myColor == 'black' ? game.white_user_id : game.black_user_id;
- } else {
- turn = myColor == 'black' ? game.black_user_id : game.white_user_id;
- }
+ if (!o.canReverse(myColor, pos)) return;
+ o.set(myColor, pos);
- const log = {
- at: new Date(),
- color: myColor,
- pos
- };
+ let turn;
+ if (o.getPattern(opColor).length > 0) {
+ turn = myColor == 'black' ? game.white_user_id : game.black_user_id;
+ } else if (o.getPattern(myColor).length > 0) {
+ turn = myColor == 'black' ? game.black_user_id : game.white_user_id;
+ } else {
+ turn = null;
+ }
- await Game.update({
- _id: gameId
- }, {
- $set: {
- turn_user_id: turn
- },
- $push: {
- logs: log
- }
- });
+ const isEnded = turn === null;
- publishOthelloGameStream(gameId, 'set', {
- color: myColor,
- pos
- });
- break;
+ let winner;
+ if (isEnded) {
+ const blackCount = o.board.filter(s => s == 'black').length;
+ const whiteCount = o.board.filter(s => s == 'white').length;
+ winner = blackCount == whiteCount ? null : blackCount > whiteCount ? game.black_user_id : game.white_user_id;
}
- });
+
+ const log = {
+ at: new Date(),
+ color: myColor,
+ pos
+ };
+
+ await Game.update({
+ _id: gameId
+ }, {
+ $set: {
+ turn_user_id: turn,
+ is_ended: isEnded,
+ winner_id: winner
+ },
+ $push: {
+ logs: log
+ }
+ });
+
+ publishOthelloGameStream(gameId, 'set', {
+ color: myColor,
+ pos
+ });
+ }
}