java利用集合完成斗地主的洗牌 发牌 排序 看牌功能
时间: 2023-12-20 17:21:27 浏览: 133
下面是利用Java集合实现斗地主的洗牌、发牌、排序和看牌功能的示例代码:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Doudizhu {
// 定义扑克牌的点数和花色
private static final String[] CARD_NUMBERS = { "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2", "小王", "大王" };
private static final String[] CARD_SUITS = { "♠", "♥", "♣", "♦" };
public static void main(String[] args) {
// 生成一副扑克牌
List<String> cards = generateCards();
// 洗牌
shuffleCards(cards);
// 发牌
Map<String, List<String>> players = dealCards(cards);
// 排序
sortCards(players);
// 看牌
showCards(players);
}
/**
* 生成一副扑克牌
*/
private static List<String> generateCards() {
List<String> cards = new ArrayList<>();
for (String suit : CARD_SUITS) {
for (String number : CARD_NUMBERS) {
cards.add(suit + number);
}
}
return cards;
}
/**
* 洗牌
*/
private static void shuffleCards(List<String> cards) {
Collections.shuffle(cards);
}
/**
* 发牌
*/
private static Map<String, List<String>> dealCards(List<String> cards) {
Map<String, List<String>> players = new HashMap<>();
players.put("player1", new ArrayList<>());
players.put("player2", new ArrayList<>());
players.put("player3", new ArrayList<>());
players.put("landlord", new ArrayList<>());
for (int i = 0; i < cards.size(); i++) {
String card = cards.get(i);
if (i >= cards.size() - 3) {
// 最后三张牌分给地主
players.get("landlord").add(card);
} else {
// 其他牌平均分给三个玩家
players.get("player" + (i % 3 + 1)).add(card);
}
}
return players;
}
/**
* 排序
*/
private static void sortCards(Map<String, List<String>> players) {
for (List<String> cards : players.values()) {
Collections.sort(cards, (c1, c2) -> {
int index1 = getIndex(c1);
int index2 = getIndex(c2);
if (index1 == index2) {
return c1.compareTo(c2);
} else {
return Integer.compare(index1, index2);
}
});
}
}
/**
* 获取扑克牌的点数
*/
private static int getIndex(String card) {
String number = card.substring(1);
switch (number) {
case "2":
return 13;
case "A":
return 12;
case "K":
return 11;
case "Q":
return 10;
case "J":
return 9;
case "10":
return 8;
case "9":
return 7;
case "8":
return 6;
case "7":
return 5;
case "6":
return 4;
case "5":
return 3;
case "4":
return 2;
case "3":
return 1;
default:
return 0;
}
}
/**
* 看牌
*/
private static void showCards(Map<String, List<String>> players) {
for (String player : players.keySet()) {
System.out.print(player + ": ");
List<String> cards = players.get(player);
for (String card : cards) {
System.out.print(card + " ");
}
System.out.println();
}
}
}
```
注:代码中使用的扑克牌样式可能在不同的操作系统和终端中显示略有不同。
阅读全文