用java写一个多米诺发牌
时间: 2024-04-30 18:19:56 浏览: 141
以下是一个简单的Java多米诺牌发牌程序:
```java
import java.util.ArrayList;
import java.util.Collections;
public class Domino {
private int left;
private int right;
public Domino(int left, int right) {
this.left = left;
this.right = right;
}
public int getLeft() {
return left;
}
public int getRight() {
return right;
}
public String toString() {
return "[" + left + "|" + right + "]";
}
public static void main(String[] args) {
ArrayList<Domino> deck = new ArrayList<>();
for (int i = 0; i <= 6; i++) {
for (int j = i; j <= 6; j++) {
deck.add(new Domino(i, j));
}
}
Collections.shuffle(deck);
ArrayList<ArrayList<Domino>> hands = new ArrayList<>();
int numPlayers = 4;
for (int i = 0; i < numPlayers; i++) {
hands.add(new ArrayList<>());
}
int index = 0;
while (!deck.isEmpty()) {
hands.get(index).add(deck.remove(0));
index = (index + 1) % numPlayers;
}
for (int i = 0; i < numPlayers; i++) {
System.out.println("Player " + (i + 1) + ": " + hands.get(i));
}
}
}
```
首先,我们创建一个 `Domino` 类来表示多米诺牌,它有两个属性 `left` 和 `right` 分别表示左右两个点数。
然后,我们创建一个 `deck` 数组来存储所有的多米诺牌,并使用两个 `for` 循环来生成所有可能的多米诺牌。
接下来,我们将 `deck` 数组随机排序,以便发牌时每个玩家都有机会获得不同的多米诺牌。
我们创建一个 `hands` 数组来存储每个玩家的多米诺牌。然后,我们使用一个 `while` 循环来从 `deck` 数组中取出多米诺牌并将其分发给玩家,直到 `deck` 数组为空。
最后,我们使用一个 `for` 循环来打印每个玩家的多米诺牌。
阅读全文
相关推荐

















