Changeset 3a783f2 for pages


Ignore:
Timestamp:
07/05/22 16:36:24 (2 years ago)
Author:
anastasovv <simon@…>
Branches:
main
Children:
189cd8f
Parents:
b13f93b
Message:

Finished poker and added ball to roulette

Location:
pages/api
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • pages/api/poker/index.js

    rb13f93b r3a783f2  
    1111    creator: '',
    1212    started: false,
     13    ended: false,
    1314    round: 0,
    14     turnIdx: 0,
     15    turnIdx: -1,
     16    pot: 0,
    1517    lastBet: 0,
    1618    turnsSinceLastBet: 0,
     
    1820    deck: [],
    1921    cardsOnTable: [],
     22    winners: [],
     23    splitWinners: false,
     24    turnTimeout: null,
    2025}
    2126
     
    2631    displayName: '',
    2732    cards: [],
     33    hand: {
     34        hand: '',
     35        highCard: 0,
     36    },
    2837    betAmount: 0,
    2938    isSatDown: false,
    3039    isCoordinator: false,
    3140    isFolded: false,
     41    isGhost: false,
     42    credits: 0,
    3243}
    3344
     
    4556                    "DA", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DX", "DJ", "DQ", "DK"    ];
    4657
     58const deck = [...singleDeck];
     59
    4760/* We are using 5 decks */
    48 const deck = singleDeck.concat(singleDeck).concat(singleDeck).concat(singleDeck).concat(singleDeck);
     61// const deck = singleDeck.concat(singleDeck).concat(singleDeck).concat(singleDeck).concat(singleDeck);
    4962
    5063/**
     
    8194}
    8295
    83 function setNextPlayerIdx(tableId) {
     96function getMaxBet(tableId) {
    8497    const tableIdx = tables.map(e=>e.id).indexOf(tableId);
    8598
     
    87100        const table = tables[tableIdx];
    88101
     102        let maxBet = 0;
     103        table.players.forEach(player => {
     104            if (player.betAmount > maxBet) {
     105                maxBet = player.betAmount;
     106            }
     107        })
     108       
     109        return maxBet;
     110    }
     111   
     112    return 0;
     113}
     114
     115function setNextPlayerIdx(tableId) {
     116    const tableIdx = tables.map(e=>e.id).indexOf(tableId);
     117
     118    if (tables[tableIdx] !== undefined) {
     119        const table = tables[tableIdx];
     120
     121        if (table.turnTimeout !== null) clearTimeout(table.turnTimeout);
     122
     123        let counter = 10;
     124
    89125        while (true) {
     126            counter--;
     127
    90128            table.turnIdx++;
    91129            table.turnIdx %= table.players.length;
    92130           
    93131            if (table.players[table.turnIdx] !== undefined && table.players[table.turnIdx].isSatDown && !table.players[table.turnIdx].isFolded) {
     132                if (table.round >= 2 && table.players[table.turnIdx].credits === 0) continue;
     133
     134                let prevTurnIdx = table.turnIdx;
     135                table.turnTimeout = setTimeout(() => {
     136                    if (prevTurnIdx === table.turnIdx) {
     137                        if (table.players[table.turnIdx] !== undefined) {
     138                            table.players[table.turnIdx].isFolded = true;
     139
     140                            setNextPlayerIdx(table.id);
     141                        }
     142                    }
     143                }, 30000);
     144
     145                table.lastBet = getMaxBet(table.id) - table.players[table.turnIdx].betAmount;
     146                if (table.round === 1 && getMaxBet(table.id) <= 20) table.lastBet = 20;
     147
    94148                return ;
    95149            }
     150
     151            if (counter <= 0) return ;
    96152        }
    97153    }
     
    113169            }
    114170        }
     171        else if (table.round > 2) {
     172            const card = drawASingleCard(table.id);
     173                           
     174            if (card !== undefined) {
     175                table.cards.push(card);
     176            }
     177        }
     178    }
     179}
     180
     181function resetGame(tableId) {
     182    const tableIdx = tables.map(e=>e.id).indexOf(tableId);
     183
     184    if (tables[tableIdx] !== undefined) {
     185        const table = tables[tableIdx];
     186
     187        table.started = false;
     188        table.ended = false;
     189        table.round = 0;
     190        table.turnIdx = 0;
     191        table.turnTimeout = null;
     192        table.pot = 0;
     193        table.lastBet = 20;
     194        table.turnsSinceLastBet = 0;
     195        table.deck = [...deck];
     196
     197        table.players = table.players.filter(e=>e.isGhost === false);
     198
     199        table.players.forEach(player => {
     200            player.credits = 0;
     201            player.cards = [];
     202            player.isFolded = false;
     203            player.betAmount = 0;
     204            player.wonAmount = 0;
     205            player.hand = {
     206                hand: '',
     207                highCard: 0,
     208            }
     209        })
     210        table.winners = [];
     211        table.splitWinners = false;
     212        table.cards = [];
     213    }
     214}
     215
     216function giveMoneyToTheWinners(tableId) {
     217    const tableIdx = tables.map(e=>e.id).indexOf(tableId);
     218
     219    if (tables[tableIdx] !== undefined) {
     220        const table = tables[tableIdx];
     221
     222        const satDownPlayers = table.players.filter(e => e.isSatDown === true);
     223        const satDownCount = satDownPlayers.length;
     224
     225        table.players.forEach(player => {
     226            let winnings = 0;
     227            if (table.winners.indexOf(player) !== -1) {
     228                // winner
     229                winnings = 0;
     230                table.players.forEach(tmpPlayer => {
     231                    winnings += Math.min(tmpPlayer.betAmount, player.betAmount);
     232                })
     233
     234                axios.get(`${process.env.HOME_URL}/api/postgre/?action=add_credits&session_id=${player.id}&credits=${winnings}&game=poker&outcome=won`).then(postgreRes => {
     235                    if (postgreRes.data?.success) {
     236                        player.credits = postgreRes.data?.credits;
     237                    }
     238                });
     239            }
     240            else {
     241                // loser
     242                winnings = player.betAmount;
     243                table.players.forEach(tmpPlayer => {
     244                    if (table.winners.indexOf(tmpPlayer) !== -1) {
     245                        winnings -= tmpPlayer.betAmount;
     246                    }
     247                })
     248
     249                axios.get(`${process.env.HOME_URL}/api/postgre/?action=add_credits&session_id=${player.id}&credits=${winnings}&game=poker&outcome=lost`).then(postgreRes => {
     250                    if (postgreRes.data?.success) {
     251                        player.credits = postgreRes.data?.credits;
     252                    }
     253                });
     254            }
     255
     256            player.wonAmount = winnings;
     257        })
     258
     259        setTimeout(() => {
     260            resetGame(table.id);
     261        }, 15000);
     262    }
     263}
     264
     265function setWinner(tableId) {
     266    const tableIdx = tables.map(e=>e.id).indexOf(tableId);
     267
     268    if (tables[tableIdx] !== undefined) {
     269        const table = tables[tableIdx];
     270
     271        table.turnIdx = -1;
     272
     273        table.players.forEach(player => {
     274            if (player.isSatDown && !player.isFolded) {
     275                player.hand = getHandDetails(player.cards.concat(table.cards))
     276            }
     277        })
     278
     279        hands.forEach(hand => {
     280            const playerHands = table.players.filter(e=>e.hand.hand === hand);
     281
     282            if (table.winners.length === 0) {
     283                if (playerHands.length === 1) {
     284                    table.winners.push(playerHands[0])
     285                }
     286                else if (playerHands.length > 1) {
     287                    let tmp = playerHands[0].hand.highCard;
     288                    let tmpWinners = [];
     289
     290                    playerHands.forEach(player => {
     291                        if (player.hand.highCard > tmp) {
     292                            tmp = player.hand.highCard;
     293                        }
     294                    })
     295
     296                    playerHands.forEach(player => {
     297                        if (player.hand.highCard === tmp) {
     298                            tmpWinners.push(player);
     299                        }
     300                    })
     301
     302                    if (tmpWinners.length > 1) table.splitWinners = true;
     303                    table.winners = [...tmpWinners];
     304                }
     305            }
     306        })
     307
     308        giveMoneyToTheWinners(table.id);
     309    }
     310}
     311
     312function progressRoundIfNeeded(tableId) {
     313    const tableIdx = tables.map(e=>e.id).indexOf(tableId);
     314
     315    if (tables[tableIdx] !== undefined) {
     316        const table = tables[tableIdx];
     317
     318        const satDownPlayers = table.players.filter(e=>e.isSatDown === true);
     319        const remainingPlayers = satDownPlayers.filter(e=>e.isFolded === false);
     320
     321        if (table.turnsSinceLastBet === remainingPlayers.length) {
     322            table.round++;
     323            table.lastBet = 0;
     324            table.turnsSinceLastBet = 0;
     325
     326            if (table.round <= 4) {
     327                getCardsOnTable(table.id);
     328            }
     329            else {
     330                table.ended = true;
     331            }
     332
     333            if (table.ended && table.winners.length === 0) {
     334                setWinner(table.id);
     335            }
     336        }
    115337    }
    116338}
     
    129351        creator: playerName,
    130352        started: false,
     353        ended: false,
    131354        round: 0,
    132         turnIdx: 0,
     355        turnIdx: -1,
     356        pot: 0,
    133357        lastBet: 20,
    134358        turnsSinceLastBet: 0,
     
    137361            id: playerId,
    138362            table: tableId,
     363            credits: 0,
    139364            status: '_1_just_entered',
    140365            displayName: playerName,
    141366            cards: [],
    142367            betAmount: 0,
     368            wonAmount: 0,
    143369            isSatDown: false,
    144370            isCoordinator: true,
    145371            isFolded: false,
     372            isGhost: false,
     373            hand: {
     374                hand: '',
     375                highCard: 0,
     376            },
    146377        }],
     378        winners: [],
     379        splitWinners: false,
    147380        cards: [],
    148381    }
     
    167400        });
    168401
     402        let tmpWinners = [];
     403        table.winners.forEach(winner => {
     404            tmpWinners.push({
     405                ...winner,
     406                id: '',
     407                table: '',
     408                cards: '',
     409            })
     410        });
     411
    169412        let tmp = {
    170413            ...table,
    171414            deck: [],
    172415            players: tmpPlayers,
     416            winners: tmpWinners,
     417            turnTimeout: null,
    173418        }
    174419
     
    201446                    id: '',
    202447                    table: '',
    203                     cards: player.cards.length > 0 ? ['back', 'back'] : '',
     448                    cards: table.ended ? player.cards : player.cards.length > 0 ? ['back', 'back'] : '',
    204449                })
    205450            }
    206451        });
    207452
     453        let tmpWinners = [];
     454        table.winners.forEach(winner => {
     455            if (winner.id === session_id) {
     456                tmpWinners.push({
     457                    ...winner,
     458                    id: '',
     459                    table: '',
     460                })
     461            }
     462            else {
     463                tmpWinners.push({
     464                    ...winner,
     465                    id: '',
     466                    table: '',
     467                    cards: table.ended ? winner.cards : winner.cards.length > 0 ? ['back', 'back'] : '',
     468                })
     469            }
     470        });
    208471        result = {
    209472            ...table,
    210473            players: tmpPlayers,
     474            winners: tmpWinners,
     475            turnTimeout: null,
    211476        }
    212477    }
     
    227492function getTableAndPlayer(session_id) {
    228493    for (let tableIdx = 0; tableIdx < tables.length; tableIdx++) {
    229         const playerIdx = tables[tableIdx].players.map(e=>e.id).indexOf(session_id);
     494        const playerIdx = tables[tableIdx].players.filter(e=>e.isGhost === false).map(e=>e.id).indexOf(session_id);
    230495
    231496        if (playerIdx !== -1) {
     
    269534            const { success, table, player } = getTableAndPlayer(req.query.session_id)
    270535
    271             if (success && table.started) {
     536            if (success && table.started && !table.ended && player.isSatDown && !player.isFolded) {
    272537                if (table.players.map(e=>e.id).indexOf(req.query.session_id) !== table.turnIdx) {
    273538                    res.end();
     
    277542                let okayToGo = false;
    278543
    279                 const satDownPlayers = table.players.filter(e=>e.isSatDown === true);
    280                 const remainingPlayers = satDownPlayers.filter(e=>e.folded === false);
    281 
    282544                if (req.query.specificAction === 'check') {
    283 
     545                    if (table.lastBet === 0) {
     546                        table.turnsSinceLastBet++;
     547                        okayToGo = true;
     548                       
     549                        progressRoundIfNeeded(table.id);
     550                    }
    284551                }
    285552                else if (req.query.specificAction === 'call') {
    286                     player.betAmount += table.lastBet;
    287                     table.turnsSinceLastBet++;
     553                    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 => {
     554                        if (postgreRes.data?.success) {
     555                            player.credits = postgreRes.data?.credits;
     556
     557                            if (player.credits >= table.lastBet)
     558                                player.betAmount += table.lastBet;
     559                            else
     560                                player.betAmount += player.credits;
     561                               
     562                            table.pot += table.lastBet;
     563                            table.turnsSinceLastBet++;
     564                            okayToGo = true;
     565       
     566                            progressRoundIfNeeded(table.id);
     567                        }
     568                    });
     569                }
     570                else if (req.query.specificAction === 'raise') {
     571                    const betAmount = parseInt(req.query.betAmount);
     572
     573                    if (betAmount >= table.lastBet) {
     574                        await axios.get(`${process.env.HOME_URL}/api/postgre/?action=take_credits&session_id=${req.query.session_id}&credits=${betAmount}&takeWhatYouCan=true`).then(postgreRes => {
     575                            if (postgreRes.data?.success) {
     576                                player.credits = postgreRes.data?.credits;
     577
     578                                player.betAmount += betAmount;
     579                                table.pot += betAmount;
     580                                table.turnsSinceLastBet = 1;
     581                                okayToGo = true;
     582                               
     583                                progressRoundIfNeeded(table.id);
     584                            }
     585                        });
     586                    }
     587                }
     588                else if (req.query.specificAction === 'fold') {
     589                    player.isFolded = true;
    288590                    okayToGo = true;
    289591
    290                     if (table.turnsSinceLastBet === remainingPlayers.length) {
    291                         table.round++;
    292                         table.lastBet = 0;
    293 
    294                         getCardsOnTable(table.id);
    295                     }
    296                 }
    297                 else if (req.query.specificAction === 'raise') {
    298                    
    299                 }
    300                 else if (req.query.specificAction === 'fold') {
    301                     player.folded = true;
     592                    progressRoundIfNeeded(table.id);
    302593                }
    303594
     
    320611
    321612            if (success && !table.started) {
     613                table.players.forEach(player => {
     614                    axios.get(`${process.env.HOME_URL}/api/postgre/?action=check_if_logged_in&session_id=${player.id}`).then(postgreRes => {
     615                        if (postgreRes.data?.success) {
     616                            player.credits = postgreRes.data?.credits;
     617                        }
     618                    });
     619                })
     620
    322621                table.started = true;
    323622                table.round = 1;
    324623
    325                 const satDownPlayers = table.players.filter(e=>e.isSatDown === true);
    326 
    327                 table.turnIdx = Math.floor(Math.random(0, satDownPlayers.length))
     624                table.turnIdx = Math.floor(Math.random(0, table.players.length))
     625                setNextPlayerIdx(table.id);
    328626
    329627                table.players.forEach(player => {
     
    363661         * /---------------------- GET ----------------------/
    364662         * Creates the table and enters the user inside
     663         * @action leave_table
     664         * @param session_id
     665         */
     666         if (req.query.action === 'leave_table' && req.query?.session_id) {
     667            const { success, table, player } = getTableAndPlayer(req.query.session_id);
     668
     669            if (success) {
     670                player.isGhost = true;
     671                player.isFolded = true;
     672
     673                if (table.players[table.turnIdx] !== undefined && table.players[table.turnIdx] === player) {
     674                    setNextPlayerIdx(table.id);
     675                }
     676            }
     677
     678            res.end();
     679        }
     680
     681        /**
     682         * /---------------------- GET ----------------------/
     683         * Creates the table and enters the user inside
    365684         * @action join_a_table
    366685         * @param session_id
     
    375694                    const table = getTable(req.query.tableId)
    376695
    377                     if (!table.started) {
     696                    if (table !== undefined && !table.started) {
    378697                        table.players.push({
    379698                            ...samplePlayer,
     
    459778 * ********************* END OF REQUEST HANDLER *********************
    460779 */
     780
     781const hands = [
     782    'Royal Flush',
     783    'Straight Flush',
     784    'Four of a Kind',
     785    'Full House',
     786    'Flush',
     787    'Straight',
     788    'Three of a Kind',
     789    'Two Pairs',
     790    'Pair',
     791    'High Card',
     792]
     793
     794const order = "23456789TJQKA"
     795function getHandDetails(hand) {
     796    const cards = hand
     797    const faces = cards.map(a => String.fromCharCode([77 - order.indexOf(a[1])])).sort()
     798    const suits = cards.map(a => a[0]).sort()
     799    const counts = faces.reduce(count, {})
     800    const duplicates = Object.values(counts).reduce(count, {})
     801    const flush = suits[0] === suits[4]
     802    const first = faces[0].charCodeAt(1)
     803    const straight = faces.every((f, index) => f.charCodeAt(1) - first === index)
     804    let rank =
     805        (flush && straight && 1) ||
     806        (duplicates[4] && 2) ||
     807        (duplicates[3] && duplicates[2] && 3) ||
     808        (flush && 4) ||
     809        (straight && 5) ||
     810        (duplicates[3] && 6) ||
     811        (duplicates[2] > 1 && 7) ||
     812        (duplicates[2] && 8) ||
     813        9;
     814
     815    return { hand: hands[rank], highCard: faces.sort(byCountFirst).join("") }
     816
     817    function byCountFirst(a, b) {
     818        //Counts are in reverse order - bigger is better
     819        const countDiff = counts[b] - counts[a]
     820        if (countDiff) return countDiff // If counts don't match return
     821        return b > a ? -1 : b === a ? 0 : 1
     822    }
     823
     824    function count(c, a) {
     825        c[a] = (c[a] || 0) + 1
     826        return c
     827    }
     828}
     829
     830function getCardCombinations(playerCards, tableCards) {
     831    let combinations = [];
     832
     833    combinations.push([playerCards[0], tableCards[0], tableCards[1], tableCards[2], tableCards[3]])
     834    combinations.push([playerCards[0], tableCards[0], tableCards[1], tableCards[2], tableCards[4]])
     835
     836    combinations.push([playerCards[0], tableCards[0], tableCards[1], tableCards[4], tableCards[3]])
     837    combinations.push([playerCards[0], tableCards[0], tableCards[4], tableCards[2], tableCards[3]])
     838    combinations.push([playerCards[0], tableCards[4], tableCards[1], tableCards[2], tableCards[3]])
     839
     840   
     841    combinations.push([playerCards[1], tableCards[0], tableCards[1], tableCards[2], tableCards[3]])
     842    combinations.push([playerCards[1], tableCards[0], tableCards[1], tableCards[2], tableCards[4]])
     843
     844    combinations.push([playerCards[1], tableCards[0], tableCards[1], tableCards[4], tableCards[3]])
     845    combinations.push([playerCards[1], tableCards[0], tableCards[4], tableCards[2], tableCards[3]])
     846    combinations.push([playerCards[1], tableCards[4], tableCards[1], tableCards[2], tableCards[3]])
     847
     848
     849    combinations.push([playerCards[0], playerCards[1], tableCards[0], tableCards[1], tableCards[2]])
     850    combinations.push([playerCards[0], playerCards[1], tableCards[0], tableCards[1], tableCards[3]])
     851    combinations.push([playerCards[0], playerCards[1], tableCards[0], tableCards[1], tableCards[4]])
     852
     853    combinations.push([playerCards[0], playerCards[1], tableCards[0], tableCards[2], tableCards[3]])
     854    combinations.push([playerCards[0], playerCards[1], tableCards[0], tableCards[2], tableCards[4]])
     855    combinations.push([playerCards[0], playerCards[1], tableCards[0], tableCards[3], tableCards[4]])
     856
     857    combinations.push([playerCards[0], playerCards[1], tableCards[1], tableCards[2], tableCards[3]])
     858    combinations.push([playerCards[0], playerCards[1], tableCards[1], tableCards[2], tableCards[4]])
     859    combinations.push([playerCards[0], playerCards[1], tableCards[1], tableCards[3], tableCards[4]])
     860
     861    combinations.push([playerCards[0], playerCards[1], tableCards[2], tableCards[3], tableCards[4]])
     862
     863
     864    return combinations;
     865}
  • pages/api/postgre/index.js

    rb13f93b r3a783f2  
    8282                }
    8383              }
     84              else if (req.query?.game === 'poker') {
     85                if (req.query?.outcome === 'lost') {
     86                  pool.query('UPDATE stats SET poker_games = $1 WHERE username = $2', [parseInt(stats.poker_games) + 1, session.username], (error, results) => {
     87                    if (error) throw error;
     88                  });
     89                }
     90                else if (req.query?.outcome === 'won') {
     91                  pool.query('UPDATE stats SET poker_games = $1, poker_won_games = $2 WHERE username = $3', [parseInt(stats.poker_games) + 1, parseInt(stats.poker_won_games) + 1, session.username], (error, results) => {
     92                    if (error) throw error;
     93                  });
     94                }
     95              }
    8496            }
    8597          });
     
    110122      const session = sessions.find(session => session.id === session_id)
    111123
     124      let takeWhatYouCan = false;
     125      if (req.query?.takeWhatYouCan === "true") takeWhatYouCan = true;
     126
    112127      if (session) {
    113128        session.lastActivity = Date.now();
    114129
    115         session.credits = session.credits - parseInt(req.query.credits)
     130        if (session.credits < parseInt(req.query.credits)) {
     131          if (takeWhatYouCan) {
     132            session.credits = 0;
     133          }
     134          else {
     135            res.json({
     136              success: false,
     137            });
     138
     139            return ;
     140          }
     141        }
     142        else {
     143          session.credits = session.credits - parseInt(req.query.credits)
     144        }
    116145
    117146        pool.query('UPDATE players SET credits = $1 WHERE username = $2', [session.credits, session.username], (error, results) => {
Note: See TracChangeset for help on using the changeset viewer.