有趣的範例(一)-洗撲克牌

基本的撲克牌分成四個花色,梅花(Clubs)、磚塊(Diamonds)、愛心(Hearts)、黑桃(Spades),以及一到十三共五十二張牌。如果加上鬼牌的話一副撲克牌有54張。這個範例是扣除鬼牌之後每次執行程式都會隨機產生五十二張牌。

本文以C++實作執行。

標頭檔檔名:DeckOfCards.h

DeckOfCards是初始化52張牌為0,shuffle是洗牌,deal是發牌,

class DeckOfCards 
{
public:
	DeckOfCards();
	void shuffle();
	void deal();

private:
	int deck[4][13];
};

實作檔:DeckOfCards.cpp

#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <iostream>
#include "DeckOfCards.h"
using namespace std;


DeckOfCards::DeckOfCards()
{
	for (int row = 0; row <= 3; row++)
	{
		for (int column = 0; column <= 12; column++)
		{
			deck[row][column] = 0;
		}
	}
	srand(time(0));
}

void DeckOfCards::shuffle()
{
	int row;
	int column;

	for (int card = 1; card <= 52; card++)
	{
		do
		{
			row = rand() % 4;
			column = rand() % 13;
		} while (deck[row][column] != 0);

		deck[row][column] = card;
	}
}

void DeckOfCards::deal()
{
	static const char *suit[4] = { "Clubs","Diamonds","Hearts","Spades" };
	static const char *face[13] = {"Ace","Deuce","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"};

	for (int card = 1; card <= 52; card++)
	{
		for (int row = 0; row <= 3; row++)
		{
			for (int column = 0; column <= 12; column++)
			{
				if (deck[row][column] == card)
				{
					cout << setw(5) << right << face[column] << "of" << setw(8) << left << suit[row] << (card % 2 == 0 ? '\n' : '\t');
				}
			}
		}
	}
}

實作檔當中的

do
		{
			row = rand() % 4;
			column = rand() % 13;
		} while (deck[row][column] != 0);

是用來確保每一張都會不重複的存在deck的陣列中。

執行檔:Source.cpp

#include "DeckOfCards.h"
#include <iostream>
using namespace std;

int main() {
	DeckOfCards deckOfCards;
	deckOfCards.shuffle();
	deckOfCards.deal();
	system("pause");
	return 0;
}

執行結果如下:


 

有夢最美 築夢踏實

活在當下 認真過每一天

我是阿夢 也是Ace