Changeset 95ce58b


Ignore:
Timestamp:
07/08/22 13:51:13 (23 months ago)
Author:
anastasovv <simon@…>
Branches:
main
Children:
d0ef259
Parents:
aac3b2b
Message:

Saving sessions data and poker data to database

Files:
5 edited

Legend:

Unmodified
Added
Removed
  • next.config.js

    raac3b2b r95ce58b  
    22const nextConfig = {
    33  reactStrictMode: true,
     4 
     5  webpack: (config) => {
     6    config.experiments = config.experiments || {}
     7    config.experiments.topLevelAwait = true
     8    return config
     9  },
    410}
    511
  • pages/api/poker/gameStates.js

    raac3b2b r95ce58b  
    1 export let tables = []
     1import { tables } from "../postgre/index";
     2
     3import { v4 as uuidv4 } from "uuid";
    24
    35export const singleDeck = ["SA", "S2", "S3", "S4", "S5", "S6", "S7", "S8", "S9", "SX", "SJ", "SQ", "SK",
    4                     "HA", "H2", "H3", "H4", "H5", "H6", "H7", "H8", "H9", "HX", "HJ", "HQ", "HK",
    5                     "CA", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CX", "CJ", "CQ", "CK",
    6                     "DA", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DX", "DJ", "DQ", "DK"    ];
     6                           "HA", "H2", "H3", "H4", "H5", "H6", "H7", "H8", "H9", "HX", "HJ", "HQ", "HK",
     7                           "CA", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CX", "CJ", "CQ", "CK",
     8                           "DA", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DX", "DJ", "DQ", "DK"    ];
    79
    810export const deck = [...singleDeck];
     
    1719    round: 0,
    1820    turnIdx: -1,
     21    lastActivity: 0,
    1922    pot: 0,
    2023    lastBet: 20,
     
    4548    },
    4649}
     50
     51
     52/**
     53 * ********************* BEGIN OF FUNCTIONS *********************
     54 */
     55
     56export function createTable(playerId, playerName, tableName) {
     57    const tableId = uuidv4();
     58
     59    const table = {
     60        id: tableId,
     61        name: tableName,
     62        status: '_1_just_created',
     63        creator: playerName,
     64        started: false,
     65        ended: false,
     66        round: 0,
     67        turnIdx: -1,
     68        lastActivity: 0,
     69        prevTurnIdx: -2,
     70        pot: 0,
     71        lastBet: 20,
     72        turnsSinceLastBet: 0,
     73        deck: [...deck],
     74        players: [{
     75            id: playerId,
     76            table: tableId,
     77            credits: 0,
     78            status: '_1_just_entered',
     79            displayName: playerName,
     80            cards: [],
     81            betAmount: 0,
     82            wonAmount: 0,
     83            isSatDown: false,
     84            isCoordinator: true,
     85            isFolded: false,
     86            isGhost: false,
     87            hand: {
     88                hand: '',
     89                highCard: 0,
     90            },
     91        }],
     92        onlyOnePlayerLeft: false,
     93        winners: [],
     94        splitWinners: false,
     95        cards: [],
     96    }
     97
     98    tables.push(table)
     99
     100    return table;
     101}
     102
     103export function getRestrictedTablesArray() {
     104    let result = [];
     105
     106    tables.forEach(table => {
     107        let tmpPlayers = [];
     108        table.players.forEach(player => {
     109            tmpPlayers.push({
     110                ...player,
     111                id: '',
     112                table: '',
     113                cards: '',
     114            })
     115        });
     116
     117        let tmpWinners = [];
     118        table.winners.forEach(winner => {
     119            tmpWinners.push({
     120                ...winner,
     121                id: '',
     122                table: '',
     123                cards: '',
     124            })
     125        });
     126
     127        let tmp = {
     128            ...table,
     129            deck: [],
     130            players: tmpPlayers,
     131            winners: tmpWinners,
     132            turnTimeout: null,
     133        }
     134
     135        result.push({...tmp});
     136    })
     137
     138    return result;
     139}
     140
     141export function getRestrictedTableArray(tableId, session_id) {
     142    let result = undefined;
     143
     144    let tableIdx = tables.map(e=>e.id).indexOf(tableId);
     145
     146    if (tableIdx !== -1) {
     147        let table = tables[tableIdx];
     148
     149        let tmpPlayers = [];
     150        table.players.forEach(player => {
     151            if (player.id === session_id) {
     152                tmpPlayers.push({
     153                    ...player,
     154                    id: '',
     155                    table: '',
     156                })
     157            }
     158            else {
     159                tmpPlayers.push({
     160                    ...player,
     161                    id: '',
     162                    table: '',
     163                    cards: table.ended ? player.cards : player.cards.length > 0 ? ['back', 'back'] : '',
     164                })
     165            }
     166        });
     167
     168        let tmpWinners = [];
     169        table.winners.forEach(winner => {
     170            if (winner.id === session_id) {
     171                tmpWinners.push({
     172                    ...winner,
     173                    id: '',
     174                    table: '',
     175                })
     176            }
     177            else {
     178                tmpWinners.push({
     179                    ...winner,
     180                    id: '',
     181                    table: '',
     182                    cards: table.ended ? winner.cards : winner.cards.length > 0 ? ['back', 'back'] : '',
     183                })
     184            }
     185        });
     186        result = {
     187            ...table,
     188            players: tmpPlayers,
     189            winners: tmpWinners,
     190            turnTimeout: null,
     191        }
     192    }
     193
     194    return result;
     195}
     196
     197export function getTable(tableId) {
     198    const tableIdx = tables.map(e=>e.id).indexOf(tableId);
     199
     200    if (tableIdx !== -1) {
     201        return tables[tableIdx];
     202    }
     203
     204    return undefined;
     205}
     206
     207export function getTableAndPlayer(session_id) {
     208    for (let tableIdx = 0; tableIdx < tables.length; tableIdx++) {
     209        const playerIdx = tables[tableIdx].players.filter(e=>e.isGhost === false).map(e=>e.id).indexOf(session_id);
     210
     211        if (playerIdx !== -1) {
     212            return {
     213                success: true,
     214                table: tables[tableIdx],
     215                player: tables[tableIdx].players[playerIdx],
     216            }
     217        }
     218    }
     219
     220    return {
     221        success: false,
     222        table: {...sampleTable},
     223        player: {...samplePlayer},
     224    };
     225}
     226
     227/**
     228 * ********************* END OF FUNCTIONS *********************
     229 */
  • pages/api/poker/index.js

    raac3b2b r95ce58b  
    33require('dotenv').config();
    44
    5 import { v4 as uuidv4 } from 'uuid';
    6 
    7 import { tables, deck, sampleTable, samplePlayer } from './gameStates'
    8 
    9 import { drawASingleCard, setNextPlayerIdx, progressRoundIfNeeded } from './tableSpecific'
    10 
    11 /**
    12  * ********************* BEGIN OF FUNCTIONS *********************
    13  */
    14 
    15 function 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 
    60 function 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 
    98 function 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 
    154 function 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 
    164 function 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  */
     5import { createTable, getRestrictedTablesArray, getRestrictedTableArray, getTable, getTableAndPlayer } from './gameStates';
     6
     7import { drawASingleCard, setNextPlayerIdx, progressRoundIfNeeded, progressRoundTillTheEnd } from './tableSpecific'
     8
     9import { tables, cleanTables, update_tables_to_database, load_tables_from_database } from '../postgre/index'
    18710
    18811/**
     
    26689
    26790                if (okayToGo) {
     91                    table.lastActivity = Date.now();
    26892                    setNextPlayerIdx(table.id);
    26993                }
    27094            }
    27195           
     96            update_tables_to_database();
     97
    27298            res.end();
    27399        }
     
    291117                })
    292118
     119                table.lastActivity = Date.now();
    293120                table.started = true;
    294121                table.round = 1;
     
    309136                })
    310137            }
     138
     139            update_tables_to_database();
    311140           
    312141            res.end();
     
    327156            }
    328157
     158            update_tables_to_database();
     159
    329160            res.end();
    330161        }
     
    340171
    341172            if (success) {
     173                table.lastActivity = Date.now();
     174               
    342175                player.isGhost = true;
    343176                player.isFolded = true;
     
    352185                }
    353186            }
     187
     188            update_tables_to_database();
    354189
    355190            res.end();
     
    394229            }
    395230
     231            update_tables_to_database();
     232
    396233            res.end();
    397234        }
     
    412249            }
    413250
     251            update_tables_to_database();
     252
    414253            res.end();
    415254        }
     
    425264
    426265            const { success, table, player } = getTableAndPlayer(session_id);
     266
     267            if (table.started && !table.ended) {
     268                const d = Date.now();
     269
     270                if (d - table.lastActivity > 30000) {
     271                    if (table.players[table.turnIdx] !== undefined) {
     272                        table.players[table.turnIdx].isFolded = true;
     273
     274                        setNextPlayerIdx(table.id);
     275                    }
     276                }
     277            }
    427278
    428279            res.json({
  • pages/api/poker/tableSpecific.js

    raac3b2b r95ce58b  
    1 import { tables, deck } from './gameStates'
     1import { tables } from '../postgre/index';
     2
     3import { deck } from './gameStates'
    24
    35import { hands, getBestHandDetails } from './handEvaluations';
     
    6264    const tableIdx = tables.map(e=>e.id).indexOf(tableId);
    6365
    64     if (tables[tableIdx] !== undefined && !tables[tableIdx].ended) {
     66    if (tables[tableIdx] !== undefined && tables[tableIdx].started && !tables[tableIdx].ended) {
    6567        const table = tables[tableIdx];
    6668
     
    8082
    8183        if (table.turnTimeout !== null) clearTimeout(table.turnTimeout);
     84        table.prevTurnIdx = -2;
    8285
    8386        let counter = 10;
     
    9194            if (table.players[table.turnIdx] !== undefined && table.players[table.turnIdx].isSatDown && !table.players[table.turnIdx].isFolded) {
    9295                if (table.round >= 2 && table.players[table.turnIdx].credits === 0) continue;
    93 
    94                 let prevTurnIdx = table.turnIdx;
    95                 table.turnTimeout = setTimeout(() => {
    96                     if (prevTurnIdx === table.turnIdx) {
    97                         if (table.players[table.turnIdx] !== undefined) {
    98                             table.players[table.turnIdx].isFolded = true;
    99                            
    100                             setNextPlayerIdx(table.id);
    101                         }
    102                     }
    103                 }, 30000);
    10496
    10597                table.lastBet = getMaxBet(table.id) - table.players[table.turnIdx].betAmount;
     
    151143        table.round = 0;
    152144        table.turnIdx = -1;
     145        table.lastActivity = 0;
    153146        table.turnTimeout = null;
    154147        table.pot = 0;
     
    233226        table.started = false;
    234227        table.ended = true;
     228        if (table.turnTimeout !== null) clearTimeout(table.turnTimeout);
     229        table.turnTimeout = null;
    235230
    236231        table.onlyOnePlayerLeft = true;
     
    301296        table.started = false;
    302297        table.ended = true;
     298        if (table.turnTimeout !== null) clearTimeout(table.turnTimeout);
     299        table.turnTimeout = null;
    303300        if (table.ended && table.winners.length === 0) {
    304301            setWinner(table.id);
     
    327324                table.started = false;
    328325                table.ended = true;
     326                if (table.turnTimeout !== null) clearTimeout(table.turnTimeout);
     327                table.turnTimeout = null;
    329328            }
    330329
  • pages/api/postgre/index.js

    raac3b2b r95ce58b  
    66
    77const crypto = require('crypto');
     8
     9import { progressRoundTillTheEnd } from '../poker/tableSpecific';
    810
    911const Pool = require('pg').Pool
     
    1113  connectionString: `postgres://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASSWORD}@${process.env.POSTGRES_HOST}/${process.env.POSTGRES_DB}`
    1214});
    13 
    14 const sessions = []
    15 // example session = { id, displayName, username, credits, lastActivity }
    1615
    1716export default function handler(req, res) {
     
    9796          });
    9897        }
     98
     99        update_sessions_to_database();
    99100         
    100101        res.json({
     
    159160          }
    160161        });
     162
     163        update_sessions_to_database();
    161164
    162165        res.json({
     
    253256
    254257        axios.get(`${process.env.HOME_URL}/api/blackjack/?action=remove_room&session_id=${session_id}`);
     258
     259        update_sessions_to_database();
    255260      }
    256261
     
    427432                      lastActivity: Date.now(),
    428433                    }
    429                    
     434
    430435                    sessions.push(session);
     436
     437                    update_sessions_to_database();
    431438   
    432439                    res.json({
     
    453460  }
    454461}
     462
     463
     464/**
     465 * User session data
     466 */
     467export var sessions = []
     468
     469export function update_sessions_to_database() {
     470   pool.query('UPDATE sessions SET data = $1 WHERE identifier = $2', [JSON.stringify(sessions), 'sessions_data'], (error, results) => {
     471     if (error) throw error;
     472   });
     473}
     474   
     475export function load_sessions_from_database() {
     476   pool.query('SELECT data FROM sessions WHERE identifier = $1', ['sessions_data'], (error, results) => {
     477     if (error) throw error;
     478 
     479     sessions = JSON.parse(results?.rows[0]?.data || []);
     480   });
     481}
     482load_sessions_from_database();
     483 
     484 /**
     485  * Poker game data
     486  */
     487export var tables = []
     488 
     489export function cleanTables() {
     490   tables = [];
     491}
     492 
     493export function update_tables_to_database() {
     494   tables = tables.map(table => ({...table, turnTimeout: null}));
     495 
     496   pool.query('UPDATE poker SET data = $1 WHERE identifier = $2', [JSON.stringify(tables), 'poker_data'], (error, results) => {
     497     if (error) throw error;
     498   });
     499}
     500   
     501export async function load_tables_from_database() {
     502   pool.query('SELECT data FROM poker WHERE identifier = $1', ['poker_data'], (error, results) => {
     503       if (error) throw error;
     504 
     505       tables = JSON.parse(results?.rows[0]?.data || []);
     506 
     507       tables.forEach(table => {
     508         if (table.started) {
     509           progressRoundTillTheEnd(table.id);
     510         }
     511       })
     512 
     513       cleanTables();
     514 
     515       update_tables_to_database();
     516   });
     517}
     518load_tables_from_database();
Note: See TracChangeset for help on using the changeset viewer.