#include<iostream> #include<string> #include<cstdlib> #include<ctime> using namespace std; struct Card //一张扑克牌 { int value; //点数 string color; //花色 string face; //1-10、J、Q、K面值 }; void initCards(Card *cards) { for(int i=0;i<52;i++) { cards[i].value=i%13+1; int j=i/13; switch(j) { case 0: cards[i].color="黑桃"; break; case 1: cards[i].color="红桃"; break; case 2: cards[i].color="梅花"; break; case 3: cards[i].color="方块"; break; } if(cards[i].value<=9&&cards[i].value>1) { cards[i].face=(char)(cards[i].value+48); } else if(cards[i].value==10) { cards[i].face="10"; } else if(cards[i].value==11) { cards[i].face="J"; } else if(cards[i].value==12) { cards[i].face="Q"; } else if(cards[i].value==13) { cards[i].face="K"; } else if(cards[i].value==1) { cards[i].face="A"; } } return; } void orderCards(Card *cards) { srand((unsigned)time(NULL)); for(int i=0;i<52;i++) { int index1=rand()%52; int index2=rand()%52; Card temp=cards[index1]; cards[index1]=cards[index2]; cards[index2]=temp; } return; } void playCards(Card *cards) { char ch; int userScore=0; //玩家点数 int cardIndex=0; int systemScore=rand()%21; //庄家点数 while(systemScore<15) //保证庄家点数在15点到21点之间 { systemScore=rand()%21; } cout<<"准备好了吗?(Y/N)"; cin>>ch; if(ch=='Y'||ch=='y') { cout<<"你得到的第一张牌:"<<cards[cardIndex].color<<" "<<cards[cardIndex].face<<endl; userScore+=cards[cardIndex].value; cardIndex++; cout<<"你得到的第二张牌:"<<cards[cardIndex].color<<" "<<cards[cardIndex].face<<endl; userScore+=cards[cardIndex].value; cardIndex++; } else { return; } cout<<"继续要牌吗?(Y/N)"; cin>>ch; while(ch=='Y'||ch=='y') { cout<<"你得到的牌:"<<cards[cardIndex].color<<" "<<cards[cardIndex].face<<endl; userScore+=cards[cardIndex].value; cardIndex++; if(userScore>21) //玩家要牌后点数大于21点 { cout<<"庄家的点数为:"<<systemScore<<endl; cout<<"你的点数为:"<<userScore<<"大于21点!"<<endl; cout<<"你输了!"<<endl; return; } else { cout<<"继续要牌吗?(Y/N)"; cin>>ch; } } if(userScore<=21) //玩家停止要牌,跟庄家比点数,判断输赢 { cout<<"庄家的点数为:"<<systemScore<<endl; cout<<"你的点数为:"<<userScore<<endl; if(systemScore>userScore) { cout<<"你输了!"<<endl; } else if(systemScore<=userScore) { cout<<"你赢了!"<<endl; } } } int main() { Card cards[52]; //初始化扑克牌 initCards(cards); //洗牌 orderCards(cards); //游戏开始 playCards(cards); return 0; }