请使用Java代码写一个斗地主小游戏
时间: 2024-04-27 09:22:58 浏览: 114
以下是一个简单的斗地主小游戏的Java代码实现,其中使用了Java集合类和随机数生成器:
```
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class DouDiZhuGame {
public static void main(String[] args) {
// 初始化一副扑克牌
List<String> poker = new ArrayList<>();
String[] colors = {"♠", "♥", "♣", "♦"};
String[] numbers = {"2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3"};
for (String color : colors) {
for (String number : numbers) {
poker.add(color + number);
}
}
poker.add("大王");
poker.add("小王");
// 洗牌
Collections.shuffle(poker);
// 发牌
List<String> player1 = new ArrayList<>();
List<String> player2 = new ArrayList<>();
List<String> player3 = new ArrayList<>();
List<String> bottomCards = new ArrayList<>();
for (int i = 0; i < poker.size(); i++) {
String card = poker.get(i);
if (i >= poker.size() - 3) {
bottomCards.add(card);
} else if (i % 3 == 0) {
player1.add(card);
} else if (i % 3 == 1) {
player2.add(card);
} else if (i % 3 == 2) {
player3.add(card);
}
}
// 查看初始牌面
System.out.println("玩家1的牌:" + player1);
System.out.println("玩家2的牌:" + player2);
System.out.println("玩家3的牌:" + player3);
System.out.println("底牌:" + bottomCards);
// 叫分
Scanner scanner = new Scanner(System.in);
int score = 0;
int highestScore = 0;
int highestScorePlayer = 0;
for (int i = 1; i <= 3; i++) {
System.out.print("玩家" + i + "是否叫分(0-不叫,1-1分,2-2分,3-3分):");
int callScore = scanner.nextInt();
if (callScore > highestScore) {
highestScore = callScore;
highestScorePlayer = i;
}
if (callScore > 0) {
score = callScore;
}
}
System.out.println("最高分:" + highestScore + ",玩家" + highestScorePlayer + "叫的分最高");
// 出牌
List<String> playerCards = new ArrayList<>();
if (highestScore > 0) {
if (highestScorePlayer == 1) {
playerCards.addAll(player1);
} else if (highestScorePlayer == 2) {
playerCards.addAll(player2);
} else if (highestScorePlayer == 3) {
playerCards.addAll(player3);
}
Collections.sort(playerCards);
System.out.println("玩家" + highestScorePlayer + "先出牌");
System.out.println("玩家" + highestScorePlayer + "的牌:" + playerCards);
System.out.print("请玩家" + highestScorePlayer + "出牌:");
String playedCard = scanner.next();
playerCards.remove(playedCard);
while (!playerCards.isEmpty()) {
System.out.print("请玩家" + (highestScorePlayer % 3 + 1) + "出牌:");
String nextPlayerCard = scanner.next();
if (playerCards.contains(nextPlayerCard)) {
playerCards.remove(nextPlayerCard);
highestScorePlayer = highestScorePlayer % 3 + 1;
} else {
System.out.println("出牌不符合规则,请重新出牌");
}
if (playerCards.isEmpty()) {
System.out.println("玩家" + highestScorePlayer + "赢了");
}
}
} else {
System.out.println("无人叫分,结束游戏");
}
}
}
```
这个小游戏实现了洗牌、发牌、叫分、出牌的基本功能,玩家可以通过命令行输入来进行操作。需要注意的是,这只是一个简单的示例,实际的斗地主游戏还需要考虑更多的细节和规则。
阅读全文