今天闲着无聊,用基础的随机数,写一个简单的斗地主发牌,给需要用到的同学做一个参考。
package com.linlx.Individual.service;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class GameTest {
public static void main(String[] args) {
GameTest a = new GameTest();
a.createCards();
}
/**
* createCards(创建牌池)
* void
* @exception
* @since 1.0.0
*/
public void createCards(){
//创建牌池集合
List<String> cardsList = new ArrayList<>();
//生成各个花色牌组
for (int i = 0; i <= 4; i++) {
switch (i) {
case 0:
addCardsList("♠",13,cardsList);
break;
case 1:
addCardsList("♣",13,cardsList);
break;
case 2:
addCardsList("♥",13,cardsList);
break;
case 3:
addCardsList("◇",13,cardsList);
break;
default:
cardsList.add("大王");
cardsList.add("小王");
break;
}
}
/**
* 以下部分为显示牌组,可要可不要
* */
System.out.println("牌组长度:"+cardsList.size());
Iterator<String> it = cardsList.iterator();
System.out.print("牌池:");
while (it.hasNext()) {
System.out.print(it.next()+" ");
}
//调用发牌方法
giveOutCards(cardsList);
}
/**
* addCardsList(生成各个花色牌组)
* @param key
* @param len
* @param cardsList
* void
* @exception
* @since 1.0.0
*/
public void addCardsList(String key,int len,List<String> cardsList){
//开始生成花色牌组,并判断生成A,J,Q,K等特殊牌组
for (int j = 0; j < len; j++) {
switch (j) {
case 0:
cardsList.add(key+"A");
break;
case 10:
cardsList.add(key+"J");
break;
case 11:
cardsList.add(key+"Q");
break;
case 12:
cardsList.add(key+"K");
break;
default:
cardsList.add(key+(j+1));
break;
}
}
}
/**
* giveOutCards(发牌)
* @param cardsList
* void
* @exception
* @since 1.0.0
*/
public void giveOutCards(List<String> cardsList){
//创建玩家牌池集合
List<Set<String>> gamePlayerCards = new ArrayList<>();
//循环出三个玩家牌组
for (int i = 0; i < 3; i++) {
//创建玩家牌组
Set<String> setCar = new HashSet<>();
//开始循环没法发牌十七张
for (int j = 0; j < 17; j++) {
boolean flag = false;
while (flag == false) {
//生成一个从54-1的随机数,并减1,稍后作为获取牌池集合的下标
int index = (int)Math.round(Math.random()*cardsList.size()+1)-1;
//判断该次想要获取的牌是否是是已被发出
if(index < cardsList.size()&&cardsList.get(index)!=null){
//将拿到的牌加入至玩家牌组
setCar.add(cardsList.get(index));
//删除牌池中的牌
cardsList.remove(index);
//赋值,跳出循环
flag = true;
}
}
}
//添加至玩家牌池
gamePlayerCards.add(setCar);
}
/**
* 以下部分为显示牌组,可要可不要
* */
System.out.print("\n地主牌:");
for (String card : cardsList) {
System.out.print(card+" ");
}
System.out.println();
for (Set<String> cards : gamePlayerCards) {
Iterator<String> it = cards.iterator();
while (it.hasNext()) {
System.out.print(it.next()+" ");
}
System.out.println(" 牌组长度:"+cards.size());
}
}
}