aboutsummaryrefslogtreecommitdiff
path: root/back/src/Game.ts
blob: 9434226af738d3658a7b139d3ab99cee1e5ebf35 (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
import {Card, Suit} from 'bsx-core';

import Client from './Client';
import logSocket from './logSocket';
import Room from './Room';
import server from './server';

class Player {
	game: Game;
	client: Client;
	cards: Card[] = [];
	stack: Card[] = [];
	flipped: Card[] = [];
	disconnected = false;
	disconnectListener?: () => void;
	rank = 0;
	constructor(game: Game, client: Client) {
		this.game = game;
		this.client = client;
	}
	sendGameState() {
		const i = this.game.players.indexOf(this);
		this.client.socket.emit('gameState', {
			cards: this.cards,
			rank: this.rank,
			players: this.game.players.map((p: Player) => ({
				username: p.client.username,
				numCards: p.cards.length,
				stackSize: p.stack.length,
				flipped: p.flipped,
				rank: p.rank,
			})),
			phase: this.game.phase,
			lastPlayed: this.game.lastPlayed,
			lastPlayedPlayer: this.game.lastPlayedPlayer < 0 ? null : this.game.players[this.game.lastPlayedPlayer].client.username,
			playerTurn: this.game.players[this.game.playerTurn].client.username
		});
	}
}

export default class Game {
	room: Room;
	players: Player[] = [];
	phase = 0;
	lastPlayed = 0;
	lastPlayedPlayer = -1;
	playerTurn = 0;
	playersFinished = 0;
	constructor(room: Room) {
		this.room = room;
		this.start();
	}
	async start() {
		const cards = [];
		for (let i = 1; i <= 13; ++i)
			for (let j = 0; j < 4; ++j)
				cards.push({rank: i, suit: j});
		// Shuffle cards
		for (let i = 0; i < 52; ++i) {
			const j = Math.floor(Math.random() * (i+1));
			[cards[i], cards[j]] = [cards[j], cards[i]];
		}
		const handSize = 5 - Math.floor(this.room.clients.length/7);
		for (let i = 0; i < this.room.clients.length; ++i) {
			this.players.push(new Player(this, this.room.clients[i]));
			this.players[i].cards = cards.slice(i * handSize, (i + 1) * handSize);
		}
		const startingPlayer = this.players[0]; // Pick a random starting player instead??
		this.playerTurn = this.players.indexOf(startingPlayer);
		this.playersFinished = this.room.clients.length;
		// Run the game
		while (true) {
			const playersLeft: Player[] = [];
			this.players.forEach((p: Player) => {
				if (!p.rank && !p.disconnected) {
					if (p.cards.length === 0) p.rank = this.playersFinished--;
					else playersLeft.push(p);
				}
			});
			if (playersLeft.length === 1) break;
			await this.round();
		}
		this.broadcastGameState();
		setTimeout(() => {
			server.to(this.room.name).emit('endGame');
			this.room.host.once('startGame', () => this.room.startGame());
			this.room.game = null;
		}, 5000);
	}
	broadcastGameState() {
		this.players.forEach((p: Player) => p.sendGameState());
	}
	async round() {
		this.phase = 0;
		this.players.forEach((p: Player) => p.stack = []);
		this.players.forEach((p: Player) => p.flipped = []);
		await this.prepare(); // Phase 0
		this.phase = 1;
		this.lastPlayed = 0;
		while (true) { // Phase 1
			const p = this.players[this.playerTurn];
			if (p.rank || p.disconnected) {
				this.playerTurn = (this.playerTurn + 1) % this.players.length;
				continue;
			}
			await this.turn();
			if (this.phase === 2) break; // Called BS!
			this.lastPlayedPlayer = this.playerTurn;
			this.playerTurn = (this.playerTurn + 1) % this.players.length;
		}
		while (this.lastPlayed > 0) { // Phase 2
			await this.flip();
			if (this.phase === 3 as number) { // Oops, flipped over a red card!
				await this.giveup(); // The player who called BS won and now the challenged player must give up a card!
				return;
			}
			this.lastPlayed--;
		}
		this.phase = 3;
		await this.giveup(); // The player who called BS won and now they must give up a card!
	}
	async prepare() { // Players prepare their hand for this round
		this.broadcastGameState();
		const playerPromises = [];
		for (let i = 0; i < this.room.clients.length; ++i) {
			const p = this.players[i];
			if (p.rank || p.disconnected) continue;
			playerPromises.push(new Promise<void>(resolve => {
				p.client.once('prepare', stack => {
					delete p.disconnectListener;
					(() => {
						p.stack = stack;
						p.cards = [...stack];
						return;
					})();
					resolve();
				});
				p.disconnectListener = () => {
					delete p.disconnectListener;
					p.client.removeAllListeners('prepare');
					resolve();
				};
			}));
		}
		await Promise.all(playerPromises);
	}
	async turn() { // Do a turn
		const p = this.players[this.playerTurn];
		this.broadcastGameState();
		await new Promise<void>(resolve => {
			p.client.once('turn', num => {
				delete p.disconnectListener;
				(() => {
					if (num === -1) {
						this.phase = 2; // Called BS, move on to the next phase!
						return;
					}
					if (num > this.lastPlayed) {
						this.lastPlayed = num;
						return;
					}
					p.client.socket.disconnect();
					logSocket(p.client.socket, 'Bad cards argument on turn');
				})();
				resolve();
			});
			p.disconnectListener = () => {
				delete p.disconnectListener;
				p.client.removeAllListeners('turn');
				resolve();
			};
		});
	}
	async flip() { // Someone called BS and now the challenged player must flip over a card
		const p = this.players[this.lastPlayedPlayer];
		this.broadcastGameState();
		await new Promise<void>(resolve => {
			p.client.once('flip', selectedPlayer => {
				delete p.disconnectListener;
				(() => {
					if (this.players[selectedPlayer].stack.length > 0) {
						if (this.players[selectedPlayer].stack[0].suit === Suit.Diamonds ||
							this.players[selectedPlayer].stack[0].suit === Suit.Hearts) this.phase = 3; // Red card
						this.players[selectedPlayer].flipped.push(this.players[selectedPlayer].stack[0]);
						this.players[selectedPlayer].stack.splice(0, 1);
						return;
					}
					p.client.socket.disconnect();
					logSocket(p.client.socket, 'Bad cards argument on turn');
				})();
				resolve();
			});
			p.disconnectListener = () => {
				delete p.disconnectListener;
				p.client.removeAllListeners('flip');
				resolve();
			};
		});
	}
	async giveup() { // Give up a card
		const p = this.players[this.lastPlayed > 0 ? this.lastPlayedPlayer : this.playerTurn];
		this.broadcastGameState();
		await new Promise<void>(resolve => {
			p.client.once('giveup', card => {
				delete p.disconnectListener;
				(() => {
					p.cards.splice(card, 1);
					return;
				})();
				resolve();
			});
			p.disconnectListener = () => {
				delete p.disconnectListener;
				p.client.removeAllListeners('giveup');
				resolve();
			};
		});
	}
	updateSocket(client: Client) {
		this.players.find((p: Player) => p.client === client)!.sendGameState();
	}
	remove(client: Client) {
		const p = this.players.find((p: Player) => p.client === client)!;
		p.disconnected = true;
		if (p.disconnectListener)
			p.disconnectListener();
	}
};