Java高級應用之斗地主游戲
斗地主綜合案例,供大家參考,具體內容如下
運用HashMap、ArrayList、List類實現斗地主綜合案例,模擬斗地主游戲的隨機發牌,并按照牌的大小和花色進行排列。
斗地主玩家每輪都有三個玩家,運用Collections類中的shuffle()方法打亂一整幅撲克牌,利用取余原理將湊亂的牌發放給三個玩家,整副牌發完后的最后三張永一個ArrayList存儲作為底牌。具體代碼實現如下:
import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.List;/***斗地主綜合案例:有序版本*1.準備牌*2.洗牌*3.發牌*4.排序*5.看牌**/public class DouDizhu02 { public static void main(String[] args) {//1。準備牌//創建一個Map集合,存儲牌的索引和組裝好的牌HashMap<Integer, String> poker = new HashMap<>();//List集合,存儲牌的索引ArrayList<Integer> pokerIndex = new ArrayList<>();//定義兩個集合,存儲花色和序號List<String> colors = List.of('♥', '♦', '♠', '♣');List<String> numbers = List.of('2', 'A', 'K', 'Q', 'J', '10', '9', '8', '7', '6', '5', '4','3');//把大王和小王存儲到集合中int index = 0;poker.put(index, '大王');pokerIndex.add(index);index++;poker.put(index, '小王');pokerIndex.add(index);index++;//循環嵌套52張牌for(String number: numbers){ for(String color : colors){poker.put(index, color + number);pokerIndex.add(index);index++; }}//System.out.println(poker);//System.out.println(pokerIndex);/*2.洗牌使用Collections中的方法shuffle(list) */Collections.shuffle(pokerIndex);/*3.發牌 *///定義四個集合,存儲玩家牌的索引,和底牌的索引ArrayList<Integer> player01 = new ArrayList<>();ArrayList<Integer> player02 = new ArrayList<>();ArrayList<Integer> player03 = new ArrayList<>();ArrayList<Integer> dipai = new ArrayList<>();//遍歷存儲牌索引的list集合,獲取每一個牌的索引for (int i = 0; i < pokerIndex.size(); i++) { Integer in = pokerIndex.get(i); if(in >= 51){dipai.add(in); }else if(i % 3 == 0){player01.add(in); }else if(i % 3 == 1){player02.add(in); }else if(i % 3 == 2){player03.add(in); }}/*4.排序使用Collections中的方法sort(List) */Collections.sort(player01);Collections.sort(player02);Collections.sort(player03);Collections.sort(dipai);/*5.看牌調用看牌的方法 */lookPoker('劉德華', poker, player01);lookPoker('周星馳', poker, player02);lookPoker('周潤發', poker, player03);lookPoker('底牌', poker, dipai); } /* 定義一個看牌的方法,提高代碼的復用性 參數: String name:玩家名稱 HashMap<Integer, String> poker:存儲牌的poker集合 ArrayList<Integer> list:存儲玩家和底牌的list集合 查表法: 遍歷玩家或者底牌集合,獲取牌的索引 使用牌的索引,去Map集合中找到對應的牌 */ public static void lookPoker(String name, HashMap<Integer, String> poker, ArrayList<Integer> list){//輸出玩家名稱,不換行System.out.print(name + ' :');for(int key : list){ String value = poker.get(key); System.out.print(value + ' ');}System.out.println(); }}
運行結果如下
牌為隨機打亂,每次運行結果都不一樣。
劉德華 :♥2 ♦2 ♠A ♦K ♠Q ♣Q ♥9 ♣9 ♥8 ♣8 ♦7 ♠7 ♣7 ♦6 ♣6 ♥5 ♠5 ♥3 周星馳 :♠2 ♥A ♦A ♣K ♦Q ♥J ♦J ♣J ♥10 ♦10 ♠10 ♦9 ♠9 ♦8 ♥7 ♠4 ♣4 周潤發 :大王 小王 ♣2 ♣A ♥K ♠K ♥Q ♠J ♣10 ♠8 ♥6 ♠6 ♦5 ♣5 ♥4 ♦4 底牌 :♦3 ♠3 ♣3
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: