【演算法】撲克發牌演算法實現

來源:互聯網
上載者:User

首先給撲克牌中每張牌設定一個編號,下面演算法實現的編號規則如下:
u 紅桃按照從小到大依次為:1-13
u 方塊按照從小到大依次為:14-26
u 黑桃按照從小到大依次為:27-39
u 梅花按照從小到大依次為:40-52
u 小王為53,大王為54
演算法實現如下:
u 首先按照以上編號規則初始化一個包含108個數位數組
u 每次隨機從該數組中抽取一個數字,分配給儲存玩家資料的數組
實現該功能的代碼如下所示: 複製代碼 代碼如下:import java.util.*;
/**
* 發牌演算法的實現
* 要求:把2副牌,也就是108張,發給4個人,留6張底牌
*/
public class Exec{
public static void main(String[] args){
//儲存108張牌的數組
int[] total = new int[108];
//儲存四個玩家的牌
int[][] player = new int[4][25];
//儲存當前剩餘牌的數量
int leftNum = 108;
//隨機數字
int ranNumber;
//隨機對象
Random random = new Random();

//初始化數組
for(int i = 0;i < total.length;i++){
total[i] = (i + 1) % 54;
//處理大小王編號
if(total[i] == 0){
total[i] = 54;
}

}

//迴圈發牌
for(int i = 0;i < 25;i++){
//為每個人發牌
for(int j = 0;j < player.length;j++){
//產生隨機下標
ranNumber = random.nextInt(leftNum);
//發牌
player[j][i] = total[ranNumber];
//移動已經發過的牌
total[ranNumber] = total[leftNum - 1];
//可發牌的數量減少1
leftNum--;
}
}

//迴圈輸出玩家手中的牌
for(int i = 0;i < player.length;i++){
for(int j = 0;j < player[i].length;j++){
System.out.print(" " + player[i][j]);
}
System.out.println();
}
//底牌
for(int i = 0;i < 8;i++){
System.out.print(" " + total[i]);
}
System.out.println();
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.