I know you're only doing a simplified version of Yahtzee, so first, here is the simple way to check for three-of-a-kind:
if ((tar[0] == tar[1] && tar[1] == tar[2]) ||
(tar[1] == tar[2] && tar[2] == tar[3]) ||
(tar[2] == tar[3] && tar[3] == tar[4])) {
// found 3 of a kind
}
For a more full-blown version, there are a lot of points for various combinations of multiple-of-a-kind in the lower section:
- Three-Of-A-Kind
- Four-Of-A-Kind
- Full House (Three-Of-A-Kind + Two-Of-A-Kind)
- Yahtzee (Five-Of-A-Kind)
and for the extended Yatzy version (not Yahtzee):
- One-Pair (Two-Of-A-Kind)
- Two-Pair (Two-Of-A-Kind + Two-Of-A-Kind)
and for the upper section you need to count how many of a certain number is present.
So, you should start by doing the counts-by-number:
int[] count = new int[6];
for (int i = 0; i < 5; i++)
count[tar[i]-1]++;
Now find the top two counts:
int topIdx1 = 0, topIdx2 = 0;
for (int i = 1; i < 6; i++)
if (count[i] > count[topIdx1]) {
topIdx2 = topIdx1;
topIdx1 = i;
} else if (count[i] > count[topIdx2]) {
topIdx2 = i;
}
Now you can easily find your combination (and the points if doing Yatzy):
if (count[topIdx1] == 5) {
// Yahtzee
} else if (count[topIdx1] == 4) {
// Four-Of-A-Kind yatzyPoints = 4*(topIdx1+1)
} else if (count[topIdx1] == 3) {
if (count[topIdx2] == 2) {
// Full House yatzyPoints = 3*(topIdx1+1) + 2*(topIdx2+1)
} else {
// Three-Of-A-Kind yatzyPoints = 3*(topIdx1+1)
}
} else if (count[topIdx1] == 2) {
if (count[topIdx2] == 2) {
// Two-Pair yatzyPoints = 2*(topIdx1+1) + 2*(topIdx2+1)
} else {
// One-Pair yatzyPoints = 2*(topIdx1+1)
}
}
And for the upper section, the points are easily calculated:
points = number * count[number-1]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…