一个面向对象设计的考试题,如何建模一副扑克牌
去掉王,剩下52张,写一个类,实现洗牌,发牌的功能
注意洗牌要能把牌洗得随机,
下面是我的简单的思路,0-51表示牌
class cards
{
public:
void shuffle()
{
for(int i=0;i<52; i++)
m_cards.push_back(i);
}
int send()
{
if(m_cards.size()==0)
return -1;
else if(m_cards.size()==1)
{
int tmp=m_cards.back();
m_cards.pop_back();
return tmp;
}
else
{
int tmpIndex=rand()%m_cards.size();
int tmp=m_cards[tmpIndex];
m_cards.erase(m_cards.begin()+tmpIndex);
return tmp;
}
}
private:
std::vector<int> m_cards;
};
感觉应该有更好的解决方案,怎么样才能更OO?
------解决方案--------------------C/C++ code
enum Suit
{
Spade = 0,
Heart,
Diamond,
Club
};
class Poker
{
private:
Suit m_suit;
int m_number;
public:
Poker(Suit suit,int number)
{
m_suit = suit;
m_number = number;
}
string GetSuit()
{
string suit = "Spade";
if(m_suit == Heart)
suit = "Heart";
if(m_suit == Diamond)
suit = "Diamond";
if(m_suit == Club)
suit = "Club";
return suit;
}
friend ostream& operator <<(ostream& os, Poker* pk)
{
string suit = pk->GetSuit();
os << "[" << suit.c_str() << ":" << pk->m_number << "]";
return os;
}
};
class Cards
{
private:
vector<Poker*> m_cards;
public:
Cards()
{
for(int i = 0 ; i < 52 ; i++)
{
m_cards.push_back(new Poker((Suit)(i / 13), (i % 13)+1));
}
}
void Output()
{
vector<Poker*>::iterator iter = m_cards.begin();
for(; iter != m_cards.end() ; iter++)
{
cout<<(Poker*)(*iter)<<endl;
}
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Cards *cards = new Cards();
cards->Output();
int a = 0;
a = cin.get();
return 0;
}
------解决方案--------------------
改进了一下。。。顶楼上
C/C++ code
#include <iostream>
#include <string>
#include <vector>
using namespace std;
enum Suit
{
Spade = 0,
Heart,
Diamond,
Club
};
class Poker
{
private:
Suit m_suit;
int m_number;
public:
Poker(Suit suit,int number)
{
m_suit = suit;
m_number = number;
}
string GetSuit()
{
string suit = "Spade";
if(m_suit == Heart)
suit = "Heart";
if(m_suit == Diamond)
suit = "Diamond";
if(m_suit == Club)
suit = "Club";
return suit;
}
friend ostream& operator <<(ostream& os, Poker* pk)
{
string suit = pk->GetSuit();
os << "[" << suit.c_str() << ":" << pk->m_number << "]";
return os;
}
};
class Cards
{
private:
vector<Poker*> m_cards;
public:
Cards()
{
for(int i = 0 ; i < 52 ; i++)
{
m_cards.push_back(new Poker((Suit)(i / 13), (i % 13)+1));
}
left = 52;
}
void Output()
{
iter = m_cards.begin();
for(; iter != m_cards.end() ; iter++)
{
cout<<(Poker*)(*iter)<<endl;
}
}
void GetACard()
{
srand( (unsigned)time(NULL));
int index=rand()%left;
iter = m_cards.begin();
Poker *p=m_cards[index];
m_cards.erase(iter+index);
cout<<(Poker*)(p)<<endl;
left--;
}
private:
vector<Poker*>::iterator iter;
unsigned int left ;
};
int main(int argc, char* argv[])
{
Cards *cards = new Cards();
// cards->Output();
int i=52;
while(i--)
{
cout<<i<<":";
cards->GetACard();
}
system("pause");
return 0;
}