用java语言编写一个4个玩家玩的2副扑克牌的游戏
时间: 2024-03-17 15:41:43 浏览: 72
java实现简易扑克牌游戏
好的,下面是一个简单的Java代码示例,实现了4个玩家玩2副扑克牌的游戏。该游戏使用了Java的面向对象编程思想,包括类和对象的概念。
```java
import java.util.ArrayList;
import java.util.Collections;
public class PokerGame {
public static void main(String[] args) {
// 创建两副扑克牌
Deck deck1 = new Deck();
Deck deck2 = new Deck();
// 洗牌
deck1.shuffle();
deck2.shuffle();
// 创建四个玩家
Player player1 = new Player("Player 1");
Player player2 = new Player("Player 2");
Player player3 = new Player("Player 3");
Player player4 = new Player("Player 4");
// 发牌
for (int i = 0; i < 13; i++) {
player1.addCard(deck1.dealCard());
player2.addCard(deck2.dealCard());
player3.addCard(deck1.dealCard());
player4.addCard(deck2.dealCard());
}
// 输出每个玩家的牌
System.out.println(player1);
System.out.println(player2);
System.out.println(player3);
System.out.println(player4);
}
}
class Card {
private String suit; // 花色
private String rank; // 点数
public Card(String suit, String rank) {
this.suit = suit;
this.rank = rank;
}
public String getSuit() {
return suit;
}
public String getRank() {
return rank;
}
public String toString() {
return rank + " of " + suit;
}
}
class Deck {
private ArrayList<Card> cards;
public Deck() {
cards = new ArrayList<Card>();
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"};
for (String suit : suits) {
for (String rank : ranks) {
Card card = new Card(suit, rank);
cards.add(card);
}
}
}
public void shuffle() {
Collections.shuffle(cards);
}
public Card dealCard() {
if (cards.size() == 0) {
return null;
}
return cards.remove(0);
}
}
class Player {
private String name;
private ArrayList<Card> hand;
public Player(String name) {
this.name = name;
hand = new ArrayList<Card>();
}
public void addCard(Card card) {
hand.add(card);
}
public String getName() {
return name;
}
public String toString() {
String result = name + ":\n";
for (Card card : hand) {
result += " " + card.toString() + "\n";
}
return result;
}
}
```
该程序包括三个类:Card、Deck和Player。Card类表示一张扑克牌,包括花色和点数;Deck类表示一副扑克牌,包括创建、洗牌和发牌等操作;Player类表示一个玩家,包括添加牌和输出牌等操作。
程序首先创建两副扑克牌,并洗牌。然后创建四个玩家,分别发牌,最后输出每个玩家的牌。
阅读全文