hello,我是忘鱼。
目录
前言
一、案例所需要具备知识
二、代码
2.运行结果
总结
前言
斗地主小游戏,属于Collection体系综合案例,学习帮助我们加深理解。
一、案例所需要具备知识
常用Arraylist常用操作,和一些基础知识。代码注释很详细,简单但很重要。
二、代码
代码如下(示例):
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;//斗地主游戏
public class GameDemo {
// 存取全部牌
public static List<Cards> allcards=new ArrayList<>();
//数量确定类型确定使用数组
static {String[] sizes={"3","4","5","6","7","8","9","10","J","Q","K","A","2"};String[] colors={"♣","♦","♥","♠"};int index=0;
// List继承了collection,使用foreach循环简单;for (String size : sizes) {index++;for (String color : colors) {
// 使用变量接取Cards c=new Cards(size,color,index);allcards.add(c);}}Cards c1=new Cards("","小🃏",++index);Cards c2=new Cards("","大🃏",++index);Collections.addAll(allcards,c1,c2);System.out.println("新牌是:"+allcards);
}public static void main(String[] args) {
//洗牌操作使用shuffleCollections.shuffle(allcards);System.out.println("洗牌后:"+allcards);
// 定义三个player,使用集合简单List<Cards> player01=new ArrayList<>();List<Cards> player02=new ArrayList<>();List<Cards> player03=new ArrayList<>();
// 发牌,留三张底牌for (int i = 0; i < allcards.size()-3; i++) {Cards c=allcards.get(i);
// 求3的余数,0,1,2if(i%3==0){player01.add(c);}else if(i%3==1){player02.add(c);}else if(i%3==2){player03.add(c);}}
// 进行大小排序;,使用方法简单;sort(player01);sort(player02);sort(player03);System.out.println("玩家1"+player01);System.out.println("玩家2"+player02);System.out.println("玩家3"+player03);
// 还有三张底牌,差点忘了,直接截取用sublist 包前不包后List<Cards> lastthreeCards=allcards.subList(allcards.size()-3,allcards.size());System.out.println("底牌三张"+lastthreeCards);}private static void sort(List<Cards> playercards) {Collections.sort(playercards, new Comparator<Cards>() {@Overridepublic int compare(Cards o1, Cards o2) {return o2.getIndex()- o1.getIndex();}});}
}
public class Cards {private String size;private String color;
// 定义牌自身属性大小判断本身大小private int index;public Cards() {}public Cards(String size, String color, int index) {this.size = size;this.color = color;this.index = index;}public String getSize() {return size;}public void setSize(String size) {this.size = size;}public String getColor() {return color;}public void setColor(String color) {this.color = color;}public int getIndex() {return index;}public void setIndex(int index) {this.index = index;}@Overridepublic String toString() {return (size+color);}
}
2.运行结果
。
总结
给个赞吧!!亲亲