此时我很困惑。 我正在制作纸牌游戏,不知道如何编写“交易”方法。 “交易”方法向玩家阵列中的每个玩家发放一定数量的牌。 我的deck类包含一个ArrayList:
public ArrayList<WarCard> cardStack = new ArrayList<WarCard>();
我已经为cardStack添加了52张预制卡。 我的播放器阵列有两个元素,播放器1和播放器2 ...... 我的问题是,如何将cardStack中的52张牌分配给玩家1或玩家2?我不知道从哪里开始...... 这就是我到目前为止所做的:
public void deal(WarPlayer[] players, int numberOfCards){
//whats the "certain number"? - suppose each one gets 26 cards - 1/2 of the total cards
numberOfCards=26;//26 cards go to each player
for(int i=0;i<26;i++){
players[i]=cardStack.get(i);
}
}
并且这段代码不能正常工作......正如预期的那样。 谢谢你的帮助!
答案 0 :(得分:0)
您可以使用以下代码编写代码:
// let's say you have a cardStack containing 52 cards
ArrayList<String> cardStack = new ArrayList<String>();
//you can shuffle the cards before dealing
shuffle(cardStack);
String[] players = new String[]{"player1", "player2"};
//this is the loop to deal cards to all players in the array
for (int i = 0; i < players.length; i++) {
// if you need to deal 10 cards to each player
for (int j = 0; j < 10; j++) {
players[i].addCard(cardStack.get(0)); // assuming your Player Object has an addCard method
// you will need to remove the card from the cardStack since you gave it to the player
cardStack.remove(0);
}
}
在每个玩家交易(对于此示例)10张牌之后,该列表将留下32张牌,每位玩家将拥有10张牌List
。
希望这有帮助
编辑:
编辑player[i].addCard(cardStack.get(j));
以确保玩家获得卡片上的第一张卡片。它应该是:
player[i].addCard(cardStack.get(0));