summaryrefslogtreecommitdiff
path: root/src/server/api/stream/channels/games/reversi-game.ts
blob: e60017948093dd0d471b73909567cb508457fa5c (plain)
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
import autobind from 'autobind-decorator';
import * as CRC32 from 'crc-32';
import { publishReversiGameStream } from '../../../../../services/stream';
import Reversi from '../../../../../games/reversi/core';
import * as maps from '../../../../../games/reversi/maps';
import Channel from '../../channel';
import { ReversiGame } from '../../../../../models/entities/games/reversi/game';
import { ReversiGames } from '../../../../../models';

export default class extends Channel {
	public readonly chName = 'gamesReversiGame';
	public static shouldShare = false;
	public static requireCredential = false;

	private gameId: ReversiGame['id'] | null = null;

	@autobind
	public async init(params: any) {
		this.gameId = params.gameId;

		// Subscribe game stream
		this.subscriber.on(`reversiGameStream:${this.gameId}`, data => {
			this.send(data);
		});
	}

	@autobind
	public onMessage(type: string, body: any) {
		switch (type) {
			case 'accept': this.accept(true); break;
			case 'cancelAccept': this.accept(false); break;
			case 'updateSettings': this.updateSettings(body.key, body.value); break;
			case 'initForm': this.initForm(body); break;
			case 'updateForm': this.updateForm(body.id, body.value); break;
			case 'message': this.message(body); break;
			case 'set': this.set(body.pos); break;
			case 'check': this.check(body.crc32); break;
		}
	}

	@autobind
	private async updateSettings(key: string, value: any) {
		if (this.user == null) return;

		const game = await ReversiGames.findOne(this.gameId!);
		if (game == null) throw new Error('game not found');

		if (game.isStarted) return;
		if ((game.user1Id !== this.user.id) && (game.user2Id !== this.user.id)) return;
		if ((game.user1Id === this.user.id) && game.user1Accepted) return;
		if ((game.user2Id === this.user.id) && game.user2Accepted) return;

		if (!['map', 'bw', 'isLlotheo', 'canPutEverywhere', 'loopedBoard'].includes(key)) return;

		await ReversiGames.update(this.gameId!, {
			[key]: value
		});

		publishReversiGameStream(this.gameId!, 'updateSettings', {
			key: key,
			value: value
		});
	}

	@autobind
	private async initForm(form: any) {
		if (this.user == null) return;

		const game = await ReversiGames.findOne(this.gameId!);
		if (game == null) throw new Error('game not found');

		if (game.isStarted) return;
		if ((game.user1Id !== this.user.id) && (game.user2Id !== this.user.id)) return;

		const set = game.user1Id === this.user.id ? {
			form1: form
		} : {
			form2: form
		};

		await ReversiGames.update(this.gameId!, set);

		publishReversiGameStream(this.gameId!, 'initForm', {
			userId: this.user.id,
			form
		});
	}

	@autobind
	private async updateForm(id: string, value: any) {
		if (this.user == null) return;

		const game = await ReversiGames.findOne(this.gameId!);
		if (game == null) throw new Error('game not found');

		if (game.isStarted) return;
		if ((game.user1Id !== this.user.id) && (game.user2Id !== this.user.id)) return;

		const form = game.user1Id === this.user.id ? game.form2 : game.form1;

		const item = form.find((i: any) => i.id == id);

		if (item == null) return;

		item.value = value;

		const set = game.user1Id === this.user.id ? {
			form2: form
		} : {
				form1: form
			};

		await ReversiGames.update(this.gameId!, set);

		publishReversiGameStream(this.gameId!, 'updateForm', {
			userId: this.user.id,
			id,
			value
		});
	}

	@autobind
	private async message(message: any) {
		if (this.user == null) return;

		message.id = Math.random();
		publishReversiGameStream(this.gameId!, 'message', {
			userId: this.user.id,
			message
		});
	}

	@autobind
	private async accept(accept: boolean) {
		if (this.user == null) return;

		const game = await ReversiGames.findOne(this.gameId!);
		if (game == null) throw new Error('game not found');

		if (game.isStarted) return;

		let bothAccepted = false;

		if (game.user1Id === this.user.id) {
			await ReversiGames.update(this.gameId!, {
				user1Accepted: accept
			});

			publishReversiGameStream(this.gameId!, 'changeAccepts', {
				user1: accept,
				user2: game.user2Accepted
			});

			if (accept && game.user2Accepted) bothAccepted = true;
		} else if (game.user2Id === this.user.id) {
			await ReversiGames.update(this.gameId!, {
				user2Accepted: accept
			});

			publishReversiGameStream(this.gameId!, 'changeAccepts', {
				user1: game.user1Accepted,
				user2: accept
			});

			if (accept && game.user1Accepted) bothAccepted = true;
		} else {
			return;
		}

		if (bothAccepted) {
			// 3秒後、まだacceptされていたらゲーム開始
			setTimeout(async () => {
				const freshGame = await ReversiGames.findOne(this.gameId!);
				if (freshGame == null || freshGame.isStarted || freshGame.isEnded) return;
				if (!freshGame.user1Accepted || !freshGame.user2Accepted) return;

				let bw: number;
				if (freshGame.bw == 'random') {
					bw = Math.random() > 0.5 ? 1 : 2;
				} else {
					bw = parseInt(freshGame.bw, 10);
				}

				function getRandomMap() {
					const mapCount = Object.entries(maps).length;
					const rnd = Math.floor(Math.random() * mapCount);
					return Object.values(maps)[rnd].data;
				}

				const map = freshGame.map != null ? freshGame.map : getRandomMap();

				await ReversiGames.update(this.gameId!, {
					startedAt: new Date(),
					isStarted: true,
					black: bw,
					map: map
				});

				//#region 盤面に最初から石がないなどして始まった瞬間に勝敗が決定する場合があるのでその処理
				const o = new Reversi(map, {
					isLlotheo: freshGame.isLlotheo,
					canPutEverywhere: freshGame.canPutEverywhere,
					loopedBoard: freshGame.loopedBoard
				});

				if (o.isEnded) {
					let winner;
					if (o.winner === true) {
						winner = freshGame.black == 1 ? freshGame.user1Id : freshGame.user2Id;
					} else if (o.winner === false) {
						winner = freshGame.black == 1 ? freshGame.user2Id : freshGame.user1Id;
					} else {
						winner = null;
					}

					await ReversiGames.update(this.gameId!, {
						isEnded: true,
						winnerId: winner
					});

					publishReversiGameStream(this.gameId!, 'ended', {
						winnerId: winner,
						game: await ReversiGames.pack(this.gameId!, this.user)
					});
				}
				//#endregion

				publishReversiGameStream(this.gameId!, 'started',
					await ReversiGames.pack(this.gameId!, this.user));
			}, 3000);
		}
	}

	// 石を打つ
	@autobind
	private async set(pos: number) {
		if (this.user == null) return;

		const game = await ReversiGames.findOne(this.gameId!);
		if (game == null) throw new Error('game not found');

		if (!game.isStarted) return;
		if (game.isEnded) return;
		if ((game.user1Id !== this.user.id) && (game.user2Id !== this.user.id)) return;

		const o = new Reversi(game.map, {
			isLlotheo: game.isLlotheo,
			canPutEverywhere: game.canPutEverywhere,
			loopedBoard: game.loopedBoard
		});

		for (const log of game.logs) {
			o.put(log.color, log.pos);
		}

		const myColor =
			((game.user1Id === this.user.id) && game.black == 1) || ((game.user2Id === this.user.id) && game.black == 2)
				? true
				: false;

		if (!o.canPut(myColor, pos)) return;
		o.put(myColor, pos);

		let winner;
		if (o.isEnded) {
			if (o.winner === true) {
				winner = game.black == 1 ? game.user1Id : game.user2Id;
			} else if (o.winner === false) {
				winner = game.black == 1 ? game.user2Id : game.user1Id;
			} else {
				winner = null;
			}
		}

		const log = {
			at: new Date(),
			color: myColor,
			pos
		};

		const crc32 = CRC32.str(game.logs.map(x => x.pos.toString()).join('') + pos.toString()).toString();

		game.logs.push(log);

		await ReversiGames.update(this.gameId!, {
			crc32,
			isEnded: o.isEnded,
			winnerId: winner,
			logs: game.logs
		});

		publishReversiGameStream(this.gameId!, 'set', Object.assign(log, {
			next: o.turn
		}));

		if (o.isEnded) {
			publishReversiGameStream(this.gameId!, 'ended', {
				winnerId: winner,
				game: await ReversiGames.pack(this.gameId!, this.user)
			});
		}
	}

	@autobind
	private async check(crc32: string | number) {
		const game = await ReversiGames.findOne(this.gameId!);
		if (game == null) throw new Error('game not found');

		if (!game.isStarted) return;

		if (crc32.toString() !== game.crc32) {
			this.send('rescue', await ReversiGames.pack(game, this.user));
		}
	}
}