用java写一个多米诺游戏发牌
时间: 2023-12-19 07:04:53 浏览: 136
好的,以下是一个简单的 Java 多米诺游戏发牌的代码示例:
```java
import java.util.ArrayList;
import java.util.Collections;
public class DominoGame {
private ArrayList<DominoTile> deck; // 多米诺牌组
public DominoGame() {
deck = new ArrayList<>();
// 初始化多米诺牌组
for (int i = 0; i <= 6; i++) {
for (int j = i; j <= 6; j++) {
deck.add(new DominoTile(i, j));
}
}
}
// 打乱牌组
public void shuffleDeck() {
Collections.shuffle(deck);
}
// 发牌
public ArrayList<ArrayList<DominoTile>> deal(int numPlayers, int numTilesPerPlayer) {
ArrayList<ArrayList<DominoTile>> players = new ArrayList<>();
for (int i = 0; i < numPlayers; i++) {
players.add(new ArrayList<>());
}
for (int i = 0; i < numTilesPerPlayer; i++) {
for (int j = 0; j < numPlayers; j++) {
players.get(j).add(deck.remove(0)); // 从牌组中移除第一张牌并添加到玩家手牌中
}
}
return players;
}
public static void main(String[] args) {
DominoGame game = new DominoGame();
game.shuffleDeck();
ArrayList<ArrayList<DominoTile>> players = game.deal(4, 5);
System.out.println(players);
}
}
class DominoTile {
private int leftPip;
private int rightPip;
public DominoTile(int leftPip, int rightPip) {
this.leftPip = leftPip;
this.rightPip = rightPip;
}
public int getLeftPip() {
return leftPip;
}
public int getRightPip() {
return rightPip;
}
@Override
public String toString() {
return "[" + leftPip + "|" + rightPip + "]";
}
}
```
上述代码定义了一个 `DominoGame` 类表示多米诺游戏,其中包括了牌组的初始化、打乱牌组和发牌的方法。还定义了一个 `DominoTile` 类表示多米诺牌,包括了左右点数和 `toString()` 方法用于输出牌的字符串形式。`main()` 方法中演示了如何使用 `DominoGame` 类进行发牌。
阅读全文