Java中使用HashMap,TreeSet和List来实现模拟斗地主的洗牌和发牌的小例子
生活随笔
收集整理的這篇文章主要介紹了
Java中使用HashMap,TreeSet和List来实现模拟斗地主的洗牌和发牌的小例子
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?模擬斗地主洗牌,發(fā)牌
?使用HashMap,TreeSet和List來實(shí)現(xiàn)
效果如下圖所示:
詳細(xì)實(shí)現(xiàn)代碼如下:
package star.july.tags;import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.TreeSet;/*** 模擬斗地主洗牌,發(fā)牌* 使用HashMap,TreeSet和List來實(shí)現(xiàn)* @author Starjuly**/ public class Poker {public static void main(String[] args) {//先把牌設(shè)置好String[] num = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};String[] size = {"方塊","梅花","紅桃","大葵"};HashMap<Integer, String> hm = new HashMap<Integer,String>();ArrayList<Integer> list = new ArrayList<Integer>(); int index = 0;//裝牌for(String s1 : num){for(String s2 : size){hm.put(index,s2.concat(s1));list.add(index);index++;}}//裝大王和小王hm.put(index, "小王");list.add(index);index++;hm.put(index, "大王");list.add(index);//洗牌:將集合中的順序打亂Collections.shuffle(list);//定義玩家和底牌TreeSet<Integer> GaoJin = new TreeSet<Integer>();TreeSet<Integer> LongWu = new TreeSet<Integer>();TreeSet<Integer> Me = new TreeSet<Integer>();TreeSet<Integer> DiPai = new TreeSet<Integer>();//將牌發(fā)給玩家和留3張底牌for(int i = 0 ; i < list.size() ; i++){if(i >= list.size() - 3){DiPai.add(list.get(i));}else if( i % 3 == 0){GaoJin.add(list.get(i));}else if( i % 3 == 1){LongWu.add(list.get(i));}else{Me.add(list.get(i));}}//遍歷每個(gè)玩家手中的牌lookPoker(hm, GaoJin, "高進(jìn)");lookPoker(hm, LongWu, "龍五");lookPoker(hm, Me, "自己");lookPoker(hm, DiPai, "底牌");}public static void lookPoker(HashMap<Integer, String> hm , TreeSet<Integer> ts,String name){System.out.print(name + " 手中的牌: ");for(Integer i : ts){ //用增強(qiáng)for循環(huán)遍歷TreeSet集合String poker = hm.get(i); //通過key找到HashMap中的值System.out.print(poker + " ");}System.out.println();} }
總結(jié)
以上是生活随笔為你收集整理的Java中使用HashMap,TreeSet和List来实现模拟斗地主的洗牌和发牌的小例子的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL数据库的常用操作
- 下一篇: JDBC的基本操作