java 编写斗地主
时间: 2023-10-17 12:10:30 浏览: 96
很好,学习 Java 编写斗地主是一个不错的练手项目。以下是一个简单的斗地主游戏框架,你可以在此基础上进行开发。
首先,我们需要定义一个 Card 类,表示一张扑克牌。
```java
public class Card {
private int suit; // 花色
private int rank; // 点数
public Card(int suit, int rank) {
this.suit = suit;
this.rank = rank;
}
public int getSuit() {
return suit;
}
public int getRank() {
return rank;
}
public String toString() {
return String.format("[%d,%d]", suit, rank);
}
}
```
接下来,我们定义一个 Deck 类,表示一副扑克牌。
```java
import java.util.*;
public class Deck {
private List<Card> cards;
public Deck() {
cards = new ArrayList<Card>();
for (int i = 0; i < 4; i++) {
for (int j = 1; j <= 13; j++) {
cards.add(new Card(i, j));
}
}
}
public void shuffle() {
Collections.shuffle(cards);
}
public List<Card> deal(int count) {
List<Card> hand = new ArrayList<Card>();
for (int i = 0; i < count; i++) {
hand.add(cards.remove(0));
}
return hand;
}
}
```
接下来,我们定义一个 Player 类,表示一个玩家。
```java
import java.util.*;
public class Player {
private String name;
private List<Card> hand;
public Player(String name) {
this.name = name;
hand = new ArrayList<Card>();
}
public String getName() {
return name;
}
public void addCards(List<Card> cards) {
hand.addAll(cards);
}
public List<Card> getCards() {
return hand;
}
public void sortCards() {
Collections.sort(hand, new Comparator<Card>() {
public int compare(Card c1, Card c2) {
if (c1.getRank() != c2.getRank()) {
return c1.getRank() - c2.getRank();
} else {
return c1.getSuit() - c2.getSuit();
}
}
});
}
}
```
最后,我们定义一个 Game 类,表示游戏本身。
```java
import java.util.*;
public class Game {
private Deck deck;
private List<Player> players;
public Game() {
deck = new Deck();
players = new ArrayList<Player>();
players.add(new Player("Player 1"));
players.add(new Player("Player 2"));
players.add(new Player("Player 3"));
}
public void dealCards() {
deck.shuffle();
for (Player player : players) {
player.addCards(deck.deal(17));
player.sortCards();
}
}
public void play() {
dealCards();
for (Player player : players) {
System.out.println(player.getName() + ": " + player.getCards());
}
}
public static void main(String[] args) {
Game game = new Game();
game.play();
}
}
```
以上是一个简单的斗地主游戏框架,你可以在此基础上进行扩展,增加游戏规则和交互逻辑,使其更加完整和有趣。
阅读全文