/
socket.ts
177 lines (164 loc) · 5.31 KB
/
socket.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import * as game from 'game';
import throttle from 'common/throttle';
import * as xhr from './xhr';
import RoundController from './ctrl';
import { defined } from 'common';
export interface RoundSocket {
send: SocketSend;
handlers: SocketHandlers;
moreTime(): void;
outoftime(): void;
berserk(): void;
sendLoading(typ: string, data?: any): void;
receive(typ: string, data: any): boolean;
reload(o?: Incoming, isRetry?: boolean): void;
}
interface Incoming {
t: string;
d: any;
}
type Callback = (...args: any[]) => void;
function backoff(delay: number, factor: number, callback: Callback): Callback {
let timer: number | undefined;
let lastExec = 0;
return function (this: any, ...args: any[]): void {
const self: any = this;
const elapsed = performance.now() - lastExec;
const exec = () => {
timer = undefined;
lastExec = performance.now();
delay *= factor;
callback.apply(self, args);
};
if (timer) clearTimeout(timer);
if (elapsed > delay) exec();
else timer = setTimeout(exec, delay - elapsed);
};
}
export function make(send: SocketSend, ctrl: RoundController): RoundSocket {
site.socket.sign(ctrl.sign);
const reload = (o?: Incoming, isRetry?: boolean) => {
// avoid reload if possible!
if (o && o.t) {
ctrl.setLoading(false);
handlers[o.t]!(o.d);
} else
xhr.reload(ctrl).then(data => {
if (site.socket.getVersion() > data.player.version) {
// race condition! try to reload again
if (isRetry) site.reload();
// give up and reload the page
else reload(o, true);
} else ctrl.reload(data);
}, site.reload);
};
const handlers: SocketHandlers = {
takebackOffers(o: { white?: boolean; black?: boolean }) {
ctrl.data.player.proposingTakeback = o[ctrl.data.player.color];
const fromOp = (ctrl.data.opponent.proposingTakeback = o[ctrl.data.opponent.color]);
if (fromOp) ctrl.opponentRequest('takeback', 'yourOpponentProposesATakeback');
ctrl.redraw();
},
move: ctrl.apiMove,
drop: ctrl.apiMove,
reload,
redirect: ctrl.setRedirecting,
clockInc(o: { color: Color; time: number }) {
if (ctrl.clock) {
ctrl.clock.addTime(o.color, o.time);
ctrl.redraw();
}
},
cclock(o: { white: number; black: number }) {
if (ctrl.corresClock) {
ctrl.data.correspondence.white = o.white;
ctrl.data.correspondence.black = o.black;
ctrl.corresClock.update(o.white, o.black);
ctrl.redraw();
}
},
crowd(o: { white: boolean; black: boolean }) {
(['white', 'black'] as const).forEach(c => {
if (defined(o[c])) game.setOnGame(ctrl.data, c, o[c]);
});
ctrl.redraw();
},
endData: ctrl.endWithData,
rematchOffer(by: Color) {
ctrl.data.player.offeringRematch = by === ctrl.data.player.color;
if ((ctrl.data.opponent.offeringRematch = by === ctrl.data.opponent.color))
ctrl.opponentRequest('rematch', 'yourOpponentWantsToPlayANewGameWithYou');
ctrl.redraw();
},
rematchTaken(nextId: string) {
ctrl.data.game.rematch = nextId;
if (!ctrl.data.player.spectator) ctrl.setLoading(true);
else ctrl.redraw();
},
drawOffer(by?: Color) {
if (ctrl.isPlaying()) {
ctrl.data.player.offeringDraw = by === ctrl.data.player.color;
const fromOp = (ctrl.data.opponent.offeringDraw = by === ctrl.data.opponent.color);
if (fromOp) ctrl.opponentRequest('draw', 'yourOpponentOffersADraw');
}
if (by) {
let ply = ctrl.lastPly();
if ((by == 'white') == (ply % 2 == 0)) ply++;
ctrl.data.game.drawOffers = (ctrl.data.game.drawOffers || []).concat([ply]);
}
ctrl.redraw();
},
berserk(color: Color) {
ctrl.setBerserk(color);
},
gone: ctrl.setGone,
goneIn: ctrl.setGone,
checkCount(e: { white: number; black: number }) {
ctrl.data.player.checks = ctrl.data.player.color == 'white' ? e.white : e.black;
ctrl.data.opponent.checks = ctrl.data.opponent.color == 'white' ? e.white : e.black;
ctrl.redraw();
},
simulPlayerMove(gameId: string) {
if (
ctrl.opts.userId &&
ctrl.data.simul &&
ctrl.opts.userId == ctrl.data.simul.hostId &&
gameId !== ctrl.data.game.id &&
ctrl.moveOn.get() &&
!game.isPlayerTurn(ctrl.data)
) {
ctrl.setRedirecting();
site.sound.play('move');
location.href = '/' + gameId;
}
},
simulEnd(simul: game.Simul) {
site.dialog.dom({
htmlText:
'<div><p>Simul complete!</p><br /><br />' +
`<a class="button" href="/simul/${simul.id}">Back to ${simul.name} simul</a></div>`,
});
},
};
site.pubsub.on('ab.rep', n => send('rep', { n }));
return {
send,
handlers,
moreTime: throttle(300, () => send('moretime')),
outoftime: backoff(500, 1.1, () => send('flag', ctrl.data.game.player)),
berserk: throttle(200, () => send('berserk', null, { ackable: true })),
sendLoading(typ: string, data?: any) {
ctrl.setLoading(true);
send(typ, data);
},
receive(typ: string, data: any): boolean {
const handler = handlers[typ];
if (handler) {
handler(data);
return true;
}
return false;
},
reload,
};
}