分析:我们是要做一个斗地主的游戏。那么我们首先需要一个牌对象、一个房间对象。
1.我们需要准备好54张牌,而且每张牌都要有默认的大小。
2.我们需要洗牌,调用Collections.shuffle(allCards);
3.洗好牌需要发牌,直接for循环,但需要判断要发给谁,我们对i%3来解决。
4.接下来就是发地主牌,我们调用allCards.subList(allCards.size()-3,allCards.size())截取最后三张。
Card.class文件
package demo;
public class Card {
private String size;
private String color;
private int num;
public Card(){
}
public Card(String size,String color,int num){
this.size = size;
this.color = color;
this.num = num;
}
public String getSize() {
return size;
}
public String getColor() {
return color;
}
@Override
public String toString() {
return size + color;
}
public int getNum() {
return num;
}
}
Room.class文件
package demo;
import java.util.*;
public class Room {
//1.定义一个容器装54张牌
private List<Card> allCards = new ArrayList<>();
//2.装54张牌
{
//3.设置点数
String[] nums = {"3","4","5","6","7","8","9","10","J","Q","k","A","2"};
//4.设置花色
String[] colors = {"♠","♣ ","♥ ","♦"};
int count = 0;
for(String num :nums){
count++;
for(String color:colors){
Card card = new Card(num,color,count);
allCards.add(card);
}
}
allCards.add(new Card("","小",53));
allCards.add(new Card("","大",54));
System.out.println("新牌是:"+allCards);
}
public void start(){
//洗牌
Collections.shuffle(allCards);
System.out.println("洗牌后:"+allCards);
//定义三个玩家
Map<String,List<Card>> plays = new HashMap<>();
List<Card> a = new ArrayList<>();
List<Card> b = new ArrayList<>();
List<Card> c = new ArrayList<>();
plays.put("小明",a);
plays.put("小白",b);
plays.put("小红",c);
//发牌
for(int i = 0;i < allCards.size()-3;i++){
Card card = allCards.get(i);
if(i%3==0){
a.add(card);
}else if(i%3==1){
b.add(card);
}else{
c.add(card);
}
}
//拿最后三张底牌
List<Card> lastCards = allCards.subList(allCards.size()-3,allCards.size());
System.out.println("底牌为:"+lastCards);
//给玩家底牌
a.addAll(lastCards);
//给牌排序
a.sort((o1,o2)->o2.getNum()-o1.getNum());
b.sort((o1,o2)->o2.getNum()-o1.getNum());
c.sort((o1,o2)->o2.getNum()-o1.getNum());
HashSet set;
//看牌
for(Map.Entry<String, List<Card>> entry : plays.entrySet()){
System.out.println(entry.getKey()+"的牌是"+entry.getValue());
}
}
}