Pure JavaScript poker hand analyzer to be used (also) in puzzle games

Read all posts about "" game
There are a lot of games you can make starting from a Poker card game. The most obvious is the poker itself, but there also are puzzle games which used Poker cards and rules in the gameplay, like Sage Solitaire. Anyway, no matter the kind of game you are about to make using Poker rules, you have to be able to check what’s in the players hand. I was sure I would have found a lot of scripts in the web, so I made some searches and the most popular examples out there are: Poker Hand Evaluator: the most complete in my opinion but needs a 124MB lookup table which makes it useless in HTML5 game development. Poker Evaluator: a nice example on jsfiddle using regular expressions but it only works with cards taken from a single deck, and in a puzzle game you can also have more than one deck or completely random cards such as two tens of hearts. Poker Hand Evaluator (yes, another): evaluates two hands of poker to see what’s the best. The code isn’t that clear but it’s a nice tool although it cannot manages completely random cards. Poker Hand Analyzer: the most clever analyzer I found, using bit & mathematical operations you can analyze your poker hands in less than 10 lines, but only works with a 52 cards deck. So I ended making my own engine capable of working with any card combination, including 5 of a kind, pairs with flush, and all and every five cards combination you can imagine. Have a try:
Play with the selectors and see your hand in real time. And this is the source code, easy and plain, you can port it to any language.
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div id = "table"></div>
<div id = "result" style = "font:normal 32px arial;margin:10px;"></div>

<script>

var hand = [];
var valuesArray = [];
var suitsArray = [];

function checkHand(){
     var resultString = "";
     for(var i = 0; i < 5; i++){
          hand[i] = document.getElementById("card_" + i).value;
     }
     convertHand();
     console.log(duplicateCards())
     switch(duplicateCards()){
          case "2":
               resultString = "1 Pair";
               break;
           case "22":
               resultString = "2 Pairs";
               break;
          case "3":
               resultString = "3 of a Kind";
               break;
          case "23":
          case "32":
               resultString = "Full House";
               break;
          case "4":
               resultString = "4 of a Kind";
               break;
          case "5":
               resultString = "5 of a Kind";
               break;
          default:
               if(isStraight()){
                    resultString = "Straight";     
               }
               if(isAceStraight()){
                    resultString = "Ace Straight";
               }
               break;
     }
     if(isFlush()){
          if(resultString){
               resultString += " and Flush";     
          }
          else{
               resultString = "Flush";
          }
     }
     if(!resultString){
          resultString = "nothing...";
     }
     document.getElementById("result").innerHTML = resultString;
}  

function convertHand(){
     for(var i = 0; i < 5; i ++){
          valuesArray[i] = hand[i] % 13;
          suitsArray[i] = Math.floor(hand[i] / 13);     
     }
}

function isFlush(){
     for(var i = 0; i < 4; i ++){
          if(suitsArray[i] != suitsArray[i+1]){
               return false;
          }
     }
     return true;
}

function isStraight(){
     var lowest = getLowest();
     for(var i = 1; i < 5; i++){
          if(occurrencesOf(lowest + i) != 1){
               return false
          }     
     }
     return true;
}

function isAceStraight(){
     var lowest = 9;
     for(var i = 1; i < 4; i++){
          if(occurrencesOf(lowest + i) != 1){
               return false
          }     
     }
     return occurrencesOf(1) == 0;
}

function getLowest(){
     var min = 12;
     for(var i = 0; i < valuesArray.length; i++){
          min = Math.min(min, valuesArray[i]);     
     }
     return min;     
} 

function duplicateCards(){
     var occurrencesFound = []; 
     var result = "";
     for(var i = 0; i < valuesArray.length; i++){
          var occurrences = occurrencesOf(valuesArray[i]);
          if(occurrences > 1 && occurrencesFound.indexOf(valuesArray[i]) == -1){
               result += occurrences; 
               occurrencesFound.push(valuesArray[i]);    
          }
     }
     return result;
}

function occurrencesOf(n){
     var count = 0;
     var index = 0;   
     do{          
          index = valuesArray.indexOf(n, index) + 1;  
          if(index == 0){
               break;
          }
          else{
               count ++;
          }
     } while(index < valuesArray.length);
     return count;
}  

</script>

<script>

     var cardSymbols = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
     var suitSymbols = ["?", "?", "?", "?"];
     var tableHTML = '';
     for(var j = 0; j < 5; j ++){
          tableHTML += '<select style = "padding:3px;font:normal 32px arial;margin:10px" id = "card_' + j + '" onchange = "checkHand();">';
          for(var i = 0; i < 52; i ++){
               tableHTML += '<option value = "' + i + '">' + cardSymbols[i % 13] + " " + suitSymbols[Math.floor(i / 13)] + '</option>';  
          }
          tableHTML += '</select>';   
     }
     document.getElementById("table").innerHTML = tableHTML;
     checkHand();
     
</script>

</body>
</html>
Hope this will be useful in your card games, I am making my own. Download the source code.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

215 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stairs
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers