一、需求描述
完成斗地主游戏的案例开发。
业务:总共有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;}@Overridepublic 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>() {@Overridepublic 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();}
}