UNPKG

2.63 kBJavaScriptView Raw
1const ChessWorker = require('./worker');
2
3module.exports = (gameSSBDao, myIdent) => {
4
5 const chessWorker = ChessWorker();
6
7 function makeMove(gameRootMessage, originSquare, destinationSquare, promoteTo) {
8 gameSSBDao.getSituation(gameRootMessage).then((situation) => {
9 if (situation.toMove === myIdent) {
10 const { pgnMoves } = situation;
11 chessWorker.postMessage({
12 topic: 'move',
13 payload: {
14 fen: situation.fen,
15 pgnMoves,
16 orig: originSquare,
17 dest: destinationSquare,
18 promotion: promoteTo,
19 },
20 reqid: {
21 gameRootMessage,
22 originSquare,
23 destinationSquare,
24 players: situation.players,
25 respondsTo: situation.latestUpdateMsg,
26 coloursToPlayer: situation.coloursToPlayer()
27 },
28
29 });
30 }
31 });
32 }
33
34 function resignGame(gameId, respondsTo) {
35 return gameSSBDao.resignGame(gameId, respondsTo);
36 }
37
38 function handleChessWorkerResponse(e) {
39 // This is a hack. Reqid is meant to be used for a string to identity
40 // which request the response game from.
41 const { gameRootMessage, originSquare, destinationSquare, coloursToPlayer } = e.data.reqid;
42 const { respondsTo } = e.data.reqid;
43
44 if (e.data.payload.error) {
45 // Todo: work out how to communicate this to the user.
46 // This shouldn't happen though... (eh, famous last words, I guess.)
47 throw new Error('Move error: ', e);
48 } else if (e.data.topic === 'move' && e.data.payload.situation.end) {
49 const {
50 status,
51 winner,
52 ply,
53 fen,
54 } = e.data.payload.situation;
55
56 const pgnMove = ply > 0
57 ? e.data.payload.situation.pgnMoves[e.data.payload.situation.pgnMoves.length - 1]
58 : null;
59
60 const winnerId = winner ? coloursToPlayer[winner].id : null;
61
62 gameSSBDao.endGame(
63 gameRootMessage,
64 status.name,
65 winnerId,
66 fen,
67 ply,
68 originSquare,
69 destinationSquare,
70 pgnMove,
71 respondsTo,
72 );
73 } else if (e.data.topic === 'move') {
74 gameSSBDao.makeMove(
75 gameRootMessage,
76 e.data.payload.situation.ply,
77 originSquare,
78 destinationSquare,
79 e.data.payload.situation.promotion,
80 e.data.payload.situation.pgnMoves[e.data.payload.situation.pgnMoves.length - 1],
81 e.data.payload.situation.fen,
82 respondsTo,
83 );
84 }
85 }
86
87 chessWorker.addEventListener('message', handleChessWorkerResponse);
88
89 return {
90 makeMove,
91 resignGame,
92 };
93};