source: pages/api/blackjack/index.js

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

Added authentication with google

  • Property mode set to 100644
File size: 14.3 KB
Line 
1import axios from 'axios';
2
3require('dotenv').config();
4
5import { game, drawASingleCard, getInitialCards, calculateHandValue, getGame, getRestrictedGameObject } from './gameStates';
6import { calculateEarnings, calculateSideBetEarnings } from './calculateEarnings';
7
8import { rooms, saveGameInHistory, update_rooms_to_database } from '../postgre/index'
9
10/**
11 * Set up a room
12 */
13function createARoom(session_id, displayName, username) {
14 let room = {
15 ...game, displayName: displayName, username: username, playerCards: [...game.playerCards], dealerCards: [...game.dealerCards],
16 }
17
18 rooms[session_id] = room;
19}
20
21/**
22 * ********************* BEGIN OF REQUEST HANDLER *********************
23 */
24export default async function handler(req, res) {
25 /**
26 * GET method
27 */
28 if (req.method === 'GET') {
29 /**
30 * /---------------------- GET ----------------------/
31 * If game status is _5_game_over, restart the room for a new game.
32 * @action play_again
33 * @param session_id
34 */
35 if (req.query.action === 'play_again' && req.query?.session_id) {
36 const session_id = req.query.session_id;
37
38 if (rooms[session_id] !== undefined && rooms[session_id].status.substr(1, 1) === '5') {
39 rooms[session_id] = {...game, displayName: rooms[session_id].displayName, username: rooms[session_id].username, playerCards: [...game.playerCards], dealerCards: [...game.dealerCards]};
40
41 rooms[session_id].betOutcomeMessageShown = true;
42
43 update_rooms_to_database();
44 }
45
46 res.end();
47 }
48
49 /**
50 * /---------------------- GET ----------------------/
51 * If game status is _4_cards_on_the_table, turn off the alert for side bet outcome
52 * @action continue_from_side_bet
53 * @param session_id
54 */
55 if (req.query.action === 'continue_from_side_bet' && req.query?.session_id) {
56 const session_id = req.query.session_id;
57
58 if (rooms[session_id] !== undefined && rooms[session_id].status.substr(1, 1) === '4') {
59 rooms[session_id].sideBetOutcomeMessageShown = true;
60
61 update_rooms_to_database();
62 }
63
64 res.end();
65 }
66
67 /**
68 * /---------------------- GET ----------------------/
69 * If game status is _4_cards_on_the_table, draw cards for the dealer while handValue < 17, and calculate game outcome and player earnings.
70 * Also, update the player's credits and stats in the database through /api/postgre?action=add_credits.
71 * @action stand
72 * @param session_id
73 */
74 if (req.query.action === 'stand' && req.query?.session_id) {
75 const session_id = req.query.session_id;
76
77 if (rooms[session_id] !== undefined && rooms[session_id].status.substr(1, 1) === '4') {
78 const room = rooms[session_id];
79
80 while (calculateHandValue(room.dealerCards) < 17) {
81 room.dealerCards.push(drawASingleCard(room));
82 }
83
84 room.status = '_5_game_over';
85
86 if (calculateHandValue(room.dealerCards) > 21) {
87 room.outcome = 'dealer_busted';
88 }
89 else if (calculateHandValue(room.playerCards) > calculateHandValue(room.dealerCards)) {
90 room.outcome = 'player_won';
91 }
92 else if (calculateHandValue(room.playerCards) < calculateHandValue(room.dealerCards)) {
93 room.outcome = 'player_lost';
94 }
95 else {
96 room.outcome = 'draw';
97 }
98
99 room.earnings = calculateEarnings(room);
100
101 if (room.outcome === 'draw') {
102 room.messageTitle = 'Draw!';
103 room.messageDescription = `You got your $${room.earnings} back`
104 }
105 else if (room.outcome === 'player_won') {
106 room.messageTitle = 'You won!';
107 room.messageDescription = `You won $${room.earnings}`
108 }
109 else if (room.outcome === 'dealer_busted') {
110 room.messageTitle = `Dealer ${room.dealerName} busted!`;
111 room.messageDescription = `You won $${room.earnings}`
112 }
113 else if (room.outcome === 'player_lost') {
114 room.messageTitle = 'You lost!';
115 room.messageDescription = `You lost $${-1*room.earnings}`
116 }
117 room.betOutcomeMessageShown = false;
118
119 rooms[session_id] = room;
120
121 axios.get(`${process.env.HOME_URL}/api/postgre/?action=add_credits&session_id=${session_id}&credits=${room.earnings}&game=blackjack&outcome=${room.outcome}`).then(postgreRes => {
122 if (postgreRes.data?.success) {
123 rooms[session_id].credits = postgreRes.data?.credits;
124
125 res.json({
126 success: true,
127 status: rooms[session_id].status,
128 playerCards: rooms[session_id].playerCards,
129 dealerCards: rooms[session_id].dealerCards,
130 outcome: rooms[session_id].outcome,
131 earnings: rooms[session_id].earnings,
132 credits: postgreRes.data?.credits,
133 })
134
135 update_rooms_to_database();
136 }
137 else {
138 res.json({
139 success: false,
140 })
141 }
142 });
143
144 rooms[session_id].finished = new Date().toGMTString();
145 saveGameInHistory('blackjack', rooms[session_id], rooms[session_id].username);
146
147 return ;
148 }
149
150 res.json({
151 success: false,
152 })
153 }
154
155 /**
156 * /---------------------- GET ----------------------/
157 * If game status is _4_cards_on_the_table, draw a card for the player.
158 * If player busts, update the player's stats in the database through /api/postgre?action=add_credits.
159 * @action hit_a_card
160 * @param session_id
161 */
162 if (req.query.action === 'hit_a_card' && req.query?.session_id) {
163 const session_id = req.query.session_id;
164
165 if (rooms[session_id] !== undefined && rooms[session_id].status.substr(1, 1) === '4') {
166 const room = rooms[session_id];
167
168 room.playerCards.push(drawASingleCard(room));
169
170 rooms[session_id] = room;
171
172 if (calculateHandValue(room.playerCards) > 21) {
173 room.status = '_5_game_over';
174 room.outcome = 'player_busted';
175
176 room.earnings = calculateEarnings(room);
177
178 room.messageTitle = 'You busted!';
179 room.messageDescription = `You lost $${-1*room.earnings}`
180
181 room.betOutcomeMessageShown = false;
182
183 rooms[session_id] = room;
184
185 axios.get(`${process.env.HOME_URL}/api/postgre/?action=add_credits&session_id=${session_id}&credits=${room.earnings}&game=blackjack&outcome=${room.outcome}`).then(postgreRes => {
186 if (postgreRes.data?.success) {
187 rooms[session_id].credits = postgreRes.data?.credits;
188
189 res.json({
190 success: true,
191 status: rooms[session_id].status,
192 playerCards: rooms[session_id].playerCards,
193 outcome: rooms[session_id].outcome,
194 earnings: rooms[session_id].earnings,
195 credits: postgreRes.data?.credits,
196 })
197
198 update_rooms_to_database();
199 }
200 else {
201 res.json({
202 success: false,
203 })
204 }
205 });
206
207 rooms[session_id].finished = new Date().toGMTString();
208 saveGameInHistory('blackjack', rooms[session_id], rooms[session_id].username);
209 }
210 else {
211 res.json({
212 success: true,
213 status: rooms[session_id].status,
214 playerCards: rooms[session_id].playerCards,
215 outcome: rooms[session_id].outcome,
216 earnings: rooms[session_id].earnings,
217 })
218
219 update_rooms_to_database();
220 }
221
222 return ;
223 }
224
225 res.json({
226 success: false,
227 })
228 }
229
230 /**
231 * /---------------------- GET ----------------------/
232 * If game status is _3_made_side_bet, check if the player won the side bet or not (if they placed a side bet of course).
233 * Update the player's stats in the database through /api/postgre?action=add_credits.
234 * @action get_initial_cards
235 * @param session_id
236 */
237 if (req.query.action === 'get_initial_cards' && req.query?.session_id) {
238 const session_id = req.query.session_id;
239
240 if (rooms[session_id] !== undefined && rooms[session_id].status.substr(1, 1) === '3') {
241 const room = rooms[session_id];
242
243 getInitialCards(room);
244
245 room.status = '_4_cards_on_the_table';
246
247 rooms[session_id] = room;
248
249 update_rooms_to_database();
250
251 if (room.sideBetName !== '' && room.sideBetName !== 'none') {
252 room.sideBetEarnings = calculateSideBetEarnings(room);
253 room.sideBetOutcome = room.sideBetEarnings > 0 ? 'side_bet_won' : 'side_bet_lost';
254
255 if (room.sideBetOutcome === 'side_bet_won') {
256 room.messageTitle = `You won the side bet!`;
257 room.messageDescription = `You won $${room.sideBetEarnings}`
258 }
259 else if (room.sideBetOutcome === 'side_bet_lost') {
260 room.messageTitle = `You lost the side bet!`;
261 room.messageDescription = `You lost $${-1*room.sideBetEarnings}`
262 }
263
264 room.sideBetOutcomeMessageShown = false;
265
266 rooms[session_id] = room;
267
268 axios.get(`${process.env.HOME_URL}/api/postgre/?action=add_credits&session_id=${session_id}&credits=${room.sideBetEarnings}`).then(postgreRes => {
269 if (postgreRes.data?.success) {
270 rooms[session_id].credits = postgreRes.data?.credits;
271
272 update_rooms_to_database();
273 }
274 });
275 }
276 }
277
278 res.end();
279 }
280
281 /**
282 * /---------------------- GET ----------------------/
283 * If game status is _2_made_initial_bet, place a side bet if the user has chosen one.
284 * @action make_side_bet
285 * @param session_id
286 * @param bet
287 * @param betName
288 */
289 if (req.query.action === 'make_side_bet' && req.query?.session_id && req.query?.bet && req.query?.betName) {
290 const session_id = req.query.session_id;
291
292 if (rooms[session_id] !== undefined && rooms[session_id].status.substr(1, 1) === '2') {
293 if (req.query?.skip !== 'true' && parseInt(req.query.bet) <= 0) {
294 return ;
295 }
296
297 axios.get(`${process.env.HOME_URL}/api/postgre?action=take_credits&session_id=${session_id}&credits=${req.query.bet}`).then(postgreRes => {
298 if (postgreRes.data?.success) {
299 rooms[session_id].credits = postgreRes.data?.credits;
300
301 const room = rooms[session_id];
302
303 room.sideBet = parseInt(req.query.bet);
304 room.sideBetName = req.query.betName;
305 room.status = '_3_made_side_bet';
306
307 rooms[session_id] = room;
308
309 res.json({
310 success: true,
311 })
312
313 update_rooms_to_database();
314 }
315 else {
316 res.end();
317 }
318 });
319 }
320 }
321
322 /**
323 * /---------------------- GET ----------------------/
324 * If game status is _1_room_created, get the initial bet placed by the player.
325 * @action make_initial_bet
326 * @param session_id
327 * @param bet
328 */
329 if (req.query.action === 'make_initial_bet' && req.query?.session_id && req.query?.bet) {
330 const session_id = req.query.session_id;
331
332 if (rooms[session_id] !== undefined && rooms[session_id].status.substr(1, 1) === '1') {
333 if (parseInt(req.query.bet) <= 0) return ;
334
335 axios.get(`${process.env.HOME_URL}/api/postgre?action=take_credits&session_id=${session_id}&credits=${req.query.bet}`).then(postgreRes => {
336 if (postgreRes.data?.success) {
337 rooms[session_id].credits = postgreRes.data?.credits;
338
339 const room = rooms[session_id];
340
341 room.initialBet = parseInt(req.query.bet);
342 room.status = '_2_made_initial_bet';
343
344 rooms[session_id] = room;
345
346 update_rooms_to_database();
347 }
348 });
349 }
350
351 res.end();
352 }
353
354 /**
355 * /---------------------- GET ----------------------/
356 * Updates the state periodically
357 * @action update_state
358 * @param session_id
359 */
360 if (req.query.action === 'update_state' && req.query?.session_id) {
361 const session_id = req.query.session_id;
362
363 const { success, game } = getGame(session_id);
364
365 res.json({
366 success: true,
367 blackjackGame: getRestrictedGameObject(session_id),
368 })
369 }
370
371 /**
372 * /---------------------- GET ----------------------/
373 * If the player is not in an existing room, create a room for them.
374 * If they are reconnecting, get the room they were in.
375 * @action get_player_info_on_enter
376 * @param session_id
377 */
378 if (req.query.action === 'get_player_info_on_enter' && req.query?.session_id) {
379 const session_id = req.query.session_id;
380
381 axios.get(`${process.env.HOME_URL}/api/postgre?action=check_if_logged_in&session_id=${session_id}`).then(postgreRes => {
382 if (postgreRes.data?.success) {
383 if (rooms[session_id] !== undefined) {
384 // room exists
385 }
386 else {
387 createARoom(session_id, postgreRes.data?.displayName, postgreRes.data?.username);
388 }
389
390 let dealerCardsTmp = [];
391 if (rooms[session_id].status.substr(1, 1) != '5') { // 5 == game_over
392 rooms[session_id].dealerCards.forEach((card, i) => {
393 if (i === 0) {
394 dealerCardsTmp.push(card);
395 }
396 else {
397 dealerCardsTmp.push('back');
398 }
399 })
400 }
401 else {
402 dealerCardsTmp = rooms[session_id].dealerCards;
403 }
404
405 res.json({
406 success: true,
407 status: rooms[session_id].status,
408 initialBet: rooms[session_id].initialBet,
409 sideBet: rooms[session_id].sideBet,
410 sideBetName: rooms[session_id].sideBetName,
411 playerCards: rooms[session_id].playerCards,
412 dealerCards: dealerCardsTmp,
413 outcome: rooms[session_id].outcome,
414 earnings: rooms[session_id].earnings,
415 displayName: postgreRes.data?.displayName,
416 session_id: postgreRes.data?.session_id,
417 credits: postgreRes.data?.credits,
418 })
419
420 update_rooms_to_database();
421 }
422 else {
423 res.json({
424 success: false,
425 })
426 }
427 });
428 }
429 }
430}
431/**
432 * ********************* END OF REQUEST HANDLER *********************
433 */
Note: See TracBrowser for help on using the repository browser.