一、需求描述
完成斗地主游戏的案例开发。
业务:总共有54张牌;
点数:3、4、5、6、7、8、9、10、J、Q、K、A、2
花色:黑桃、红桃、方片、梅花
大小王:大王、小王
点数分别要组合4种花色,大小王各一张。
斗地主:每次发出51张牌,剩下3张作为底牌。
二、代码实现
2.1 Card类
package com.itheima.doudizhu;
public class Card {
private String number;//点数
private String color; //花色
private int size;//每张牌大小
public Card() {
}
public Card(String number, String color, int size) {
this.number = number;
this.color = color;
this.size = size;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
@Override
public String toString() {
return number + color;
}
}
2.2 Room类
package com.itheima.doudizhu;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Room {
//房间必须有一张牌
private List<Card> allCards = new ArrayList<>();
//每次进入房间,牌都是洗好的,所以在构造函数中实现
public Room() {
//1、整理好牌
//2、点数和花色都确定了,使用数组存储
String[] numbers = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
//使用数组存储花色
String[] colors = {"♠","♥","♣","♦"};
//代表每个点数的大小
int size = 0;
//3、获得每张牌对象
for (String number : numbers) {
size++;
for (String color : colors) {
Card c = new Card(number,color,size);
//将每张牌存入到整副牌中
allCards.add(c);
}
}
//存入小王和大王
Card c1 = new Card("","🃏",++size);
Card c2 = new Card("","🃏",++size);
//得到完整的一副牌
Collections.addAll(allCards,c1,c2);
//打印牌
System.out.println("新牌:" + allCards);
}
//游戏启动
public void start() {
//洗牌
Collections.shuffle(allCards);
System.out.println("洗牌后:" + allCards);
//给3个玩家发牌
List<Card> player1 = new ArrayList<>();
List<Card> player2 = new ArrayList<>();
List<Card> player3 = new ArrayList<>();
//依次发出51张牌,然后留3张牌作为底牌
for (int i = 0; i < allCards.size() - 3; i++) {
Card c = allCards.get(i);
if (i % 3 ==0) {
player1.add(c);
} else if (i % 3 == 1) {
player2.add(c);
} else if (i % 3 == 2) {
player3.add(c);
}
}
//对玩家的牌进行排序
SortCard(player1);
SortCard(player2);
SortCard(player3);
//看牌
System.out.println("1号玩家:" + player1);
System.out.println("2号玩家:" + player2);
System.out.println("3号玩家:" + player3);
//记录底牌
List<Card> threeCard = allCards.subList(allCards.size() - 3,allCards.size());
System.out.println("底牌:" + threeCard);
player2.addAll(threeCard);
SortCard(player2);
System.out.println("2号玩家抢到地主后:" + player2);
}
//对牌进行排序
private void SortCard(List<Card> cards) {
Collections.sort(cards, new Comparator<Card>() {
@Override
public int compare(Card o1, Card o2) {
return o1.getSize() - o2.getSize();//升序排序
}
});
}
}
2.3 Demo类
package com.itheima.doudizhu;
public class GameDemo {
public static void main(String[] args) {
//进入房间
Room room = new Room();
//游戏启动
room.start();
}
}