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