模拟打扑克洗牌代码

本文介绍如何用Java编程实现扑克牌的洗牌过程,将52张牌(不包含大小王)从有序状态随机打乱成无序状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

打扑克使用52张牌(大小王不算),由整齐的顺序随机洗到混乱的状态

package laojiu;

/**
 * 模拟实现洗牌的过程
 * @author QJ
 *@date 2020.7.9 晚上
 */
public class ShuffleCardsDome {
	public static void main(String[] args) {
		
		 final int N = 52;  //52张牌 
         int[] cards = new int[N];
         
         
         //牌的花色数组
         String[] cardColors = {"黑桃","红心","方块","梅花"};
         //牌面数组
         String[] cardValues = {
        		 "A","2","3","4","5","6","7","8","9","10",
        		 "J","Q","k"};
         
         for(int i = 0;i < cards.length;i++) {
        	 cards[i]=i; //牌面与变量的值一致,0-51之间
         }
         
         System.out.println("洗牌前:");
//         for ( i = 0; i < cards.length; i++) {   用“//”的代码,由数字演变成牌面数字                          花色的过程
//			System.out.print(cards[i]);
//			if((i+1) % 13 == 0) {
//				System.out.println();
//			}else {
//				System.out.print(",");
//			}
//         }
         for (int i = 0; i < cards.length; i++) {
 			//System.out.print(cards[i]);
         	 System.out.printf("%s-%s",cardColors[cards[i] / 13],cardValues[cards[i]%13]);
 			if((i+1) % 13 == 0) {
 				System.out.println();
 			}else {
 				System.out.print("\t");
 			}
 			}
 			
         
         //洗牌:随机生成一个0-51之间的数字newIndex,cards[i]和cards[newIndex]元素相交换
         for(int i=0;i<cards.length;i++) {
        	 int newIndex = (int)(Math.random()*N); //0-51之间的随机数字
        	 int temp = cards[i];
        	 cards[i] = cards[newIndex];
        	 cards[newIndex] = temp;
         }
         
//         //牌的花色数组
//         String[] cardColors = {"黑桃","红心","方块","梅花"};
//         //牌面数组
//         String[] cardValues = {
//        		 "A","2","3","4","5","6","7","8","9","10",
//        		 "J","Q","k"};
//         
         
         System.out.println("洗牌后:");
         for (int i = 0; i < cards.length; i++) {
			//System.out.print(cards[i]);
        	 System.out.printf("%s-%s",cardColors[cards[i] / 13],cardValues[cards[i]%13]);
        	 //cardColors[cards[i] / 13]结果只可能为:0[黑桃],1[红心],2[方块],3[梅花]
        	 //cardValues[card[i]%13]的结果可能为0,1,2,3,......11,12,13   分别代表A,2,3,4.....J,Q,K
			if((i+1) % 13 == 0) {
				System.out.println();
			}else {
				System.out.print("\t");
			}
        	 
        	 
		}
        }
	}
上面代码的控制台:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200710125900928.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0NocmlzX3Fq,size_16,color_FFFFFF,t_70)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200710130009446.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0NocmlzX3Fq,size_16,color_FFFFFF,t_70)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值