source: pages/api/poker/index.js@ 189cd8f

main
Last change on this file since 189cd8f was 189cd8f, checked in by anastasovv <simon@…>, 2 years ago

Code cleanings

  • Property mode set to 100644
File size: 14.5 KB
Line 
1import axios from 'axios';
2
3require('dotenv').config();
4
5import { v4 as uuidv4 } from 'uuid';
6
7import { tables, deck, sampleTable, samplePlayer } from './gameStates'
8
9import { drawASingleCard, setNextPlayerIdx, progressRoundIfNeeded } from './tableSpecific'
10
11/**
12 * ********************* BEGIN OF FUNCTIONS *********************
13 */
14
15function createTable(playerId, playerName, tableName) {
16 const tableId = uuidv4();
17
18 const table = {
19 id: tableId,
20 name: tableName,
21 status: '_1_just_created',
22 creator: playerName,
23 started: false,
24 ended: false,
25 round: 0,
26 turnIdx: -1,
27 pot: 0,
28 lastBet: 20,
29 turnsSinceLastBet: 0,
30 deck: [...deck],
31 players: [{
32 id: playerId,
33 table: tableId,
34 credits: 0,
35 status: '_1_just_entered',
36 displayName: playerName,
37 cards: [],
38 betAmount: 0,
39 wonAmount: 0,
40 isSatDown: false,
41 isCoordinator: true,
42 isFolded: false,
43 isGhost: false,
44 hand: {
45 hand: '',
46 highCard: 0,
47 },
48 }],
49 winners: [],
50 splitWinners: false,
51 cards: [],
52 }
53
54 tables.push(table)
55
56 return table;
57}
58
59function getRestrictedTablesArray() {
60 let result = [];
61
62 tables.forEach(table => {
63 let tmpPlayers = [];
64 table.players.forEach(player => {
65 tmpPlayers.push({
66 ...player,
67 id: '',
68 table: '',
69 cards: '',
70 })
71 });
72
73 let tmpWinners = [];
74 table.winners.forEach(winner => {
75 tmpWinners.push({
76 ...winner,
77 id: '',
78 table: '',
79 cards: '',
80 })
81 });
82
83 let tmp = {
84 ...table,
85 deck: [],
86 players: tmpPlayers,
87 winners: tmpWinners,
88 turnTimeout: null,
89 }
90
91 result.push({...tmp});
92 })
93
94 return result;
95}
96
97function getRestrictedTableArray(tableId, session_id) {
98 let result = undefined;
99
100 let tableIdx = tables.map(e=>e.id).indexOf(tableId);
101
102 if (tableIdx !== -1) {
103 let table = tables[tableIdx];
104
105 let tmpPlayers = [];
106 table.players.forEach(player => {
107 if (player.id === session_id) {
108 tmpPlayers.push({
109 ...player,
110 id: '',
111 table: '',
112 })
113 }
114 else {
115 tmpPlayers.push({
116 ...player,
117 id: '',
118 table: '',
119 cards: table.ended ? player.cards : player.cards.length > 0 ? ['back', 'back'] : '',
120 })
121 }
122 });
123
124 let tmpWinners = [];
125 table.winners.forEach(winner => {
126 if (winner.id === session_id) {
127 tmpWinners.push({
128 ...winner,
129 id: '',
130 table: '',
131 })
132 }
133 else {
134 tmpWinners.push({
135 ...winner,
136 id: '',
137 table: '',
138 cards: table.ended ? winner.cards : winner.cards.length > 0 ? ['back', 'back'] : '',
139 })
140 }
141 });
142 result = {
143 ...table,
144 players: tmpPlayers,
145 winners: tmpWinners,
146 turnTimeout: null,
147 }
148 }
149
150 return result;
151}
152
153function getTable(tableId) {
154 const tableIdx = tables.map(e=>e.id).indexOf(tableId);
155
156 if (tableIdx !== -1) {
157 return tables[tableIdx];
158 }
159
160 return undefined;
161}
162
163function getTableAndPlayer(session_id) {
164 for (let tableIdx = 0; tableIdx < tables.length; tableIdx++) {
165 const playerIdx = tables[tableIdx].players.filter(e=>e.isGhost === false).map(e=>e.id).indexOf(session_id);
166
167 if (playerIdx !== -1) {
168 return {
169 success: true,
170 table: tables[tableIdx],
171 player: tables[tableIdx].players[playerIdx],
172 }
173 }
174 }
175
176 return {
177 success: false,
178 table: {...sampleTable},
179 player: {...samplePlayer},
180 };
181}
182
183/**
184 * ********************* END OF FUNCTIONS *********************
185 */
186
187/**
188 * ********************* BEGIN OF REQUEST HANDLER *********************
189 */
190export default async function handler(req, res) {
191 /**
192 * GET method
193 */
194 if (req.method === 'GET') {
195
196 /**
197 * /---------------------- GET ----------------------/
198 * Creates the table and enters the user inside
199 * @action game_action
200 * @param session_id
201 * @param specificAction
202 * @param betAmount
203 */
204 if (req.query.action === 'game_action' && req.query?.session_id && req.query?.specificAction && req.query?.betAmount) {
205 const { success, table, player } = getTableAndPlayer(req.query.session_id)
206
207 if (success && table.started && !table.ended && player.isSatDown && !player.isFolded) {
208 if (table.players.map(e=>e.id).indexOf(req.query.session_id) !== table.turnIdx) {
209 res.end();
210 return ;
211 }
212
213 let okayToGo = false;
214
215 if (req.query.specificAction === 'check') {
216 if (table.lastBet === 0) {
217 table.turnsSinceLastBet++;
218 okayToGo = true;
219
220 progressRoundIfNeeded(table.id);
221 }
222 }
223 else if (req.query.specificAction === 'call') {
224 await axios.get(`${process.env.HOME_URL}/api/postgre/?action=take_credits&session_id=${req.query.session_id}&credits=${table.lastBet}&takeWhatYouCan=true`).then(postgreRes => {
225 if (postgreRes.data?.success) {
226 player.credits = postgreRes.data?.credits;
227
228 if (player.credits >= table.lastBet)
229 player.betAmount += table.lastBet;
230 else
231 player.betAmount += player.credits;
232
233 table.pot += table.lastBet;
234 table.turnsSinceLastBet++;
235 okayToGo = true;
236
237 progressRoundIfNeeded(table.id);
238 }
239 });
240 }
241 else if (req.query.specificAction === 'raise') {
242 const betAmount = parseInt(req.query.betAmount);
243
244 if (betAmount >= table.lastBet) {
245 await axios.get(`${process.env.HOME_URL}/api/postgre/?action=take_credits&session_id=${req.query.session_id}&credits=${betAmount}&takeWhatYouCan=true`).then(postgreRes => {
246 if (postgreRes.data?.success) {
247 player.credits = postgreRes.data?.credits;
248
249 player.betAmount += betAmount;
250 table.pot += betAmount;
251 table.turnsSinceLastBet = 1;
252 okayToGo = true;
253
254 progressRoundIfNeeded(table.id);
255 }
256 });
257 }
258 }
259 else if (req.query.specificAction === 'fold') {
260 player.isFolded = true;
261 okayToGo = true;
262
263 progressRoundIfNeeded(table.id);
264 }
265
266 if (okayToGo) {
267 setNextPlayerIdx(table.id);
268 }
269 }
270
271 res.end();
272 }
273
274 /**
275 * /---------------------- GET ----------------------/
276 * Creates the table and enters the user inside
277 * @action start_game
278 * @param session_id
279 */
280 if (req.query.action === 'start_game' && req.query?.session_id) {
281 const { success, table } = getTableAndPlayer(req.query.session_id)
282
283 if (success && !table.started) {
284 table.players.forEach(player => {
285 axios.get(`${process.env.HOME_URL}/api/postgre/?action=check_if_logged_in&session_id=${player.id}`).then(postgreRes => {
286 if (postgreRes.data?.success) {
287 player.credits = postgreRes.data?.credits;
288 }
289 });
290 })
291
292 table.started = true;
293 table.round = 1;
294
295 table.turnIdx = Math.floor(Math.random(0, table.players.length))
296 setNextPlayerIdx(table.id);
297
298 table.players.forEach(player => {
299 if (player.isSatDown) {
300 for (let i = 0; i < 2; i++) {
301 const card = drawASingleCard(table.id);
302
303 if (card !== undefined) {
304 player.cards.push(card);
305 }
306 }
307 }
308 })
309 }
310
311 res.end();
312 }
313
314 /**
315 * /---------------------- GET ----------------------/
316 * Creates the table and enters the user inside
317 * @action sit_down
318 * @param session_id
319 * @param tableId
320 */
321 if (req.query.action === 'sit_down' && req.query?.session_id && req.query?.tableId) {
322 const { success, table, player } = getTableAndPlayer(req.query.session_id)
323
324 if (success && !table.started) {
325 player.isSatDown = true;
326 }
327
328 res.end();
329 }
330
331 /**
332 * /---------------------- GET ----------------------/
333 * Creates the table and enters the user inside
334 * @action leave_table
335 * @param session_id
336 */
337 if (req.query.action === 'leave_table' && req.query?.session_id) {
338 const { success, table, player } = getTableAndPlayer(req.query.session_id);
339
340 if (success) {
341 player.isGhost = true;
342 player.isFolded = true;
343
344 if (table.players[table.turnIdx] !== undefined && table.players[table.turnIdx] === player) {
345 setNextPlayerIdx(table.id);
346 }
347 }
348
349 res.end();
350 }
351
352 /**
353 * /---------------------- GET ----------------------/
354 * Creates the table and enters the user inside
355 * @action join_a_table
356 * @param session_id
357 * @param tableId
358 * @param displayName
359 */
360 if (req.query.action === 'join_a_table' && req.query?.session_id && req.query?.tableId && req.query?.displayName) {
361 if (req.query.tableId.length > 0) {
362 const { success } = getTableAndPlayer(req.query.session_id);
363
364 if (!success) {
365 const table = getTable(req.query.tableId)
366
367 if (table !== undefined && !table.started) {
368 table.players.push({
369 id: req.query.session_id,
370 table: req.query.tableId,
371 credits: 0,
372 status: '_1_just_entered',
373 displayName: req.query.displayName,
374 cards: [],
375 betAmount: 0,
376 wonAmount: 0,
377 isSatDown: false,
378 isCoordinator: false,
379 isFolded: false,
380 isGhost: false,
381 hand: {
382 hand: '',
383 highCard: 0,
384 },
385 })
386 }
387 }
388 }
389
390 res.end();
391 }
392
393 /**
394 * /---------------------- GET ----------------------/
395 * Creates the table and enters the user inside
396 * @action create_a_table
397 * @param session_id
398 * @param displayName
399 * @param tableName
400 */
401 if (req.query.action === 'create_a_table' && req.query?.session_id && req.query?.displayName && req.query?.tableName) {
402 const { success } = getTableAndPlayer(req.query.session_id);
403
404 if (!success) {
405 createTable(req.query.session_id, req.query.displayName, req.query.tableName);
406 }
407
408 res.end();
409 }
410
411 /**
412 * /---------------------- GET ----------------------/
413 * Creates the table and enters the user inside
414 * @action update_state
415 * @param session_id
416 */
417 if (req.query.action === 'update_state' && req.query?.session_id) {
418 const session_id = req.query.session_id;
419
420 const { success, table, player } = getTableAndPlayer(session_id);
421
422 res.json({
423 success: true,
424 pokerGame: {
425 tables: getRestrictedTablesArray(),
426 table: getRestrictedTableArray(table.id, req.query.session_id),
427 player: player,
428 }
429 })
430 }
431
432 /**
433 * /---------------------- GET ----------------------/
434 * If the player is not in an existing room, create a room for them.
435 * If they are reconnecting, get the room they were in.
436 * @action get_player_info_on_enter
437 * @param session_id
438 */
439 if (req.query.action === 'get_player_info_on_enter' && req.query?.session_id) {
440 const session_id = req.query.session_id;
441
442 axios.get(`${process.env.HOME_URL}/api/postgre?action=check_if_logged_in&session_id=${session_id}`).then(postgreRes => {
443 if (postgreRes.data?.success) {
444 res.json({
445 success: true,
446 displayName: postgreRes.data?.displayName,
447 session_id: postgreRes.data?.session_id,
448 credits: postgreRes.data?.credits,
449 })
450 }
451 else {
452 res.json({
453 success: false,
454 })
455 }
456 });
457 }
458 }
459}
460/**
461 * ********************* END OF REQUEST HANDLER *********************
462 */
Note: See TracBrowser for help on using the repository browser.