写一个Java代码模仿掼蛋规则的随机发牌,输出两副牌发给四个人的花色和牌号
时间: 2024-10-28 09:12:26 浏览: 54
在Java中,我们可以创建一个Deck类表示一副扑克牌,包含四种花色(红桃、黑桃、梅花、方块)和每种花色从A到K共13张牌。然后我们再创建一个Player类,模拟四个人。这里是一个简单的随机发牌的示例代码:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// 定义牌类
class Card {
String suit; // 花色
int rank; // 牌号
public Card(String suit, int rank) {
this.suit = suit;
this.rank = rank;
}
@Override
public String toString() {
return suit + rank;
}
}
// 定义牌组类
class Deck {
List<Card> cards;
public Deck() {
cards = new ArrayList<>();
for (String suit : "SHDC") { // SHD代表四种花色
for (int i = 1; i <= 13; i++) {
cards.add(new Card(suit, i));
}
}
}
public void shuffle() {
Collections.shuffle(cards);
}
public Card dealCard() {
if (cards.isEmpty()) {
throw new IllegalStateException("No more cards in the deck.");
}
return cards.remove(0);
}
}
// 定义玩家类
class Player {
private List<Card> hand;
public Player() {
hand = new ArrayList<>();
}
public void receiveCard(Card card) {
hand.add(card);
}
public String getHand() {
return hand.toString();
}
}
public class Main {
public static void main(String[] args) {
Deck deck = new Deck();
deck.shuffle();
Player player1 = new Player();
Player player2 = new Player();
Player player3 = new Player();
Player player4 = new Player();
for (int i = 0; i < 52; i += 2) { // 每次发两张牌
player1.receiveCard(deck.dealCard());
player2.receiveCard(deck.dealCard());
if (i + 2 < 52) { // 只有前两次发第三副牌
player3.receiveCard(deck.dealCard());
player4.receiveCard(deck.dealCard());
}
}
System.out.println("Player 1 Hand: " + player1.getHand());
System.out.println("Player 2 Hand: " + player2.getHand());
System.out.println("Player 3 Hand: " + (player3.getHand() != null ? player3.getHand() : "Not enough cards"));
System.out.println("Player 4 Hand: " + (player4.getHand() != null ? player4.getHand() : "Not enough cards"));
}
}
```
这个代码会随机打乱牌,并按照规则每次发两张牌给四个玩家。请注意,由于牌组大小固定,当牌发完后,后面的部分玩家可能会没有足够的牌。
阅读全文