對不起,可能會令人困惑的標題,這是我可以想出來描述我遇到的問題最好的。無論如何,下至黃銅釘:我正在開發一個Java任務(是的,這是課堂作業,聽我說)來創建一個名爲FiveDice2.java的骰子游戲。我需要做的是讓它爲每個CPU和人類玩家分別擲出五個骰子,然後通過確定他們是否有一對,兩個一類,三個等等來確定哪個「玩家」贏得了遊戲。我的問題在於最後一部分。我似乎無法瞭解如何真正實現這一目標。如何查找隨機數組中有多少個值匹配?
我最好的想法是創建一個所有可能的滾動值的數組,1-6,並將骰子滾動與該數組進行比較,並跟蹤每個數字在單獨變量中獲得的匹配數量(int ones, int twos,int threes等),但是我越想到它,就越意識到需要進行多少驗證,而且我不禁感到自己並沒有走上正軌。
我最好的嘗試去有點像這樣:
public class FiveDice2
{
\t public static void main(String[] args)
\t {
//Declare arrays for cpu and player dice
Die[] cpuDice = new Die[5];
Die[] playerDice = new Die[5];
int possibleValues = new int[]{1,2,3,4,5,6};
int ones, twos, threes, fours, fives, sixes;
int cpuHand, playerHand;
\t \t //Instantiate five Dice objects for the "CPU"
for(cpu = 0; cpu < cpuDice.length; cpu++)
{
cpuDice[cpu] = new Die();
}
\t \t //Instantiate five more Dice objects for the player
for(p = 0; p < cpuDice.length; p++)
{
playerDice[p] = new Die();
}
\t \t //Print rules of game to the console
\t \t System.out.println("Dice Game");
\t \t System.out.println("Two sets of dice will be thrown.");
\t \t System.out.println("Winner is determined by who has the better \"hand\" of dice.");
\t \t System.out.println("Each combination in the table beats all the ones below it: ");
\t \t System.out.println("-Five of a kind");
\t \t System.out.println("-Four of a kind");
\t \t System.out.println("-Three of a kind");
\t \t System.out.println("-Pair");
\t \t System.out.println("If none of the above, whoever has the highest total wins.");
\t \t //Output values of the "CPU's" rolls
System.out.println("CPU dice:");
for(cpu = 0; cpu < cpuDice.length; cpu++)
{
System.out.println(cpuDice[cpu].getDieValue());
}
System.out.println();
\t \t //Output values of the player's rolls
System.out.println("Player dice:");
for(p = 0; p < playerDice.length; p++)
{
System.out.println(playerDice[p].getDieValue());
}
System.out.println();
for(int i = 0; i < possibleValues.length; ++i)
{
if(cpuDice[i] == possibleValues[i])
{
if(cpuDice[i] == 1)
{
ones++;
}
if(cpuDice[i] == 2)
{
twos++;
}
if(cpuDice[i] == 3)
{
threes++;
}
if(cpuDice[i] == 4)
{
fours++;
}
if(cpuDice[i] == 5)
{
fives++;
}
if(cpuDice[i] == 6)
{
sixes++;
}
}
if(playerDice[i] == possibleValues[i])
{
if(playerDice[i] == 1)
{
ones++;
}
if(playerDice[i] == 2)
{
twos++;
}
if(playerDice[i] == 3)
{
threes++;
}
if(playerDice[i] == 4)
{
fours++;
}
if(playerDice[i] == 5)
{
fives++;
}
if(playerDice[i] == 6)
{
sixes++;
}
}
}
\t }
}
這將是巨大的,如果有人可以幫助我瞭解我要去哪裏錯了或者我應該如何改變我考慮如何做到這一點;我不是要求得到一個答案,我只是想幫助我理解如何到達那裏。提前致謝。
滾動五個骰子後,嘗試排序值。這可以很容易地識別出一種類型和直線。 –