棋牌類游戲是目前比較火的游戲之一。今天本文就以實例形式實現洗牌游戲。本文實例所采用的算法是:遍歷每個位置上的牌,然后與隨機位置上的牌交換。
運行結果如下圖所示:
對于牌來講,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() + " "); } }}
希望本文所述實例對大家的算法學習能有所幫助。
新聞熱點
疑難解答