I'm new to programming and am using JavaScript to program a simple poker dice game with three randomly rolled die. The best possible hand is a straight ie 3, 4, 5. The problem I'm having is coding the method of deciding whether the three die are consecutive. At the moment the best I have come up with is:
if ((die3 === die2 + 1 && die2 === die1 + 1) ||
(die3 === die1 + 1 && die1 === die2 + 1) ||
(die2 === die3 + 1 && die3 === die1 + 1) ||
(die2 === die1 + 1 && die1 === die3 + 1) ||
(die1 === die3 + 1 && die3 === die2 + 1) ||
(die1 === die2 + 1 && die2 === die3 + 1))
This works, but seems very inelegant and would be a nightmare to scale up if I were to try to use more than three dice.
Any help with an alternative method would be greatly appreciated. Thanks.
It's easier if you work with an array. Either rearrange your code to use die[0]
instead of die1
, die[1]
for die2
, etc.
Once you have an array, you can do things like .sort()
it, and search it iteratively to find the numbers you're looking for.
For instance, after sorting numbers will be in order, so you just need to test for:
if( die[1] == die[0]+1 && die[2] == die[1]+1)
The idea of sorting an array is close to correct that people are doing; however, they are forgetting that there should not be any duplicates in that array. You should first sort them and then look for duplicates. Assume dice
is an array of your dice values.
// Assumes at least two dice
function isStraight(dice) {
dice.sort();
var duplicates = false;
for(var index = 0; index < dice.length - 1; index++) {
if(dice[index] == dice[index + 1]) {
duplicates = true;
break;
}
}
return !duplicates && (dice[dice.length - 1] - dice[0] == dice.length - 1);
}
Here's a jsFiddle with three simple tests (non exhaustive).
If you actually use this method, you should make a copy of the dice
array before sorting it. Unless you don't care if the dice array is changed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With