C#实现洗牌游戏实例
作者:shichen2014 时间:2021-07-07 00:45:29
棋牌类游戏是目前比较火的游戏之一。今天本文就以实例形式实现洗牌游戏。本文实例所采用的算法是:遍历每个位置上的牌,然后与随机位置上的牌交换。
运行结果如下图所示:
对于牌来讲,2个关键的因素是面值和类型(如红桃、梅花等)。
代码如下:
public class Card
{
private string mianzhi;
private string leixin;
public Card(string m, string l)
{
mianzhi = m;
leixin = l;
}
public override string ToString()
{
return leixin + " " + mianzhi;
}
}
客户端程序有3个方法,一个是初始化牌的数组,一个是遍历所有牌并显示,还有一个是使用算法洗牌。
具体实现代码如下:
class Program
{
private static Card[] allCards = new Card[52];
private static string[] ms = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };
private static string[] ls = { "红桃", "方块", "梅花", "黑桃" };
static void Main(string[] args)
{
Init();
ShowAllCards();
Console.WriteLine("\r\n");
Shuffle();
ShowAllCards();
Console.ReadKey();
}
private static void Shuffle()
{
Random r = new Random();
Card tempCard;
//依次遍历所有牌与随机位置上的牌交换位置
for (int i = 0; i < allCards.Length; i++)
{
int ran = r.Next(52);
tempCard = allCards[i];
allCards[i] = allCards[ran];
allCards[ran] = tempCard;
}
}
private static void Init()
{
for (int i = 0; i < allCards.Length; i++)
{
allCards[i] = new Card(ms[i % 13],ls[i%4]);
}
}
private static void ShowAllCards()
{
foreach (var item in allCards)
{
Console.Write(item.ToString() + " ");
}
}
}
希望本文所述实例对大家的算法学习能有所帮助。
标签:C#,游戏
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解SpringMVC @RequestBody接收Json对象字符串
2022-03-20 05:00:10
浅谈JAVA中输入输出流实例详解
2022-10-21 05:20:57
![](https://img.aspxhome.com/file/2023/1/81881_0s.png)
SpringMVC使用RESTful接口案例详解
2022-08-08 23:41:52
登陆验证码kaptcha结合spring boot的用法详解
2023-02-19 15:56:32
JAVA8 Stream流中的reduce()方法详解
2023-09-01 21:10:33
springboot如何实现自动装配源码解读
2023-11-10 15:44:20
在Eclipse中运行Solr 基础知识
2021-07-06 22:51:04
Mybatis Lombok使用方法与复杂查询介绍
2023-03-30 00:30:13
![](https://img.aspxhome.com/file/2023/4/68764_0s.png)
Java编程关于子类重写父类方法问题的理解
2022-05-25 05:00:32
![](https://img.aspxhome.com/file/2023/7/71837_0s.jpg)
SpringBoot外部化配置使用Plus版的方法示例
2022-12-21 01:03:46
SpringBoot文件上传控制及Java 获取和判断文件头信息
2021-12-10 16:47:20
![](https://img.aspxhome.com/file/2023/1/84771_0s.png)
BeanUtils.copyProperties在拷贝属性时忽略空值的操作
2022-07-11 05:22:04
java 中死锁问题的实例详解
2022-08-18 02:22:39
springboot+mybatis+redis 二级缓存问题实例详解
2022-08-09 09:06:36
![](https://img.aspxhome.com/file/2023/8/63148_0s.jpg)
Android中的常用尺寸单位(dp、sp)快速入门教程
2023-09-19 08:59:08
Android开发之DrawerLayout实现抽屉效果
2023-09-30 03:40:59
![](https://img.aspxhome.com/file/2023/5/85975_0s.png)
springboot与vue详解实现短信发送流程
2023-05-24 14:55:29
![](https://img.aspxhome.com/file/2023/5/97935_0s.png)
Java TreeMap排序算法实例
2023-02-25 10:26:20
基于jdk动态代理和cglib动态代理实现及区别说明
2022-04-11 00:32:44
Java Spring AOP源码解析之事务实现原理
2023-09-10 02:39:46
![](https://img.aspxhome.com/file/2023/5/66945_0s.png)