Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
194
rated 0 times [  197] [ 3]  / answers: 1 / hits: 34944  / 11 Years ago, tue, july 23, 2013, 12:00:00

I'm trying to develop a simplified poker game through Javascript. I've listed all possible card combinations a given player might have in its hand ordered by its value, like this:



switch(sortedHand)
{
//Pair
case [1,1,4,3,2]: sortedHand.push(1,Pair); break;
case [1,1,5,3,2]: sortedHand.push(2,Pair); break;
case [1,1,5,4,2]: sortedHand.push(3,Pair); break;
case [1,1,5,4,3]: sortedHand.push(4,Pair); break;
case [1,1,6,3,2]: sortedHand.push(5,Pair); break;
case [1,1,6,4,2]: sortedHand.push(6,Pair); break;
case [1,1,6,4,3]: sortedHand.push(7,Pair); break;
case [1,1,6,5,2]: sortedHand.push(8,Pair); break;
case [1,1,6,5,3]: sortedHand.push(9,Pair); break;
case [1,1,6,5,4]: sortedHand.push(10,Pair); break;


Even though the sortedHand array stores values succesfully (as I've seen through console.log), the switch() statement always returns the default case, and everyone gets an straight flush. I fear this is a matter of the literal approach I've used to declare possible array values to be compared with the whole of sortedHand, but I don't know any better. Is it even possible to use switch() in such a manner?


More From » arrays

 Answers
13

You can try switching on a textual representation of the array.



switch(sortedHand.join(' '))
{
//Pair
case '1 1 4 3 2': sortedHand.push(1,Pair); break;
case '1 1 5 3 2': sortedHand.push(2,Pair); break;
case '1 1 5 4 2': sortedHand.push(3,Pair); break;
case '1 1 5 4 3': sortedHand.push(4,Pair); break;
// etc.
}


As an alternative to specifying every case directly, perhaps build a function dispatch table using an object and get rid of the switch entirely.



var dispatch = {};

// Build the table however you'd like, for your application
for (var i = 0; i < 10; i++) {
(function(i) {
var hand = ...; // Add your hand logic here
dispatch[hand] = function() { sortedHand.push(i, Pair); };
})(i);
}

// Execute your routine
dispatch[sortedHand.join(' ')]();

[#76801] Monday, July 22, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
juancarlos

Total Points: 580
Total Questions: 105
Total Answers: 103

Location: Grenada
Member since Sun, Dec 20, 2020
4 Years ago
;