java洗牌_java语言实现简单的洗牌,发牌
packagecom.java.lei.homework;importjava.util.Arrays;importjava.util.Random;public classPokerGame {//1.創(chuàng)建數(shù)組,用以存儲撲克牌
static String[] pokers = new String[54];public static voidmain(String[] args) {//2.創(chuàng)建牌 所有的牌賦值到array數(shù)組中
pokers =newPoker();//3.洗牌 這里的實(shí)參pokers是經(jīng)過創(chuàng)建牌之后新生成的pokers
String[] pokers2 =upsetPoker(pokers);//4.發(fā)牌
sendPoker(pokers2);
}//創(chuàng)建牌的方法
public staticString[] newPoker() {//1.定義花色數(shù)組
String[] colors = {"紅桃","黑桃","梅花","方片"};//2.定義牌面數(shù)組
String[] numbers = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};//3.定義王
String[] kings = {"大王","小王"};//4.使用循環(huán)將牌存儲到pokers數(shù)組
int index = 0;for(int i = 0 ; i < numbers.length ; i ++) {for(int j = 0 ; j < colors.length ; j ++) {
pokers[index++] = colors[j] +numbers[i];
}
}//5.大小王拷貝入pokers數(shù)組
System.arraycopy(kings, 0, pokers, index, 2);//6.輸出牌
System.out.println("現(xiàn)有一副撲克牌" + Arrays.toString(pokers) + "\n");returnpokers;
}//洗牌的方法
public staticString[] upsetPoker(String[] array) {//1.定義新的數(shù)組,用以存儲洗好的牌
String[] newpokers = newString[pokers.length];//2.定義數(shù)組,用以標(biāo)識被隨機(jī)取出的牌
boolean[] mark = new boolean[pokers.length];//3.洗牌
for(int i = 0 ; i < pokers.length ; i ++) {//a.創(chuàng)建隨機(jī)數(shù)
Random rd = newRandom();//b.獲取隨機(jī)數(shù)的下標(biāo)
int index =rd.nextInt(pokers.length);//c.判斷標(biāo)識
if(mark[index] == false) {//d.將未洗過的牌存儲入newpokers
newpokers[i] =pokers[index];//e.修改標(biāo)識,被洗過的牌標(biāo)記為true
}else{
i--; //該次取隨機(jī)數(shù)取到的是洗過的牌,則重新再取一次
}
}//newpokers內(nèi)的牌拷貝到數(shù)組pokers
pokers =Arrays.copyOf(newpokers, newpokers.length);
System.out.println("洗過的牌:" + Arrays.toString(newpokers)+"\n");returnnewpokers;
}//發(fā)牌的方法
public static voidsendPoker(String[] array) {//1.定義玩家及底牌數(shù)組
String[] one = new String[0];
String[] two= new String[0];
String[] three= new String[0];
String[] underpoker= new String[3];//2.循環(huán)進(jìn)行發(fā)牌
for(int i = 0 ; i < pokers.length-3 ; i++) {if(i % 3 == 0) {
one= Arrays.copyOf(one, one.length+1);
one[one.length-1] =pokers[i];
}else if(i % 3 == 1) {
two= Arrays.copyOf(two, two.length+1);
two[two.length-1] =pokers[i];
}else if(i % 3 == 2) {
three= Arrays.copyOf(three, three.length+1);
three[three.length-1] =pokers[i];
}
}
System.arraycopy(pokers, pokers.length-3, underpoker, 0, 3);
System.out.println("玩家1:" +Arrays.toString(one));
System.out.println("玩家2:" +Arrays.toString(two));
System.out.println("玩家3:" +Arrays.toString(three));
System.out.println("底牌:" +Arrays.toString(underpoker));
}
}
總結(jié)
以上是生活随笔為你收集整理的java洗牌_java语言实现简单的洗牌,发牌的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab 空矩阵耗时,性能 – 更快
- 下一篇: h5页面生成图片分享到微信js_html