source: pages/api/poker/index.js@ aac3b2b

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

Fixes to poker functionality

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