生活随笔
收集整理的這篇文章主要介紹了
斗地主综合案例之有序版本
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一.項目要實現的目標
54張牌分發下去。達到3個玩家,每個玩家17張牌,3張底牌,牌面有序。見如下圖:
二.需求分析
1.準備牌
實現:
- 用集合number存儲{“2”,“A”,“K”,“Q”,“J”,“10”,“9”,“8”,“7”,“6”,“5”,“4”,“3”}
- 用集合color存儲{紅心,梅花,方塊,黑桃}
- 用兩個集合來組裝52張牌。52張牌加大王,小王構成 map集合
- 用map去存儲索引和牌
- 用indexList存儲map的索引
- 2.洗牌
*用Collections.shuffle(indexList) - 3.發牌
- 根據indexList的索引來發牌
- 索引i>=51 就當成底牌(3張) diPai
- i%3==0 就給玩家1發牌 player1
- i%3==1 就給玩家2發牌 player2
- i%3==2 就給玩家3發牌 player3
- 4.排序
- 根據集合中的元素(即hashMap的索引值),按數值升序排序,如此撲克牌自然就按按照有序規則排序
- 5.看牌
根據底牌,玩家1,玩家2,玩家3集合里面存儲的hashMap的索引值(鍵),從hashMap集合中找到對應的值,然后顯示就行
三,具體實現代碼
package dou
.di
.com
;
import java
.util
.*
;
public class DouDiZhuTest {public static void main(String
[] args
) {List
<String> number
= List
.of("2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3");List
<String> color
= List
.of("?", "?", "?", "?");HashMap
<Integer, String> map
= new HashMap<>();map
.put(0, "大王");map
.put(1, "小王");int index
= 2;for (String s
: number
) {for (String s1
: color
) {String string
= s1
+ s
;map
.put(index
, string
);index
++;}}
ArrayList
<Integer> indexList
= new ArrayList<>();Set
<Integer> keySet
= map
.keySet();for (Integer in
: keySet
) {indexList
.add(in
);}
Collections
.shuffle(indexList
);ArrayList
<Integer> diPai
= new ArrayList<>();ArrayList
<Integer> player1
= new ArrayList<>();ArrayList
<Integer> player2
= new ArrayList<>();ArrayList
<Integer> player3
= new ArrayList<>();
for (int i
= 0; i
< indexList
.size(); i
++) {Integer integer
= indexList
.get(i
);if (i
>= 51) {diPai
.add(integer
);} else if (i
% 3 == 0) {player1
.add(integer
);} else if (i
% 3 == 1) {player2
.add(integer
);} else if (i
% 3 == 2) {player3
.add(integer
);}}Collections
.sort(player1
);Collections
.sort(player2
);Collections
.sort(player3
);Collections
.sort(diPai
);look("周杰倫", map
, player1
);look("李小龍", map
, player2
);look("王安石", map
, player3
);look("底牌", map
, diPai
);}private static void look(String playName
, HashMap
<Integer, String> hashMap
, ArrayList
<Integer> integers
) {System
.out
.print(playName
+ ":");for (Integer key
: integers
) {String value
= hashMap
.get(key
);System
.out
.print(value
+ " ");}System
.out
.println();}}
總結
以上是生活随笔為你收集整理的斗地主综合案例之有序版本的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。