纸牌记忆小游戏C语言源代码
C++实现猜牌小游戏
![C++实现猜牌小游戏](https://img.taocdn.com/s3/m/a93bfc926c85ec3a87c2c5af.png)
C++实现猜牌小游戏这是大一的时用C写的猜牌小游戏,里面用了easyx图形库,供大家参考,具体内容如下运行效果实现代码#include<stdio.h>#include<time.h>#include<stdlib.h>#include<Windows.h> #include<graphics.h> #include<mmsystem.h>#pragma comment(lib,"winmm.lib") #define HANG 4#define LIE 4#define SIZE 200int g_matt[HANG][LIE] = { 0 };int g_matt_time[HANG][LIE] = { 0 }; int g_matt_mask[HANG*LIE] = { 0 }; IMAGE img[10];void Put(){char jpg[50];for (int i = 0; i <10; i++){sprintf(jpg, "images\\%d.jpg", i); loadimage(&img[i], jpg, SIZE, SIZE); //printf("%s\n", jpg);}}int getNextNumber(){char stat[8] = { 0 };for (int i = 0; i < HANG; i++){for (int j = 0; j < LIE; j++){if (g_matt[i][j]>0 && g_matt[i][j]<9)//让数组里面的数不能重复出现3次stat[g_matt[i][j]-1]++;////printf("%c", stat);}}char n = 0;while (1) {n = rand() % 8 + 1;//随机1到8if (stat[n-1] >= 2) {//判断这个数组里面不能出现2个以上重复的1到8 continue;} else {break;}}return n;}void Playone(){for (int i = 0; i < HANG; i++){for (int j = 0; j < LIE; j++){g_matt[i][j] = getNextNumber();printf("%d ", g_matt[i][j]);}printf("\n");}for (int i = 0; i < HANG; i++){for (int j = 0; j < LIE; j++){if (g_matt[i][j] >= 1 && g_matt[i][j] <= 8) g_matt[i][j] += 20;printf("%d ", g_matt[i][j]);}printf("\n");}}void Plus(){for (int i = 0; i < HANG; i++){for (int j = 0; j < LIE; j++){if (g_matt[i][j] == 1){putimage(i*SIZE, j*SIZE, &img[1]); }else if (g_matt[i][j] == 2){ putimage(i*SIZE, j*SIZE, &img[2]); }else if (g_matt[i][j] == 3){ putimage(i*SIZE, j*SIZE, &img[3]); }else if (g_matt[i][j] == 4){ putimage(i*SIZE, j*SIZE, &img[4]); }else if (g_matt[i][j] == 5){ putimage(i*SIZE, j*SIZE, &img[5]); }else if (g_matt[i][j] == 6){ putimage(i*SIZE, j*SIZE, &img[6]); }else if (g_matt[i][j] == 7){ putimage(i*SIZE, j*SIZE, &img[7]); }else if (g_matt[i][j] == 8){putimage(i*SIZE, j*SIZE, &img[8]);}else if (g_matt[i][j] >= 20 && g_matt[i][j] <= 28){putimage(i*SIZE, j*SIZE, &img[0]);}else if (g_matt[i][j] > 100){putimage(i*SIZE, j*SIZE, &img[9]);}}}}void Play(){MOUSEMSG msg = { 0 };msg = GetMouseMsg();//if (WM_LBUTTONDOWN == matt[msg.x][msg.y] >= 20 || matt[msg.x][msg.y]<=28){switch (msg.uMsg){case WM_LBUTTONDOWN:{int row = msg.y / SIZE;int col = msg.x / SIZE;if (g_matt[col][row] >= 20 && g_matt[col][row] <= 28){g_matt[col][row] -= 20;//printf("%d ", g_matt[col][row]);}//mciSendString("open images\\click.wav", NULL, NULL, NULL); mciSendString("play images\\click.wav", NULL, NULL, NULL); Sleep(10);mciSendString("cloes images\\click.wav", NULL, NULL, NULL); }}//cleardevice();}void Over(){int *p = (int*)g_matt+1;for (int i = 0; i < HANG*LIE; i++) {for (int j = i + 1; j < HANG*LIE; j++) {if(p[i] <= 8 && p[i] >= 1 && p[i] == p[j]){p[i] += 120;p[j] += 120;//mciSendString("open images\\search.wav", NULL, NULL, NULL); mciSendString("play images\\search.wav", NULL, NULL, NULL); Sleep(10);mciSendString("cloes images\\search.wav", NULL, NULL, NULL); }}}}void Keep(){for (int i = 0; i < HANG; i++){for (int j = 0; j < LIE; j++){if (g_matt[i][j] >= 1 && g_matt[i][j] <= 8){g_matt[i][j] += 20;//printf("%d ", g_matt[i][j]);}}printf("\n");}}int main() {//int *p1;mciSendString("open images\\东京不太热.mp3", NULL, NULL, NULL); mciSendString("play images\\东京不太热.mp3", NULL, NULL, NULL); srand(time(NULL));HWND hwnd =initgraph(800, 800);Put();Playone();int frames = 0;DWORD t1, t2,t3;t1 = GetTickCount();//程序运行时间while (1){t2 = GetTickCount();Plus();//贴图Play();//鼠标点击if (t2-t1>=1600){//等于当前时间减去程序运行时间大于等于两秒才运行也就是卡两秒Keep();//加密//continue;t1 = t2;//当前时间赋给程序运行时间}Over();char ch[16] = { 0 };char n = 0;for (int i = 0; i < HANG; i++){for (int j = 0; j < LIE; j++){if (g_matt[i][j] >= 120){ch[g_matt[i][j] - 1]++;}}}while (n>6) {if (ch[n - 1] >= 6) {//判断这个数组里面不能出现2个以上重复的1到8 MessageBox(hwnd, "恭喜你赢了", "", MB_OK);//continue; n++;}}}return 0;}。
C++PlayCards21点游戏(源码)
![C++PlayCards21点游戏(源码)](https://img.taocdn.com/s3/m/e17f8ea90029bd64783e2cbc.png)
private:
string name;
Card cd[52];
int num;
int total;
};
class Game
{
public:
Game(int num,string s)
{
playernum=num;
my_house.Setname(s);
cout<<"("<<my_player[i].GetTotal()<<")"<<endl;
}
}
void Being()
{
char temp;
int i;
for(i=0;i<playernum;i++){
int t=0;
cout<<"玩家"<<i+1<<":"<<endl;
}
void Prepare()
{
int i;
for(i=0;i<playernum;i++){
cout<<"请输入玩家"<<i+1<<"的名字:";
my_player[i].Setname();
cout<<endl;
}
}
void Begin()
}
void Setname()
{
cin>>name;
}
void Add(Card c)
纸牌记忆小游戏C语言源代码
![纸牌记忆小游戏C语言源代码](https://img.taocdn.com/s3/m/81afe45c7f21af45b307e87101f69e314232fa4c.png)
纸牌记忆小游戏C语言源代码#include#include#includeintoutputacard(inta,int b) //输出一张扑克{if(b==11){printf("[%c",a); //Jprintf("%c]",b+63);}else if(b==12){printf("[%c",a); //Qprintf("%c]",b+69);}else if(b==13){printf("[%c",a); //Kprintf("%c]",b+62);}else if(b==1){printf("[%c",a); //Aprintf("%c]",b+64);}else if(b==88)printf("[%c%c]",a,b); //XXelse{printf("[%c",a); //随机输出8张扑克printf("%d]",b);}}int main(){int puke[8][2];inti,j,k;srand((unsigned int)time(NULL));printf("记住下面牌的顺序\n准备好了按<回车>,我会提问你的^-^\n");for(i=0; i<8; i++)for(j=0; j<2; j++){if(j==0)puke[i][j]=3+rand()%3; /*红心是003 方块004 梅花005 黑桃006*/elsepuke[i][j]=1+rand()%12; //A……K}for(k=0; k<8; k++)outputacard(puke[k][0],puke[k][1]); //随机输出8张扑克printf("\n");int puke2[8][2];int puke0[2];intt,rh;for(t=0; t<8; t++){puke2[t][0]=puke[t][0];puke2[t][1]=puke[t][1];}for(t=0; t<8; t++) /*把上面的8张扑克打乱顺序存入另一个数组*/{rh=rand()%7;if(rh!=t){puke0[0]=puke2[t][0];puke0[1]=puke2[t][1];puke2[t][0]=puke2[rh][0];puke2[t][1]=puke2[rh][1];puke2[rh][0]=puke0[0];puke2[rh][1]=puke0[1];}}for(k=0; k<8; k++)outputacard(puke2[k][0],puke2[k][1]); /*打乱顺序后重新输出8张扑克*/ printf("\n");int puke3[8][2],puke4[8][2];for(i=0; i<8; i++) /*为把上面代表两组扑克的数组puke,puke2复制到另外*/for(j=0; j<2; j++) /*两个数组puke3、puke4中,以方便后面输出*/for(j=0; j<2; j++){puke3[i][j]=88;puke4[i][j]=88;}system("pause");system("CLS");inta,b,num=0;int alp1[8]= {0,0,0,0,0,0,0,0},alp2[8]= {0,0,0,0,0,0,0,0}; /* 记录各个位置的牌是否翻开*/while(alp1[0]==0||alp1[1]==0||alp1[2]==0||alp1[3]==0||alp1 [4]==0||alp1[5]==0||alp1[6]==0||alp1[7]==0){printf("依次输入第一行、第二行两张相同的牌的位置\n");for(k=0; k<8; k++)outputacard(puke3[k][0],puke3[k][1]);printf("\n");for(k=0; k<8; k++)outputacard(puke4[k][0],puke4[k][1]);printf("\n");scanf("%d%d",&a,&b);num++;system("CLS");if(puke[a-1][0]==puke2[b-1][0]&&puke[a-1][1]==puke2[b-1][1]&&alp1[a-1]!=1&&alp2 [b-1]!=1&&a>=1&&a<=8&&b>=1&&b<=8){/*如果两张牌相同且没有被翻开过且输入的数字大于0小于8复制puke,puke2中这两个元素的数据到puke3,puke4中,并输出puke3,puke4*/puke3[a-1][0]=puke[a-1][0];puke3[a-1][1]=puke[a-1][1];alp1[a-1]++;puke4[b-1][0]=puke2[b-1][0];puke4[b-1][1]=puke2[b-1][1];alp2[b-1]++;printf("猜对了,厉害!\n");for(k=0; k<8; k++)outputacard(puke3[k][0],puke3[k][1]);printf("\n");for(k=0; k<8; k++)outputacard(puke4[k][0],puke4[k][1]);printf("\n");system("pause");system("CLS");}else if(alp1[a-1]!=1&&alp2[b-1]!=1&&a>=1&&a<=8&&b>=1&&b<=8){/*如果两张牌不相同但没有被翻开过且输入的数字大于0小于9输出原puke3,puke4并显示该位置正确的牌*/printf("你好像记错了,再想想,我相信你!\n");for(i=0; i<8; i++){if(i==a-1)outputacard(puke[i][0],puke[i][1]);elseoutputacard(puke3[i][0],puke3[i][1]);}printf("\n");for(k=0; k<8; k++){if(k==b-1){outputacard(puke2[k][0],puke2[k][1]);}elseoutputacard(puke4[k][0],puke4[k][1]);}printf("\n");system("pause");system("CLS");}else if(a>=1&&a<=8&&b>=1&&b<=8) /*如果这两张牌中任意一张已经被翻开,输出如下*/{printf("这两张牌中的某一张好像已经被你翻开了哦\n");for(k=0; k<8; k++)outputacard(puke3[k][0],puke3[k][1]);printf("\n");for(k=0; k<8; k++)outputacard(puke4[k][0],puke4[k][1]);printf("\n");system("pause");system("CLS");}else{printf("每行只有8张牌呦,请输入正确的位置,么么哒\n");for(k=0; k<8; k++)outputacard(puke3[k][0],puke3[k][1]);printf("\n");for(k=0; k<8; k++)outputacard(puke4[k][0],puke4[k][1]);printf("\n");system("pause");system("CLS");}}printf("你一共猜了%d次\n",num);if(num==8)printf("完美\n");else if(num>8&&num<=10)printf("非常棒!\n");else if(num>10&&num<=16)printf("你的记忆力挺不错的!\n");elseprintf("你的记忆力一般般啦,再练练吧!\n"); system("pause"); return 0;}。
24点纸牌游戏源代码
![24点纸牌游戏源代码](https://img.taocdn.com/s3/m/4be0b092dd88d0d233d46a17.png)
#include <stdio.h>#include <windows.h>#pragma comment ( lib, "Winmm.lib")// 0,1,2,3分别代表+,-,*,/float OperVisual(float num1,float num2,int oper);//双目运算int Show(float num1,float num2,float num3,float num4,int i);//交换率运算并显示void main(){int i1,i2,i3,i4,i=0;unsigned int s1,s2;float num[4];//分别代表输入的4个数puts("Please enter the number 4:");scanf("%f%f%f%f",&num[0],&num[1],&num[2],&num[3]);s1=timeGetTime();for(i1=0;i1<4;i1++){for(i2=0;i2<4;i2++){for(i3=0;i3<4;i3++){for(i4=0;i4<4;i4++){if(i1!=i2&&i1!=i3&&i1!=i4&&i2!=i3&&i2!=i4&&i3!=i4)i=Show(num[i1],num[i2],num[i3],num[i4],i);}}}}if(!i) printf("No answer !");s2=timeGetTime();printf("\ntime consuming:%dms\n",s2-s1);getchar();getchar();}int Show(float num1,float num2,float num3,float num4,int i){int oper1,oper2,oper3;//分别代表3个操作符char OperShow[4]={'+','-','*','/'};//0,1,2,3float end1,end2,end3;for(oper1=0;oper1<4;oper1++){//第一个运算符end1=OperVisual(num1,num2,oper1);//将第一个数进行4次运算for(oper2=0;oper2<4;oper2++){//第二个运算符end2=OperVisual(end1,num3,oper2);//将前两个数的结果和第三个数进行4次运算for (oper3=0;oper3<4;oper3++){//第三个运算符end3=OperVisual(end2,num4,oper3);//将前三个数的结果和第三个数进行4次运算if(end3==24){if(oper1<=1&&oper2>=2)//如果第一个运算符为+或-第二个运算符为*或/printf("(%.f%c%.f)%c%.f%c%.f=24\n",num1,OperShow[oper1],num2,OperShow[oper2],nu m3,OperShow[oper3],num4),i++;else if(oper1<=1&&oper2<=1&&oper3>=2)printf("(%.f%c%.f%c%.f)%c%.f=24\n",num1,OperShow[oper1],num2,OperShow[oper2],nu m3,OperShow[oper3],num4),i++;else if(oper1>=2&&oper2<=1&&oper3>=2)printf("(%.f%c%.f%c%.f)%c%.f=24\n",num1,OperShow[oper1],num2,OperShow[oper2],nu m3,OperShow[oper3],num4),i++;elseprintf("%.f%c%.f%c%.f%c%.f=24\n",num1,OperShow[oper1],num2,OperShow[oper2],num3,Op erShow[oper3],num4),i++;}}}}return i;}float OperVisual(float num1,float num2,int oper){float result;switch(oper){case 0:result=num1+num2;break;case 1:result=num1-num2;break;case 2:result=num1*num2;break;case 3:result=num1/num2;break;}return result;}。
C语言二十一点纸牌游戏系统详细设计样本
![C语言二十一点纸牌游戏系统详细设计样本](https://img.taocdn.com/s3/m/d45e27813c1ec5da51e2702e.png)
/* nPlayer--玩家手中所有牌点数和,nPlayerTurns--玩家手中牌数量*/
char chAnswer;
char mmm;
a;
system("cls");/*执行系统命令"清屏"*/
Rules_f();
printf("确认与否开始游戏:");
{
int nRan;
srand((unsigned)time(NULL));
nRan=rand()%(lBigNumber-(lSmallNumber-1))+lSmallNumber;
return(nRan);
}
void Hit_f2(int * npTotal,int a) /*发一张牌,返回点数之和*/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void Wait_f(int);
void Pause_f();/*暂停,按任意键继续*/
int Random_f(long ,long );/*返回两个参数之间随机数*/
void Replay_f(char *);/*询问与否重开一局*/
图2.4在作弊模式下取胜,可以接着要牌,但玩家牌最多不能超过5张,取胜后会记录成果,询问与否继续游戏
2.5非作弊模式
图2.5此状况为非作弊模式,不能见庄家牌,只能懂得成果,输掉游戏后记录成果,询问与否继续
2.6退出游戏
图2.6此为退出游戏,输入后自动关闭窗口
3.源程序:
#include<time.h>
扑克牌游戏c源代码
![扑克牌游戏c源代码](https://img.taocdn.com/s3/m/07bb88a5960590c69ec376ab.png)
扑克牌游戏c++源代码/*第1题扑克牌游戏--源代码及关键源代码注解如下:*///* This Program was written entirely by the author Frank Vokoun.//*******************preprocessor directives***********************//#include <iostream.h>#include <string.h>#include <conio.h>#include <stdlib.h>#include <stdio.h>#include <time.h>// used to seed the random number generator////*********************************************************************** class Playing_Card //扑克类{private:int m_Value;char m_Face[3]; //扑克的数字大小char m_Suit ; //扑克的花色(黑、红、梅、方)public:Playing_Card();// CONSTRUCTORvoid showcard();// Displays an object of class Playing_Card void Card_Make(int);};class Deck//一副扑克(52张){private:Playing_Card m_cardarray[52];// Object array of class Playing_Cardint m_lastdelt;public:Deck();// CONSTRUCTOR initializes empty Deck objectvoid MakeDeck();// makes a complete object of class Deckvoid Deal_One();// Deals a card from top of the deckvoid ShowDeck();// Displays a Deck object to the screenvoid DeckShuff(int);// "Shuffles" a Deck object for int timesvoid Remove_Card();// Removes used card from Deck Prevents};//mistakenly using a nonexistant card //can bu used to send a card ??//***************************prototypes**********************************void Program_Init();// Program informationint main();void Center_Text(char []);// Centers textint get_number();// Gets a integer from userchar Get_Key();// Gets a char from user, pauses programvoid DeckMakeDriver();// Tests Several Functions including Makedeck int getRandInt(int min, int max);// Random number generatorvoid prog_close();// pauses before program termination//****************************Main*************************************int main()//************************************************************************** //*int main:Main Function Calls other functions//*//*expects:None.//*Returns:Integer 0;//*Side effects None//*//*Tasks(1) Seeds the Random number generator//*(2) Calls Program Init function for Title etc.//*(3) Call DeckMakeDriver to Test MakeDeck and DeckShuff.//*//***********************************************************************{srand( (unsigned)time( NULL ) );// Seeds GetRandIntint Card_Number = 0;Program_Init();// Showd title etc.DeckMakeDriver();// The Main Function Driver Tests Deck and//Playing_Card classesprog_close();// pauses screen outputreturn 1;}Playing_Card::Playing_Card()// CONSTRUCTOR//************************************************************************** //*Playing_Card Playing_Card CONSTRUCTOR FOR CLASS Playing_Card//*//*expects:None.//*Returns:None//*Side effects None//*//*Tasks Constructs object of class playing_card replaces default constructor//*********************************************************************// Constructor replaces default constructor{int i;for(i=1;i<=3;)// inits string variable to blanks{m_Face[i] = ' ';i++;}m_Suit = ' ';// inits char variable to blankm_Value = 0;}void Program_Init()//************************************************************************* //*void Program_Init():Shows Title//*//*expects None//*returns:None//*Side Effects:Text is centered on screen//*//*Task(s)Output program information to screen.//*//***********************************************************************{Center_Text("Lab #5");cout << endl;Center_Text("A Deck Driver");cout << endl <<"\n" ;Center_Text("By Frank Vokoun");cout << endl <<"\n" ;Center_Text("(C) 2001, Frank Vokoun");cout << endl <<"\n" ;Center_Text("Hit the <Return> key to Continue..");cin.get();}char Get_Key()//*********************************************************************** //*char Get_Key():Uses a input prompt to get a char//*//*expects:None.//*Returns:Input char.//*Side effects:Pauses Program execution (desired effect).//*//*Task(s):Gets a char from the user..//*//********************************************************************** {char x;x = cin.get();cout << endl;return x;}void Playing_Card::showcard()//*****************************************************************//*void showcard(card):Displays a Playing Cards object to the screen//*//* Expects:None -> Uses calling members Playing_Card object//* Returns:None//* Side Effects:Displays//*//*Task(s):Displays the object of class Playing_Card to screen//*//*********************************************************************** {cout << " ";cout << m_Face ;cout.width(1);cout << m_Suit;cout << " ";}void Center_Text(char ShellText[80])//********************************************************************** //*Void Center_Text:Displays text centered on the screen.//*//*expects:The text to display.//*Returns:None.//*Side effects:Outputs Centered text on screen.//*//*******************************************************************{int length;int center;length= strlen(ShellText);center = (80 - length)/2;for(;center!=0;center--){cputs(" ");}cputs(ShellText);}int get_number()//******************************************************************** //*//*int get_number:Gets an integer from the user.//*expects:None.//*Returns:Integer.//*Side effects:None.//*Task(s):Asks the user to enter an integer then returnsthat integer.//*.//********************************************************************** {int Input_Integer = 0;Center_Text("Please enter an integer between 0 and 51. 52 to quit.");cout << endl;cin >> Input_Integer;return Input_Integer;}void Playing_Card::Card_Make(int num)//********************************************************************* //* Get_Card(int):Creates a Playing_Card object based on an interger input.//* Expects:int//* Returns:None -> uses Calling members Playing_Card object//* Side Effects:None//*//*Tasks: 1. assign a face value//* 2. assign a m_Suit(char type)//* 3. assign a point value//*//******************************************************************** {int i = 0;char j;int face_num = num % 13;switch(face_num)// Assigns a Face value for string cards{case 0: strcpy(m_Face," A");break;case 9: strcpy(m_Face,"10");break;case 10: strcpy(m_Face," J");break;case 11: strcpy(m_Face," Q");break;case 12: strcpy(m_Face," K");break;default:j = char(face_num + 49);// Fills string with number mod 13if(i<3){m_Face[i] = ' '; i++;m_Face[i] = j;i++;m_Face[i] = NULL;break;}}if(num <= 12)m_Suit = 6;// assigns suit use ascii values forif(num >12 && num <= 25)m_Suit = 3;//card symbolsif(num >25 && num <= 38)m_Suit = 5;if(num >38 && num <= 51)m_Suit = 4;if(face_num <= 9)m_Value = face_num + 1;// Card value's Ace = 1 if(face_num >= 10)m_Value = 10;}void DeckMakeDriver()//********************************************************************//* DeckMakeDriver():Used to test the various deck functions Deckmake,//*Deckshuff, Deckcopy etc.//*Expects:None.//* Returns:None.//* Side effects:None//*//* Tasks: 1. Call make Deck//* 2. Show Deck//* 3. Call shuffle//* 4. Call show deck//* 5. While !Done Call//* a. Deal one//* b. Show card//*//*Note the dot operator is need to access object because this is not a member of the class //**********************************************************************{Deck deck_1;deck_1.MakeDeck();// Creates the Deck.deck_1.ShowDeck();// Displays deck to screen.Get_Key();// Pauses Program.deck_1.DeckShuff(250);// Shuffles the deck 250 timesdeck_1.ShowDeck();// Displays deck to screen.cout << endl <<endl << endl;char y;do{deck_1.Deal_One();cout << endl;cout << endl << endl << "Y to Deal One more N to quit"<< endl;cin >> y;y = toupper(y);}while(y == 'Y' );}void Deck::MakeDeck()// creates a full deck not a construct//************************************************************************** //* Deck Make Deck():Creates a Deck Object//* Expects:none -> uses calling functions deck object//*Returns:none -> uses calling functions Deck object //* Side effects:none//* Tasks: 1. Create a Full Deck structure of unique card structures//* a. have the decks last delt variable = to the top card//***********************************************************************{m_lastdelt = 51;// Set Deck to emptywhile(m_lastdelt >-1)// iterate until deck is full.{m_cardarray[m_lastdelt].Card_Make(m_lastdelt); // call card make for every card object m_lastdelt--;// inside the deck object ie cardarray}}void Deck::ShowDeck()//********************************************************************//* void ShowDeck:Displays the deck in a organized readable fashion to the screen //* Expects:none shows calling functions object of class deck//* Returns:none//* Side Effects:None//* Tasks: 1. set an index to lastdealt + 1//* 2. call ShowCard passing in card[index]//*********************************************************************{int index = m_lastdelt + 1;int newline = 0;Center_Text("Current Deck of Cards from top to bottom");cout << endl;while(index<=51){if(newline % 11 == 0) cout << endl;m_cardarray[index].showcard();// calls showcard for every card innewline++;// the cardarray objectindex++;}}int getRandInt(int min, int max)//*********************************************************************//*int GetRandInt:Returns a random number between min and max//*//* BORROWED FUNCTION:Used with permission from Prof. Steve Samuelson.//*//*Expects:min -- smallest possible number to return//*max -- largest possible number to return//* Returns: A number between min and max//* Side Effects:None//*//* Tasks: 1. set a num = to random number generator.//* 2. make num = num % (max - min +1); add min.//* 3. Return the num//*******************************************************************{int numToReturn;numToReturn = rand();numToReturn = numToReturn % (max - min + 1) + min;return numToReturn;}void Deck::DeckShuff( int times) //洗牌次数//********************************************************************//*Deck DeckShuff(Deck, int):Simulates the shuffling of a deck of cards//*expects:none -> uses calling functions Deck object//*Returns:none -> manipulates calling functions object of class Deck USING //* A THIS POINTER//*Side effects:no unintended effects.//*//*Task(s) 1. To randomly arrange the elements of the Deck structure Playing_Card//*array.//* A. split the Deck structure into two halves at a random location//*between 20 and 35.//* B. Alternating between the two halves move a random number of //*Playing_Card structures to the original deck structure, Until//*it is full of cards (52cards in a deck).* this is also the//*number of cards available in the to halves.//* C. Since it is a full unused deck set the lastdelt variable to -1//*//*//*********************************************************************{int x, split; //split是分开成两部分的位置,如上部分、下部分Center_Text("Shuffling Deck");cout << endl;for(x=0;x<=times;x++)// iterate input number of times {split = getRandInt(20,35);// Get split locationDeck topdeck;// Create 2 new unfilled decks Deck bottomdeck;int i;int bottomdeckindex = 1;int topdeckindex = 1;for(i=0;i<=split - 1;){topdeck.m_cardarray[topdeckindex] = this->m_cardarray[i];topdeckindex++;i++;}for(i=(split);i< 52;)// move remaining cards to bottom deck{bottomdeck.m_cardarray[bottomdeckindex] = this->m_cardarray[i]; bottomdeckindex++;i++;}int deckoutindex = 0;// set deck to fill's index to zeroint numcardstomovetop;int numcardstomovebottom;int j;int h = 0;bottomdeckindex = 52 - split;// set index to num cards in bottom topdeckindex =split;// set index to num cards in topwhile(deckoutindex <= 51){numcardstomovetop = getRandInt(2,7);//从上部分抽取的张数,是2-7之间的随机数numcardstomovebottom = getRandInt(2,7);// Move a random number of cards(2-7)for(j=0;j <=numcardstomovebottom;j++)//from bottomdeck to original deck{if(bottomdeckindex > 0)// check for available cards{this->m_cardarray[deckoutindex] = bottomdeck.m_cardarray[bottomdeckindex]; deckoutindex++;bottomdeckindex--;}for(h=0;h<=numcardstomovetop;h++)// Move a random number of cards (2 to 7){//from topdeck to original deck.if((topdeckindex > 0) && (deckoutindex <=52))// check for available cards{//and slotsthis->m_cardarray[deckoutindex]=topdeck.m_cardarray[topdeckindex]; deckoutindex++;topdeckindex--;}}}}}this->m_lastdelt = -1;// Return a complete shuffled deck}void prog_close()//*******************************************************************//*void prog_close:Waits for user input to end//*Inputs:None//*Returns:None//*Side effects:Output text to screen/waits for user input to//*end program.//*//*task(s) 1. Pauses Program so the last output can be seen//*//*********************************************************************** {cout << endl << endl;cout << " Hit the <Return> key to Continue.." << endl;cout << endl << endl;Get_Key();// Necesary for clear input.cin.get();}void Deck::Remove_Card()//*****************************************************************//* Deck Remove_Card(Deck deck_1):Removes the card delt from dealing deck.//*Expects:The Deck that delt the card.//*Returns:The Deck without the card delt.//*Side effects:None.//*//*Task(s):Remove card delt from Deck//****************************************************************{m_cardarray[m_lastdelt]= Playing_Card();// reinits used card prevents mistakes}void Deck::Deal_One()//************************************************************************** *****************//* Deck Deal one(Deck):Deals a card from the top of the deck//* Expects: A deck to deal from//* Returns:The deck minus the card delt//* Side effects:lastdealt in the deck is incremented//*//* Tasks: 1. Check if lastdealt = 51 if so Error//* 2. Increment last dealt//* 3. Return card[last dealt]//************************************************************************** {if(m_lastdelt != 51)// Checks for available cards{m_lastdelt++;cout.width(5);cout <<" Card delt";m_cardarray[m_lastdelt].showcard();}else{cout << "Out of range Error";prog_close();}}Deck :: Deck()// CONSTRUCTOR replaces default//**********************************************************************//* Deck Deck Class Deck CONSTRUCTOR//* Expects: A deck to deal from//* Returns:The deck minus the card delt//* Side effects:lastdealt in the deck is incremented//*//* Tasks: 1. Check if lastdealt = 51 if so Error//* 2. Increment last dealt//* 3. Return card[last dealt]//******************************************************************* {int lastdelt = 0;int i;for(i=0;i<=51;i++){m_cardarray[1] = Playing_Card();// calls constructor class Playing_Card}// for every Playing_Card object in}// the class Deck's array.。
记忆训练游戏源码(C语言版)
![记忆训练游戏源码(C语言版)](https://img.taocdn.com/s3/m/5e50a939ee06eff9aef807a1.png)
//头文件#include <stdio.h>#include <stdlib.h>#include <windows.h>#include <time.h>//成员变量申明int time1,time2; // 游戏开始时间,游戏结束时间int count,right; // 玩家玩游戏的次数,玩家通关关数char restart; // 玩家选择是否继续static int t = 1000; // 静态初始化t//函数申明void menu(); // 申明主菜单方法void load(); // 申明倒计时子函数void charSellet(); // 申明字母记忆菜单函数void letter(int x); // 字母记忆子函数void scoreGame(int score,int right); //游戏结果函数void endGame(void); // 游戏结束界面void allGame(); // 全键盘记忆功能void delay(int t); // 延时函数void numberGame(); // 申明数字记忆菜单函数void setNumberGame(); // 申明数字记忆游戏方法// 主函数void main(){time1 = time(NULL); // 记录玩家开始时的时间menu(); // 主函数调用主菜单方法}// 定义主菜单函数void menu(){int choice; // 定义一个参数system("color 4f"); // 设置背景颜色// 输出主菜单界面printf("\n\n\n");printf("\t****************** 记忆训练游戏*****************\n");printf("\n\t****** 设计者:万平时间:2015.1.4 ******");printf("\n\t***********************************************************\n");printf("\n\t************ 1.数字记忆************\n");printf("\n\t************ 2.字母记忆************\n");printf("\n\t************ 3.全键盘记忆************\n");printf("\n\t************ 0.退出************\n");printf("\n\t***********************************************************\n");printf("\t***********************************************************\n");printf("\n\t请选择:"); // 提示玩家输入scanf("%d",&choice); // 获取玩家输入的编号,并用choice接收switch(choice) // 对玩家输入的编号进行判断{case 0:endGame(); // 调用游戏结束函数break;case 1:system("cls");setNumberGame();// 调用数字游戏方法break;case 2:charSellet(); // 调用字母游戏方法break;case 3:load(); // 调用倒计时子函数allGame(); // 调用全键盘记忆函数break;default: // 错误输入判断printf("\n\t您的输入有误,请重新输入! ");break;}}// 定义倒计时子函数void load(){int i;system("cls");printf("\n\n\n\n\n\t\t\t\tloading...\n\n\n\n\n\n\n\n");for(i = 0;i<80;i++) // 循环输出>{printf(">");delay(10); // 停留10毫秒}}// 定义延时函数void delay(int t){Sleep(t); // 界面停留函数}/** 01:数字记忆模块*/// 定义数字记忆菜单void setNumberGame(){int choice;system("cls");// 输出难度菜单界面printf("\n\n\n\n");printf("\n\t***********************************************************\n");printf("\n\t************ 1.一般************\n");printf("\n\t************ 2.中等************\n");printf("\n\t************ 3.困难************\n");printf("\n\t************ 4.疯狂************\n");printf("\n\t************ 5.返回************\n");printf("\n\t***********************************************************\n");printf("\n\t请选择:"); // 提示玩家输入scanf("%d",&choice); // 获取玩家输入的编号,并用choice接收switch(choice) // 对玩家输入的编号进行判断{case 1:load(); // 调用倒计时子函数numberGame(); // 调用数字记忆子函数break;case 2:load(); // 调用倒计时子函数t=t-500; // 改变显示时间numberGame(); // 调用改变时间后的数字记忆函数break;case 3:load(); // 调用倒计时子函数t=t-900;numberGame();break;case 4:load(); // 调用倒计时子函数t=t-950;numberGame();break;case 5:system("cls");menu(); // 调用主菜单函数default:printf("\n\t您的输入有误!按任意键继续!");break;}}// 定义数字游戏方法void numberGame(){int s1 = 0,s2 = 1,input,num; // s1,s2用于随机函数的个数,input存放玩家输入的数字,num存放随机数字do{system("cls"); // 清屏srand((unsigned)time(NULL)); // 以当前时间作为开始num = ((s1 = s1*10+1)+rand()%((s2 = s2*10)-s1)); // 产生一个随机数count++; // 统计游戏次数printf("\n\n\n\n\n\n\t\t\t\t 游戏中... \n\n\n\n");printf("\n\n\n\t请记住此数字:%d",num); // 输出随机数delay(t); // 调用延时函数system("cls");printf("\n\n\n\n\n\n\t\t\t\t 游戏中... \n\n\n\n");printf("\n\t【第");printf("%d",right+1);printf(" 关】");printf("\n\n\t请输入刚才的数字:"); // 玩家输入看到的数字scanf("%d",&input); // 获取玩家输入的数字,并存放于input中if(input == num) // 判断玩家输入的数字与随机数是否相等{system("cls");right++; // 分数加1printf("\n\n\n\n\n\n\t\t\t\t 游戏中... \n\n\n\n");printf("\n\n\n\t闯关成功,继续挑战!...");Sleep(1000); // 显示停留1000毫秒system("cls");continue; // 跳转到循环开始}else // 如果不相等{do{system("cls");printf("\n\n\n\n\n\n\t\t\t\t 游戏中... \n\n\n\n");printf("\n\n\n\t输错了,是否继续?(y/n):");scanf("%c",&restart); // 获取玩家的输入,并存放在restart中if(restart == 'Y' || restart == 'y'){s1 = s1/10; // 恢复错误时的数字个数s2 = s2/10; // 恢复错误时的数字个数break;}else if(restart == 'N' || restart == 'n'){scoreGame(count,right); // 调用游戏结果函数}}while(1);}}while(1);}/** 02:字母记忆模块*/// 定义字母记忆菜单函数void charSellet(){int choice;system("cls");// 输出字母记忆菜单界面printf("\n\n\n\n");printf("\n\t***********************************************************\n");printf("\n\t************ 1.大写字母************\n");printf("\n\t************ 2.小写字母************\n");printf("\n\t************ 3.返回************\n");printf("\n\t***********************************************************\n");printf("\n\t请选择:"); // 提示用户输入scanf("%d",&choice); // 获取玩家输入的编号,并用choice接收switch(choice) // 对玩家输入的编号进行判断{case 1:load(); // 调用倒计时子函数letter(1); // 调用字母记忆函数,显示大写字母break;case 2:load(); // 调用倒计时子函数letter(2); // 调用字母记忆函数,显示大写字母break;case 3:system("cls");menu(); // 调用主菜单函数default:printf("\n\t您的输入有误!按任意键继续!");break;}}// 定义字母记忆游戏void letter(int x){int i;int n=1; // 初始化循环变量char num[100],input[100]; // 用于存放随机产生的字母,用于存放玩家输入的字母srand((unsigned)time(NULL)); // 从当前时间开始do {system("cls");printf("\n\n\n\n\n\n\t\t\t\t 游戏中... \n\n\n\n");printf("\n\n\n\t请记住这些字母:");if(x == 1) // 判断用户选择大写字母for(i=0;i<n;i++) // 循环获取字母{num[i]=rand()%26+'A' ; // 随机产生大写字母printf("%c",num[i]); // 输出大写字母}else if(x == 2){for(i=0;i<n;i++) // 循环获取字母{num[i]=rand()%26+'a' ; // 随机产生小写字母printf("%c",num[i]); // 输出小写字母}}num[n]='\0'; // 给数组加一个结束标志count++; // 统计游戏次数Sleep(500); // 界面停留500毫秒system("cls");printf("\n\n\n\n\n\n\t\t\t\t 游戏中... \n\n\n\n");printf("\n\t【第");printf("%d",right+1);printf(" 关】");printf("\n\n\t请输入刚才的字母:");scanf("%s",input); // 获取玩家输入的字母,并存放在input中if(strcmp(num,input)==0) // 比较两个字符串是否相同{right++; // 记录正确个数n++; // 循环上限加1system("cls");printf("\n\n\n\n\n\n\t\t\t\t 游戏中... \n\n\n\n");printf("\n\n\n\t闯关成功,继续挑战!...");Sleep(1000); // 显示停留1000毫秒system("cls");continue; // 跳转到循环开头}else{do{system("cls");printf("\n\n\n\n\n\n\t\t\t\t 游戏中... \n\n\n\n");printf("\n\n\n\t输错了!是否继续?(y/n):");scanf("%c",&restart); // 获取玩家的输入,并存放在restart中if(restart=='y'||restart=='Y')break;else if(restart=='N'||restart=='n'){scoreGame(count,right); // 调用游戏结果子函数break; // 跳转到函数开头}}while(1);}}while(1);}/** 03:全键盘记忆模块*///定义全键盘记忆函数void allGame(){int i;int n=1; // 初始化循环变量char input[100],num[100]; // 存放全键盘随时产生字符串与玩家输入字符do{system("cls");printf("\n\n\n\n\n\n\t\t\t\t 游戏中... \n\n\n\n");printf("\n\n\n\t请记住这个字符串:");for(i=0;i<n;i++) // 循环获取全键盘字符{num[i]=33+rand()%(125-33); // 随机产生全键盘字符printf("%c",num[i]); // 输出随机产生全键盘字符}num[n]='\0';count++; // 记录游戏次数Sleep(1000);system("cls");printf("\n\n\n\n\n\n\t\t\t\t 游戏中... \n\n\n\n");printf("\n\t【第");printf("%d",right+1);printf(" 关】");printf("\n\n\t请输入刚才的字符串:");scanf("%s",input); // 获取玩家输入的字母,并存放在input中if(strcmp(num,input)==0) // 判断字符串是否相同{n++;right++;system("cls");printf("\n\n\n\n\n\n\t\t\t\t 游戏中... \n\n\n\n");printf("\n\n\n\t闯关成功,继续挑战!...");Sleep(1000); // 显示停留1000毫秒system("cls");continue; // 跳转到游戏开头}else{do{system("cls");printf("\n\n\n\n\n\n\t\t\t\t 游戏中... \n\n\n\n");printf("\n\n\n\t输错了!是否继续?(y/n)");scanf("%c",&restart); // 获取玩家的输入,并存放在restart中if(restart=='y'||restart=='Y')break;else if(restart=='N'||restart=='n'){scoreGame(count,right); // 调用游戏结果子函数break;}}while(1);}}while(1);}// 定义游戏结果子函数,显示玩家的分数及闯关数等信息void scoreGame(int score,int right) // 分数score,正确数right作为参数{do{time2 = time(NULL); // 获取游戏结束的时间system("cls"); // 清屏printf("\n\n\n\n\n");printf("\t***********************************************************\n");printf("\n\t******************* 游戏结果*******************\n");printf("\n\t******************* 闯关数: ");printf("%d",score);printf("关*******************\n"); // 输出成功闯关数printf("\n\t******************* 得分: ");printf("%d",right);printf("分*******************\n"); // 输出得分printf("\n\t******************* 失败: ");printf("%d",score-right);printf("关*******************\n"); // 输出失败关数printf("\n\t******************* 时间: ");printf("%d",time2-time1);printf("秒******************\n\n");// 输出玩家游戏时间printf("\t***********************************************************\n");printf("\n\t\t\t");printf("\n\t确定退出游戏?(y/n):");scanf("%c",&restart); // 获取玩家的输入,并存放在restart中if(restart=='y'||restart=='Y')endGame(); // 调用结束显示函数else if(restart=='n'||restart=='N'){system("cls");menu(); // 调用主菜单函数}} while(1);}// 定义游戏结束显示菜单void endGame(){system("cls"); // 清屏printf("\n\n\n\n");// 输出结束菜单printf("\n\t********** 感谢你使用本游戏,祝您生活愉快!*********\n");printf("\n\t********** 设计者:万平时间:2015.1.4 **********\n");printf("\n\t***********************************************************\n");printf("\n\t***********************************************************\n");printf("\n\t************************ 谢谢,再见!**********************\n");printf("\n\n\t\t\t");exit(0); // 退出游戏界面}。
纸牌游戏源代码
![纸牌游戏源代码](https://img.taocdn.com/s3/m/e844371e964bcf84b9d57b15.png)
AboutDialog.java程序import javax.swing.JDialog;import javax.swing.JFrame;import java.awt.Point;import javax.swing.JTabbedPane;import javax.swing.JPanel;import javax.swing.JButton;import javax.swing.JLabel;/** 创建日期2005-7-10 TODO 要更改此生成的文件的模板,请转至窗口-首选项-Java -代码样式-代码模板*//**@*download by * @author 叶少伟TODO 要更改此生成的类型注释的模板,请转至窗口-首选项-Java -代码样式-代码模板*/public class AboutDialog extends JDialog{private javax.swing.JPanel jContentPane = null;protected JFrame owner = null;private JTabbedPane jTabbedPane = null;private JPanel jPanel = null;private JPanel jPanel1 = null;private JPanel jPanel2 = null;private JPanel jPanel3 = null;private JPanel jPanel4 = null;private JButton jButton = null;private JLabel jLabel = null;private JLabel jLabel1 = null;private JLabel jLabel2 = null;private JLabel jLabel3 = null;/*** This is the default constructor*/public AboutDialog(JFrame frame){super(frame);owner = frame;setResizable(false);initialize();}/*** This method initializes this** @return void*/private void initialize(){this.setTitle("关于对话框");this.setSize(209, 132);this.setContentPane(getJContentPane());this.setLocation();this.setVisible(true);this.addWindowListener(new java.awt.event.WindowAdapter() {public void windowClosing(java.awt.event.WindowEvent e) {owner.setEnabled(true);AboutDialog.this.dispose();}});}/*** This method initializes jContentPane** @return javax.swing.JPanel*/private javax.swing.JPanel getJContentPane(){if (jContentPane == null){jContentPane = new javax.swing.JPanel();jContentPane.setLayout(new java.awt.BorderLayout());jContentPane.add(getJTabbedPane(), java.awt.BorderLayout.CENTER);jContentPane.add(getJPanel4(), java.awt.BorderLayout.SOUTH);}return jContentPane;}private void setLocation(){Point point = owner.getLocation();int width = this.getWidth();int height = this.getHeight();int x = (int) (point.getX() + (owner.getWidth() - width) / 2);x = (x > 1024 - width ? 1024 - width : x);x = (x < 0 ? 0 : x);int y = (int) (point.getY() + (owner.getHeight() - height) / 2);y = (y > 768 - height ? 768 - height : y);y = (y < 0 ? 0 : y);setLocation(x, y);}/*** This method initializes jTabbedPane** @return javax.swing.JTabbedPane*/private JTabbedPane getJTabbedPane() {if (jTabbedPane == null) {jTabbedPane = new JTabbedPane();jTabbedPane.addTab("关于", null, getJPanel(), null);jTabbedPane.addTab("作者", null, getJPanel1(), null);jTabbedPane.addTab("班级", null, getJPanel2(), null);jTabbedPane.addTab("学号", null, getJPanel3(), null);}return jTabbedPane;}/*** This method initializes jPanel** @return javax.swing.JPanel*/private JPanel getJPanel() {if (jPanel == null) {jLabel = new JLabel();jPanel = new JPanel();jLabel.setText("蜘蛛牌");jLabel.setFont(new java.awt.Font("楷体_GB2312", java.awt.Font.BOLD, 18));jLabel.setForeground(java.awt.Color.blue);jPanel.add(jLabel, null);}return jPanel;}/*** This method initializes jPanel1** @return javax.swing.JPanel*/private JPanel getJPanel1() {if (jPanel1 == null) {jLabel1 = new JLabel();jPanel1 = new JPanel();jLabel1.setText("叶少伟");jLabel1.setFont(new java.awt.Font("楷体_GB2312", java.awt.Font.BOLD, 18));jLabel1.setForeground(java.awt.Color.blue);jPanel1.add(jLabel1, null);}return jPanel1;}/*** This method initializes jPanel2** @return javax.swing.JPanel*/private JPanel getJPanel2() {if (jPanel2 == null) {jLabel2 = new JLabel();jPanel2 = new JPanel();jLabel2.setText("A02计算机(1)班");jLabel2.setForeground(java.awt.Color.blue);jLabel2.setFont(new java.awt.Font("楷体_GB2312", java.awt.Font.BOLD, 18));jPanel2.add(jLabel2, null);}return jPanel2;}/*** This method initializes jPanel3** @return javax.swing.JPanel*/private JPanel getJPanel3() {if (jPanel3 == null) {jLabel3 = new JLabel();jPanel3 = new JPanel();jLabel3.setText("020505101");jLabel3.setForeground(java.awt.Color.blue);jLabel3.setFont(new java.awt.Font("楷体_GB2312", java.awt.Font.BOLD, 18));jPanel3.add(jLabel3, null);}return jPanel3;}/*** This method initializes jPanel4** @return javax.swing.JPanel*/private JPanel getJPanel4() {if (jPanel4 == null) {jPanel4 = new JPanel();jPanel4.add(getJButton(), null);}return jPanel4;}/*** This method initializes jButton** @return javax.swing.JButton*/private JButton getJButton() {if (jButton == null) {jButton = new JButton();jButton.setText("确定");jButton.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(java.awt.event.ActionEvent e) {owner.setEnabled(true);AboutDialog.this.dispose();}});}return jButton;}} // @jve:decl-index=0:visual-constraint="10,10"Araneid.java程序import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.util.*;/** 创建日期2005-7-12 TODO 要更改此生成的文件的模板,请转至窗口-首选项-Java -代码样式-代码模板*//**download by * @author 叶少伟TODO 要更改此生成的类型注释的模板,请转至窗口-首选项-Java -代码样式-代码模板*/public class Araneid extends JFrame{public static final int EASY = 1;public static final int NATURAL = 2;public static final int HARD = 3;private int grade = Araneid.EASY;private Container pane = null;private PKCard cards[] = new PKCard[104];private JLabel clickLabel = null;private int c = 0;private int n = 0;private int a = 0;private int finish = 0;Hashtable table = null;private JLabel groundLabel[] = null;public static void main(String[] args){Araneid araneid = new Araneid();}/*** This is the default constructor*/public Araneid(){super();this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);this.setSize(1024, 742);this.setJMenuBar(new AraneidMenuBar(this));this.pane = this.getContentPane();this.pane.setBackground(new Color(0, 112, 26));this.pane.setLayout(null);this.clickLabel = new JLabel();this.clickLabel.setBounds(883, 606, 121, 96);this.pane.add(this.clickLabel);this.clickLabel.addMouseListener(new MouseAdapter(){public void mouseReleased(MouseEvent me){if (c < 60) Araneid.this.deal();}});this.setTitle("蜘蛛牌");this.initCards();this.randomCards();this.setCardsLocation();groundLabel = new JLabel[10];int x = 20;for (int i = 0; i < 10; i++){groundLabel[i] = new JLabel();groundLabel[i].setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISE D));groundLabel[i].setBounds(x, 25, 71, 96);x += 101;this.pane.add(groundLabel[i]);}this.setVisible(true);this.deal();this.addKeyListener(new KeyAdapter(){class Show extends Thread{public void run(){Araneid.this.showEnableOperator();}}public void keyPressed(KeyEvent e){if (finish != 8) if (e.getKeyCode() == KeyEvent.VK_D && c < 60){Araneid.this.deal();}else if (e.getKeyCode() == KeyEvent.VK_M){new Show().start();}}});}public void newGame(){this.randomCards();this.setCardsLocation();this.setGroundLabelZOrder();this.deal();}public int getC(){return c;}public void setGrade(int grade){this.grade = grade;}public void initCards(){if (cards[0] != null){for (int i = 0; i < 104; i++){pane.remove(cards[i]);}}int n = 0;if (this.grade == Araneid.EASY){n = 1;}else if (this.grade == Araneid.NATURAL){n = 2;}else{n = 4;}for (int i = 1; i <= 8; i++){for (int j = 1; j <= 13; j++){cards[(i - 1) * 13 + j - 1] = new PKCard((i % n + 1) + "-" + j,this);}}this.randomCards();}public void randomCards(){PKCard temp = null;for (int i = 0; i < 52; i++){int a = (int) (Math.random() * 104);int b = (int) (Math.random() * 104);temp = cards[a];cards[a] = cards[b];cards[b] = temp;}}public void setNA(){a = 0;n = 0;}public void setCardsLocation(){table = new Hashtable();c = 0;finish = 0;n = 0;a = 0;int x = 883;int y = 580;for (int i = 0; i < 6; i++){for (int j = 0; j < 10; j++){int n = i * 10 + j;pane.add(cards[n]);cards[n].turnRear();cards[n].moveto(new Point(x, y));table.put(new Point(x, y), cards[n]);}x += 10;}x = 20;y = 45;for (int i = 10; i > 5; i--){for (int j = 0; j < 10; j++){int n = i * 10 + j;if (n >= 104) continue;pane.add(cards[n]);cards[n].turnRear();cards[n].moveto(new Point(x, y));table.put(new Point(x, y), cards[n]);x += 101;}x = 20;y -= 5;}}public void showEnableOperator(){int x = 0;out: while (true){Point point = null;PKCard card = null;do{if (point != null) n++;point = this.getLastCardLocation(n);while (point == null){point = this.getLastCardLocation(++n);if (n == 10) n = 0;x++;if (x == 10) break out;}card = (PKCard) this.table.get(point);}while (!card.isCardCanMove());while (this.getPreviousCard(card) != null&& this.getPreviousCard(card).isCardCanMove()) {card = this.getPreviousCard(card);}if (a == 10) a = 0;for (; a < 10; a++){if (a != n){Point p = null;PKCard c = null;do{if (p != null) a++;p = this.getLastCardLocation(a);int z = 0;while (p == null){p = this.getLastCardLocation(++a);if (a == 10) a = 0;if (a == n) a++;z++;if (z == 10) break out;}c = (PKCard) this.table.get(p);}while (!c.isCardCanMove());if (c.getCardValue() == card.getCardValue() + 1){card.flashCard(card);try{Thread.sleep(800);}catch (InterruptedException e){// TODO 自动生成catch 块e.printStackTrace();}c.flashCard(c);a++;if (a == 10) n++;break out;}}}n++;if (n == 10) n = 0;x++;if (x == 10) break out;}}public void deal(){this.setNA();for (int i = 0; i < 10; i++){if (this.getLastCardLocation(i) == null){JOptionPane.showMessageDialog(this, "有空位不能发牌!", "提示",JOptionPane.W ARNING_MESSAGE);return;}}int x = 20;for (int i = 0; i < 10; i++){Point lastPoint = this.getLastCardLocation(i);if (c == 0)lastPoint.y += 5;elselastPoint.y += 20;table.remove(cards[c + i].getLocation());cards[c + i].moveto(lastPoint);table.put(new Point(lastPoint), cards[c + i]);cards[c + i].turnFront();cards[c + i].setCanMove(true);this.pane.setComponentZOrder(cards[c + i], 1);Point point = new Point(lastPoint);if (cards[c + i].getCardValue() == 1){int n = cards[c + i].whichColumnAvailable(point);point.y -= 240;PKCard card = (PKCard) this.table.get(point);if (card != null && card.isCardCanMove()){this.haveFinish(n);}}x += 101;}c += 10;}public PKCard getPreviousCard(PKCard card){Point point = new Point(card.getLocation());point.y -= 5;card = (PKCard) table.get(point);if (card != null) return card;point.y -= 15;card = (PKCard) table.get(point);return card;}public PKCard getNextCard(PKCard card){Point point = new Point(card.getLocation());point.y += 5;card = (PKCard) table.get(point);if (card != null) return card;point.y += 15;card = (PKCard) table.get(point);return card;}public Point getLastCardLocation(int column){Point point = new Point(20 + column * 101, 25);PKCard card = (PKCard) this.table.get(point);if (card == null) return null;while (card != null){point = card.getLocation();card = this.getNextCard(card);}return point;}public Point getGroundLabelLocation(int column){return new Point(groundLabel[column].getLocation());}public void setGroundLabelZOrder(){for (int i = 0; i < 10; i++){pane.setComponentZOrder(groundLabel[i], 105 + i);}}public void haveFinish(int column){Point point = this.getLastCardLocation(column);PKCard card = (PKCard) this.table.get(point);do{this.table.remove(point);card.moveto(new Point(20 + finish * 10, 580));pane.setComponentZOrder(card, 1);this.table.put(card.getLocation(), card);card.setCanMove(false);point = this.getLastCardLocation(column);if (point == null)card = null;elsecard = (PKCard) this.table.get(point);}while (card != null && card.isCardCanMove());finish++;if (finish == 8){JOptionPane.showMessageDialog(this, "恭喜你,过关了!", "成功", JOptionPane.PLAIN_MESSAGE);}if (card != null)card.turnFront();card.setCanMove(true);}}}AraneidMenuBar.java程序import javax.swing.JMenuBar;import javax.swing.JMenu;import javax.swing.JMenuItem;import javax.swing.JRadioButtonMenuItem;import javax.swing.ButtonGroup;/** 创建日期2005-7-14 TODO 要更改此生成的文件的模板,请转至窗口-首选项-Java -代码样式-代码模板*//**download by * @author 叶少伟TODO 要更改此生成的类型注释的模板,请转至窗口-首选项-Java -代码样式-代码模板*/public class AraneidMenuBar extends JMenuBar{private Araneid main = null;private JMenu jMenu = null;private JMenu jMenu1 = null;private JMenuItem jMenuItem = null;private JMenuItem jMenuItem1 = null;private JMenuItem jMenuItem2 = null;private JRadioButtonMenuItem jRadioButtonMenuItem = null;private JRadioButtonMenuItem jRadioButtonMenuItem1 = null;private JRadioButtonMenuItem jRadioButtonMenuItem2 = null;private JMenuItem jMenuItem3 = null;private JMenuItem jMenuItem4 = null;/*** This is the default constructorpublic AraneidMenuBar(Araneid araneid){super();this.main = araneid;initialize();}/*** This method initializes this** @return void*/private void initialize(){this.add(getJMenu());this.add(getJMenu1());}/*** This method initializes jMenu** @return javax.swing.JMenu*/private JMenu getJMenu(){if (jMenu == null){jMenu = new JMenu();jMenu.setText("游戏");jMenu.add(getJMenuItem1());jMenu.add(getJMenuItem2());jMenu.add(getJMenuItem4());jMenu.addSeparator();jMenu.add(getJRadioButtonMenuItem());jMenu.add(getJRadioButtonMenuItem1());jMenu.add(getJRadioButtonMenuItem2());jMenu.addSeparator();jMenu.add(getJMenuItem3());jMenu.addMenuListener(new javax.swing.event.MenuListener() { public void menuSelected(javax.swing.event.MenuEvent e) {if(main.getC() < 60) getJMenuItem2().setEnabled(true);else getJMenuItem2().setEnabled(false);}public void menuDeselected(javax.swing.event.MenuEvent e) {}public void menuCanceled(javax.swing.event.MenuEvent e) {} });ButtonGroup group = new ButtonGroup();group.add(getJRadioButtonMenuItem());group.add(getJRadioButtonMenuItem1());group.add(getJRadioButtonMenuItem2());}return jMenu;}/*** This method initializes jMenu1** @return javax.swing.JMenu*/private JMenu getJMenu1(){if (jMenu1 == null){jMenu1 = new JMenu();jMenu1.setText("帮助");jMenu1.add(getJMenuItem());}return jMenu1;}/*** This method initializes jMenuItem** @return javax.swing.JMenuItem*/private JMenuItem getJMenuItem(){if (jMenuItem == null){jMenuItem = new JMenuItem();jMenuItem.setText("关于");jMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) {new AboutDialog(main);}});}return jMenuItem;}/*** This method initializes jMenuItem1** @return javax.swing.JMenuItem*/private JMenuItem getJMenuItem1(){if (jMenuItem1 == null){jMenuItem1 = new JMenuItem();jMenuItem1.setText("开局");jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) {main.newGame();}});}return jMenuItem1;}/*** This method initializes jMenuItem2** @return javax.swing.JMenuItem*/private JMenuItem getJMenuItem2(){if (jMenuItem2 == null){jMenuItem2 = new JMenuItem();jMenuItem2.setText("新一轮发牌");jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) {if(main.getC() < 60) main.deal();}});}return jMenuItem2;}/*** This method initializes jRadioButtonMenuItem** @return javax.swing.JRadioButtonMenuItem*/private JRadioButtonMenuItem getJRadioButtonMenuItem(){if (jRadioButtonMenuItem == null){jRadioButtonMenuItem = new JRadioButtonMenuItem();jRadioButtonMenuItem.setText("初级:单色");jRadioButtonMenuItem.setSelected(true);jRadioButtonMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) {main.setGrade(Araneid.EASY);main.initCards();main.newGame();}});}return jRadioButtonMenuItem;}/*** This method initializes jRadioButtonMenuItem1** @return javax.swing.JRadioButtonMenuItem*/private JRadioButtonMenuItem getJRadioButtonMenuItem1(){if (jRadioButtonMenuItem1 == null){jRadioButtonMenuItem1 = new JRadioButtonMenuItem();jRadioButtonMenuItem1.setText("中级:双色");jRadioButtonMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) {main.setGrade(Araneid.NA TURAL);main.initCards();main.newGame();}});}return jRadioButtonMenuItem1;}/*** This method initializes jRadioButtonMenuItem2** @return javax.swing.JRadioButtonMenuItem*/private JRadioButtonMenuItem getJRadioButtonMenuItem2(){if (jRadioButtonMenuItem2 == null){jRadioButtonMenuItem2 = new JRadioButtonMenuItem();jRadioButtonMenuItem2.setText("高级:四色");jRadioButtonMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) {main.setGrade(Araneid.HARD);main.initCards();main.newGame();}});}return jRadioButtonMenuItem2;}/*** This method initializes jMenuItem3** @return javax.swing.JMenuItem*/private JMenuItem getJMenuItem3(){if (jMenuItem3 == null){jMenuItem3 = new JMenuItem();jMenuItem3.setText("退出");jMenuItem3.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(java.awt.event.ActionEvent e) {main.dispose();System.exit(0);}});}return jMenuItem3;}/*** This method initializes jMenuItem4** @return javax.swing.JMenuItem*/private JMenuItem getJMenuItem4() {if (jMenuItem4 == null) {jMenuItem4 = new JMenuItem();jMenuItem4.setText("显示可行操作");jMenuItem4.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(java.awt.event.ActionEvent e) {new Show().start();}});}return jMenuItem4;}class Show extends Thread{public void run(){main.showEnableOperator();}}}PKCard.java程序import java.awt.*;import java.awt.event.*;import javax.swing.*;/** 创建日期2005-7-12 TODO 要更改此生成的文件的模板,请转至窗口-首选项-Java -代码样式-代码模板*//**download by * @author 叶少伟TODO 要更改此生成的类型注释的模板,请转至窗口-首选项-Java -代码样式-代码模板*/public class PKCard extends JLabel implements MouseListener,MouseMotionListener{private Point point = null;private Point initPoint = null;private int value = 0;private int type = 0;private String name = null;private Container pane = null;private Araneid main = null;private boolean canMove = false;private boolean isFront = false;private PKCard previousCard = null;/** (非Javadoc)** @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent) */public void mouseClicked(MouseEvent arg0){// TODO 自动生成方法存根}public void flashCard(PKCard card){new Flash(card).start();if(main.getNextCard(card) != null)card.flashCard(main.getNextCard(card));}class Flash extends Thread{private PKCard card = null;public Flash(PKCard card){this.card = card;}public void run(){boolean is = false;ImageIcon icon = new ImageIcon("images/white.gif");for (int i = 0; i < 4; i++){try{Thread.sleep(200);}catch (InterruptedException e){// TODO 自动生成catch 块e.printStackTrace();}if (is){this.card.turnFront();is = !is;}else{this.card.setIcon(icon);is = !is;}card.updateUI();}}}/** (非Javadoc)** @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent) */public void mousePressed(MouseEvent arg0){// TODO 自动生成方法存根point = arg0.getPoint();main.setNA();this.previousCard = main.getPreviousCard(this);// System.out.println(((PKCard) arg0.getSource()).initPoint);// System.out.println(((PKCard) arg0.getSource()).getCardType());// System.out.println();}/** (非Javadoc)** @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent) */public void mouseReleased(MouseEvent arg0){// TODO 自动生成方法存根Point point = ((JLabel) arg0.getSource()).getLocation();int n = this.whichColumnAvailable(point);if (n == -1 || n == this.whichColumnAvailable(this.initPoint)){this.setNextCardLocation(null);main.table.remove(this.getLocation());this.setLocation(this.initPoint);main.table.put(this.initPoint, this);return;}point = main.getLastCardLocation(n);boolean isEmpty = false;PKCard card = null;if (point == null){point = main.getGroundLabelLocation(n);isEmpty = true;}else{card = (PKCard) main.table.get(point);}if (isEmpty || (this.value + 1 == card.getCardValue())){point.y += 40;if (isEmpty) point.y -= 20;this.setNextCardLocation(point);main.table.remove(this.getLocation());point.y -= 20;this.setLocation(point);main.table.put(point, this);this.initPoint = point;if (this.previousCard != null){this.previousCard.turnFront();this.previousCard.setCanMove(true);}this.setCanMove(true);}else{this.setNextCardLocation(null);main.table.remove(this.getLocation());this.setLocation(this.initPoint);main.table.put(this.initPoint, this);return;}point = main.getLastCardLocation(n);card = (PKCard) main.table.get(point);if (card.getCardValue() == 1){point.y -= 240;card = (PKCard) main.table.get(point);if (card != null && card.isCardCanMove()){main.haveFinish(n);}}}public void setNextCardLocation(Point point){PKCard card = main.getNextCard(this);if (card != null){if (point == null){card.setNextCardLocation(null);main.table.remove(card.getLocation());card.setLocation(card.initPoint);main.table.put(card.initPoint, card);}else{point = new Point(point);point.y += 20;card.setNextCardLocation(point);point.y -= 20;main.table.remove(card.getLocation());card.setLocation(point);main.table.put(card.getLocation(), card);card.initPoint = card.getLocation();}}}public int whichColumnAvailable(Point point){int x = point.x;int y = point.y;int a = (x - 20) / 101;int b = (x - 20) % 101;if (a != 9){if (b > 30 && b <= 71)a = -1;else if (b > 71) a++;}else if (b > 71){a = -1;}if (a != -1){Point p = main.getLastCardLocation(a);if (p == null) p = main.getGroundLabelLocation(a);b = y - p.y;if (b <= -96 || b >= 96) a = -1;}return a;}/** (非Javadoc)** @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent) */public void mouseEntered(MouseEvent arg0){// TODO 自动生成方法存根}/** (非Javadoc)** @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)*/public void mouseExited(MouseEvent arg0){// TODO 自动生成方法存根}/** (非Javadoc)** @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent) */public void mouseDragged(MouseEvent arg0){// TODO 自动生成方法存根if (canMove){int x = 0;int y = 0;Point p = arg0.getPoint();x = p.x - point.x;y = p.y - point.y;this.moving(x, y);}}public void moving(int x, int y){PKCard card = main.getNextCard(this);Point p = this.getLocation();pane.setComponentZOrder(this, 1);main.table.remove(p);p.x += x;p.y += y;this.setLocation(p);main.table.put(p, this);if (card != null) card.moving(x, y);}/** (非Javadoc)** @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)*/public void mouseMoved(MouseEvent arg0){// TODO 自动生成方法存根}/*** This is the default constructor*/public PKCard(String name, Araneid araneid){super();this.type = new Integer(name.substring(0, 1)).intValue();this.value = new Integer(name.substring(2)).intValue(); = name;this.main = araneid;this.pane = this.main.getContentPane();this.addMouseListener(this);this.addMouseMotionListener(this);this.setIcon(new ImageIcon("images/rear.gif"));this.setSize(71, 96);this.setVisible(true);}public void turnFront(){this.setIcon(new ImageIcon("images/" + name + ".gif"));this.isFront = true;}public void turnRear(){this.setIcon(new ImageIcon("images/rear.gif"));this.isFront = false;this.canMove = false;}public void moveto(Point point){this.setLocation(point);this.initPoint = point;}public void setCanMove(boolean can){this.canMove = can;PKCard card = main.getPreviousCard(this);if (card != null && card.isCardFront()){if (!can){if (!card.isCardCanMove())return;elsecard.setCanMove(can);}else{if (this.value + 1 == card.getCardValue()&& this.type == card.getCardType()) {card.setCanMove(can);}elsecard.setCanMove(false);}}}public boolean isCardFront(){return this.isFront;}public boolean isCardCanMove(){return this.canMove;}public int getCardValue(){return value;}public int getCardType(){return type;。
C 纸牌小游戏代码
![C 纸牌小游戏代码](https://img.taocdn.com/s3/m/b4cbe4ad0242a8956aece43e.png)
C 纸牌小游戏代码/*项目三*/using System;using System.Collections.Generic; using System.Text;using System.Threading;namespace ConsoleApplication2 {class Game{string[] str = new string[52];int[] number = new int[52];int i = 0;int[] a = new int[4];int[] b = new int[4];int[] c = new int[4];int[] d = new int[4];int[] e = new int[4];Random ra = new Random(unchecked((int)DateTime.Now.Ticks)); public void getnum(int[] number, int minnum, int maxnum) {int flag;flag = number[i] = ra.Next(0, 52);int f = 0;while (f < i){if (number[f] == flag)getnum(number, 0, 52);f++;}}public void GetRandomNum()//给number随机赋从0到51不同的值 {while (i < 52){int flag;flag = number[i] = ra.Next(0, 52);int f = 0;while (f < i){if (number[f] == flag){getnum(number, 0, 52);break;}f++;}i++;}}public void EnterCard()//给每个字符串数组赋上牌值{str[0] = "1 of the club";str[1] = "2 of the club";str[2] = "3 of the club";str[3] = "4 of the club";str[4] = "5 of the club"; str[5] = "6 of the club";str[6] = "7 of the club";str[7] = "8 of the club";str[8] = "9 of the club";str[9] = "10 of the club";str[10] = "Jack of the club";str[11] = "queen of the club";str[12] = "king of the club";str[13] = "1 of the diamond";str[14] = "2 of the diamond";str[15] = "3 of the diamond"; str[16] = "4 of the diamond"; str[17] = "5 of the diamond";str[18] = "6 of the diamond";str[19] = "7 of the diamond";str[20] = "8 of the diamond"; str[21] = "9 of the diamond";str[22] = "10 of the diamond"; str[23] = "Jack of the diamond"; str[24] = "queen of the diamond";str[25] = "king of the diamond";str[26] = "1 of the heart";str[27] = "2 of the heart";str[28] = "3 of the heart";str[29] = "4 of the heart";str[30] = "5 of the heart";str[31] = "6 of the heart";str[32] = "7 of the heart";str[33] = "8 of the heart";str[34] = "9 of the heart";str[35] = "10 of the heart";str[36] = "Jack of the heart";str[37] = "queen of the heart"; str[38] = "king of the heart";str[39] = "1 of the spade";str[40] = "2 of the spade";str[41] = "3 of the spade";str[42] = "4 of the spade";str[43] = "5 of the spade";str[44] = "6 of the spade";str[45] = "7 of the spade";str[46] = "8 of the spade";str[47] = "9 of the spade";str[48] = "10 of the spade"; str[49] = "Jack of the spade"; str[50] = "queen of the spade";str[51] = "king of the spade";}public void FaPai(int PersonNum)//发牌{for (int j = 0; j < PersonNum; j++){a[j] = number[j * 5];b[j] = number[j * 5 + 1];c[j] = number[j * 5 + 2];d[j] = number[j * 5 + 3]; e[j] = number[j * 5 + 4];}}public void Print(string[me, i] Pernt j)sonNa//显示玩家的牌{Console.WriteLine("玩家{0}的牌", PersonName[j]);Console.WriteLine("1. {0}", str[a[j]]);Console.WriteLine("2. {0}", str[b[j]]);Console.WriteLine("3. {0}", str[c[j]]);Console.WriteLine("4. {0}", str[d[j]]);Console.WriteLine("5. {0}", str[e[j]]);}public void Print1(string[] PersonName, int j)//显示玩家的牌 { Console.WriteLine("玩家{0}剩下的牌", PersonName[j]);Console.WriteLine("1. {0}", str[a[j]]);Console.WriteLine("2. {0}", str[b[j]]);Console.WriteLine("3. {0}", str[c[j]]); Console.WriteLine("4. {0}", str[d[j]]);Console.WriteLine("5. {0}", str[e[j]]);Console.WriteLine("按ENTER建进入下一个玩家");Console.ReadLine();}public bool CompareAns(int j, string[] PersonName, int n, bool bool2)//对玩家的牌与胜利的结果进行比较{int min = 0, max = 0;max = (a[j] > b[j]) ? a[j] : b[j];max = (c[j] > max) ? c[j] : max;max = (d[j] > max) ? d[j] : max;max = (e[j] > max) ? e[j] : max;min = (a[j] < b[j]) ? a[j] : b[j];min = (c[j] < min) ? c[j] : min;min = (d[j] < min) ? d[j] : min;min = (e[j] < min) ? e[j] : min;if (min >= 0 && max < 13 || min >= 13 && max < 26 || min >= 26 && max < 39|| min >= 39 && max < 52){Console.Clear();Console.WriteLine("恭喜玩家{0}赢得游戏~", PersonName[j]);bool2 = false;}//判断是否还有底牌可供玩家拿取else if (n==52){Console.Clear();Console.WriteLine("没有底牌了~~重新开始。
记忆益智游戏代码
![记忆益智游戏代码](https://img.taocdn.com/s3/m/c05549642bf90242a8956bec0975f46527d3a7f4.png)
记忆益智游戏代码开发一个记忆游戏,你可以选择创建一个简单的卡片匹配游戏,其中玩家需要记住不同卡片的位置,并在翻转后匹配相同的卡片。
以下是一个使用Python和pygame 库创建基本记忆游戏的步骤指南。
步骤1: 安装pygame如果你还没有安装pygame,你可以通过pip来安装:bash复制代码pip install pygame步骤2: 初始化游戏窗口和设置python复制代码import pygameimport random# 初始化pygamepygame.init()# 设置屏幕大小和标题WIDTH, HEIGHT = 800, 600screen = pygame.display.set_mode((WIDTH, HEIGHT))pygame.display.set_caption('记忆游戏')# 颜色定义WHITE = (255, 255, 255)BLACK = (0, 0, 0)# 设置帧率FPS = 30clock = pygame.time.Clock()# 字体和得分font = pygame.font.SysFont(None, 55)score_text = font.render("Score: 0", True, WHITE)score = 0# 游戏状态game_active = Truegame_over = Falsecards_flipped = 0card_one = Nonecard_two = Nonematching_cards = 0# 卡片类和列表class Card:def__init__(self, x, y, image):self.image = imageself.rect = self.image.get_rect()self.rect.x = xself.rect.y = yself.flipped = Falsecard_images = [pygame.image.load('card1.png'),pygame.image.load('card2.png')] # 替换为你的图片路径cards = []for i in range(2): # 两对卡片作为示例for j in range(2): # 每对卡片有两个card = Card(100 + j * 200, 100 + i * 200, card_images[i])cards.append(card)# 打乱卡片顺序(可选)random.shuffle(cards)步骤3: 游戏主循环和事件处理python复制代码def draw_cards():for card in cards:if card.flipped:screen.blit(card.image, card.rect)else:pygame.draw.rect(screen, WHITE, card.rect)running = Truewhile running:screen.fill(BLACK)for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseelif event.type== pygame.MOUSEBUTTONDOWN and game_active and not game_over:mouse_x, mouse_y = pygame.mouse.get_pos()for card in cards:if card.rect.collidepoint((mouse_x, mouse_y)):if not card.flipped:card.flipped = Trueif cards_flipped == 0:card_one = cardelif cards_flipped == 1:card_two = cardcards_flipped += 1if cards_flipped == 2:if card_one.image == card_two.image:matching_cards += 2pygame.time.wait(1000) # 等待1秒card_one.flipped = Falsecard_two.flipped = Falsecards.remove(card_one)cards.remove(card_two)card_one = Nonecard_two = Nonecards_flipped = 0if game_active and len(cards) == 0:game_over = Truescore = matching_cardsif game_over:score_text = font.render("Score: " + str(score), True, WHITE) screen.blit(score_text, (WIDTH // 2 - score_text.get_width() // 2, HEIGHT // 2 - score_text.get_height() // 2))pygame.display.flip()pygame.time.wait(2000) # 等待2秒然后退出running = Falseelse:draw_cards()pygame.display.flip()clock.tick(FPS)pygame.quit()步骤4: 添加图片和声音(可选)为了增加游戏体验,你可以添加自己的卡片图片和声音效果。
C语言写一个随机发牌的游戏程序
![C语言写一个随机发牌的游戏程序](https://img.taocdn.com/s3/m/3b7dd4aa0029bd64783e2cb2.png)
2.7.1.3 练习3 写一个随机发牌的游戏程序要求:输入发牌数n,然后随机发出n张不同的牌,用数字0-53表示一副扑克牌//card_game.c#include<stdio.h>#include<stdlib.h>#include<time.h>#define NULL 0int begin(){int n;printf("Input cards you want(num>0):");scanf("%d",&n);return n;}void Exit(void){char ch;printf("Press <Q> to end...");scanf("%c",&ch);if(ch=='Q'||ch=='q')exit(0);}int deal(void){int card;card=rand()%54;return card;}void play(){int n=begin();int a[54],i;srand(time(NULL));a[0]=deal();for(i=1;i<n;i++)for(;;){int num=deal();int flag=1;for(int j=0;j<i;j++)if(a[j]==num){flag=0;break;}if(flag){a[i]=num;break;}}for(i=0;i<n;i++)printf("%d\t",a[i]);printf("\n");scanf("%*c");}void welcome(){printf("+-----------------------------+\n");printf(" Welcome to Play Card_Game.\n");printf("+-----------------------------+\n");}int main(){while(1){welcome();play();Exit();}return 0;}注意:1)发牌时候一共有54张不同的牌,使用随机函数是注意判断不能使得发过的牌重新被发,所以在play()函数中需要判断新发的牌是否为之前发过的牌。
扑克牌小游戏c++代码
![扑克牌小游戏c++代码](https://img.taocdn.com/s3/m/48437f8ab9d528ea81c77912.png)
#include <iostream.h>#include <string.h>#include <conio.h>#include <stdlib.h>#include <stdio.h>#include <time.h>class Playing_Card{private:int m_Value;char m_Face[3];char m_Suit ;public:Playing_Card();void showcard();void Card_Make(int);};class Deck{private:Playing_Card m_cardarray[54];int m_lastdelt;public:Deck();void MakeDeck() ;void Deal_One();void ShowDeck();void DeckShuff(int);void Remove_Card();void Senddeck();};void Program_Init();int main();void Center_Text(char []);int get_number();char Get_Key();void DeckMakeDriver();int getRandInt(int min, int max); void prog_close();int main()srand( (unsigned)time( NULL ) );int Card_Number = 0;Program_Init();DeckMakeDriver();prog_close();//退出return 1;}Playing_Card::Playing_Card(){int i;for(i=1;i<=3;){m_Face[i] = ' ';i++;}m_Suit = ' ';m_Value = 0;}//******************************************************************* void Program_Init()//显示初始界面{Center_Text("C++课程设计实验报告");cout << endl;cout<<endl;Center_Text("扑克牌相关");cout << endl <<"\n" ; cout<<endl;Center_Text("设计:郇志伟");cout << endl <<"\n" ;cout<<endl;Center_Text("2006-9-20");cout << endl <<"\n" ;Center_Text("Hit the <Enter> key to Continue..");cin.get();}//******************************************************************* char Get_Key(){char x;x = cin.get();cout << endl;return x;}void Playing_Card::showcard(){cout << " ";cout << m_Face ;cout.width(1);cout << m_Suit;cout << " ";}//******************************************************************* void Center_Text(char ShellText[80]){int length;int center;length= strlen(ShellText);center = (80 - length)/2;for(;center!=0;center--){cputs(" ");}cputs(ShellText);}int get_number(){int Input_Integer = 0;Center_Text("Please enter an integer between 0 and 53. 54to quit.");cout << endl;cin >> Input_Integer;return Input_Integer;}//******************************************************************* void Playing_Card::Card_Make(int num){int i = 0;char j;if(num==53){strcpy(m_Face,"jo");m_Suit='2';m_Value=15;}if(num==52){strcpy(m_Face,"jo");m_Suit='1';m_Value=14;}if(num<=51){int face_num = num % 13;switch(face_num){case 0: strcpy(m_Face," A");break;case 9: strcpy(m_Face,"10");break;case 10: strcpy(m_Face," J");break;case 11: strcpy(m_Face," Q");break;case 12: strcpy(m_Face," K");break;default:j = char(face_num + 49);if(i<3){m_Face[i] = ' '; i++;m_Face[i] = j;i++;m_Face[i] = NULL;break;}}if(num <= 12)m_Suit = 6;if(num >12 && num <= 25)m_Suit = 3;if(num >25 && num <= 38)m_Suit = 5;if(num >38 && num <= 51)m_Suit = 4;if(face_num <= 9)m_Value = face_num + 1;if(face_num >= 10)m_Value = 10;}}//******************************************************************* void DeckMakeDriver(){Deck deck_1;deck_1.MakeDeck();//创建一副扑克deck_1.ShowDeck();//显示一副扑克Get_Key();deck_1.DeckShuff(250);//洗牌deck_1.ShowDeck();//显示一副扑克Get_Key();deck_1.Senddeck();//依次分发给4个人并显示Get_Key();cout << endl <<endl << endl;char y;do{deck_1.Deal_One();//删除一张牌cout << endl;cout << endl << endl << "Y to Deal One more N to quit"<< endl;cin >> y;y = toupper(y);}while(y == 'Y' );}//******************************************************************* void Deck::MakeDeck() //创建一副扑克{m_lastdelt = 53;while(m_lastdelt >-1){m_cardarray[m_lastdelt].Card_Make(m_lastdelt);m_lastdelt--;}}//******************************************************************* void Deck::ShowDeck() //显示一副扑克{int index = m_lastdelt + 1;int newline = 0;Center_Text("Current Deck of Cards from top to bottom");cout << endl;while(index<=53){if(newline % 11== 0) cout << endl;m_cardarray[index].showcard();newline++;index++;}cout<<endl;}//*******************************************************************int getRandInt(int min, int max){int numToReturn;numToReturn = rand();numToReturn = numToReturn % (max - min + 1) + min;return numToReturn;}//******************************************************************* void Deck::DeckShuff( int times) //洗牌{int x, split;Center_Text("Shuffling Deck");cout << endl;for(x=0;x<=times;x++){split = getRandInt(20,35);Deck topdeck;Deck bottomdeck;int i;int bottomdeckindex = 1;int topdeckindex = 1;for(i=0;i<=split - 1;){topdeck.m_cardarray[topdeckindex] = this->m_cardarray[i];topdeckindex++;i++;}for(i=(split);i< 54;){bottomdeck.m_cardarray[bottomdeckindex] = this->m_cardarray[i];bottomdeckindex++;i++;}int deckoutindex = 0;int numcardstomovetop;int numcardstomovebottom;int j;int h = 0;bottomdeckindex = 54 - split;topdeckindex =split;while(deckoutindex <= 53){numcardstomovetop = getRandInt(2,7);numcardstomovebottom = getRandInt(2,7);for(j=0;j <=numcardstomovebottom;j++){if(bottomdeckindex > 0){this->m_cardarray[deckoutindex] = bottomdeck.m_cardarray[bottomdeckindex];deckoutindex++;bottomdeckindex--;}for(h=0;h<=numcardstomovetop;h++){if((topdeckindex > 0) && (deckoutindex <=54)){this->m_cardarray[deckoutindex]=topdeck.m_cardarray[topdeckindex];deckoutindex++;topdeckindex--;}}}}}this->m_lastdelt = -1;}//*******************************************************************void Deck::Senddeck()//依次分发给4个人并显示{int m_player,n_player;int player1=0,player2=0,player3=0,player4=0;this->m_lastdelt=53;Playing_Card playeri[2][14];Playing_Card playerj[2][13];int time=0;while(time<13){m_player=0,n_player=0;playeri[m_player][player1]=this->m_cardarray[m_lastdelt];m_player++;player1++;m_lastdelt--;playeri[m_player][player2]=this->m_cardarray[m_lastdelt];player2++;m_lastdelt--;playerj[n_player][player3]=this->m_cardarray[m_lastdelt];n_player++;player3++;m_lastdelt--;playerj[n_player][player4]=this->m_cardarray[m_lastdelt];player4++;m_lastdelt--;time++;}playeri[0][13]=this->m_cardarray[1];playeri[1][13]=this->m_cardarray[0];for(int i=0;i<=3;i++){cout<<"player"<<i+1<<":";if(i<=1){for(int j=0;j<=13;j++){playeri[i][j].showcard();}}else{for(int j=0;j<=12;j++){playerj[i-2][j].showcard();}}cout<<'\n';}}//******************************************************************* void prog_close()//退出{cout << endl << endl;cout << " Hit the <Enter> key to Continue.." << endl;cout << endl << endl;Get_Key();cin.get();}//******************************************************************* void Deck::Remove_Card()//删除一张牌。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#include<stdio.h>#include<stdlib.h>#include<time.h>int outputacard(int a,int b) //输出一张扑克{if(b==11){printf("[%c",a); //Jprintf("%c]",b+63);}else if(b==12){printf("[%c",a); //Qprintf("%c]",b+69);}else if(b==13){printf("[%c",a); //Kprintf("%c]",b+62);}else if(b==1){printf("[%c",a); //Aprintf("%c]",b+64);}else if(b==88)printf("[%c%c]",a,b); //XXelse{printf("[%c",a); //随机输出8张扑克printf("%d]",b);}}int main(){int puke[8][2];int i,j,k;srand((unsigned int)time(NULL));printf("记住下面牌的顺序\n准备好了按<回车>,我会提问你的^-^\n");for(i=0; i<8; i++)for(j=0; j<2; j++){if(j==0)puke[i][j]=3+rand()%3; /*红心是003 方块004 梅花005 黑桃006*/elsepuke[i][j]=1+rand()%12; //A……K}for(k=0; k<8; k++)outputacard(puke[k][0],puke[k][1]); //随机输出8张扑克printf("\n");int puke2[8][2];int puke0[2];int t,rh;for(t=0; t<8; t++){puke2[t][0]=puke[t][0];puke2[t][1]=puke[t][1];}for(t=0; t<8; t++) /*把上面的8张扑克打乱顺序存入另一个数组*/{rh=rand()%7;if(rh!=t){puke0[0]=puke2[t][0];puke0[1]=puke2[t][1];puke2[t][0]=puke2[rh][0];puke2[t][1]=puke2[rh][1];puke2[rh][0]=puke0[0];puke2[rh][1]=puke0[1];}}for(k=0; k<8; k++)outputacard(puke2[k][0],puke2[k][1]); /*打乱顺序后重新输出8张扑克*/printf("\n");int puke3[8][2],puke4[8][2];for(i=0; i<8; i++) /*为把上面代表两组扑克的数组puke,puke2复制到另外*/for(j=0; j<2; j++) /*两个数组puke3、puke4中,以方便后面输出*/for(j=0; j<2; j++){puke3[i][j]=88;puke4[i][j]=88;}system("pause");system("CLS");int a,b,num=0;int alp1[8]= {0,0,0,0,0,0,0,0},alp2[8]= {0,0,0,0,0,0,0,0}; /* 记录各个位置的牌是否翻开*/while(alp1[0]==0||alp1[1]==0||alp1[2]==0||alp1[3]==0||alp1[4]==0||alp1[5]==0||alp1[6]==0||alp1[7]==0){printf("依次输入第一行、第二行两张相同的牌的位置\n");for(k=0; k<8; k++)outputacard(puke3[k][0],puke3[k][1]);printf("\n");for(k=0; k<8; k++)outputacard(puke4[k][0],puke4[k][1]);printf("\n");scanf("%d%d",&a,&b);num++;system("CLS");if(puke[a-1][0]==puke2[b-1][0]&&puke[a-1][1]==puke2[b-1][1]&&alp1[a-1]!=1&&alp2 [b-1]!=1&&a>=1&&a<=8&&b>=1&&b<=8){/*如果两张牌相同且没有被翻开过且输入的数字大于0小于8复制puke,puke2中这两个元素的数据到puke3,puke4中,并输出puke3,puke4*/puke3[a-1][0]=puke[a-1][0];puke3[a-1][1]=puke[a-1][1];alp1[a-1]++;puke4[b-1][0]=puke2[b-1][0];puke4[b-1][1]=puke2[b-1][1];alp2[b-1]++;printf("猜对了,厉害!\n");for(k=0; k<8; k++)outputacard(puke3[k][0],puke3[k][1]);printf("\n");for(k=0; k<8; k++)outputacard(puke4[k][0],puke4[k][1]);printf("\n");system("pause");system("CLS");}else if(alp1[a-1]!=1&&alp2[b-1]!=1&&a>=1&&a<=8&&b>=1&&b<=8){/*如果两张牌不相同但没有被翻开过且输入的数字大于0小于9输出原puke3,puke4并显示该位置正确的牌*/printf("你好像记错了,再想想,我相信你!\n");for(i=0; i<8; i++){if(i==a-1)outputacard(puke[i][0],puke[i][1]);elseoutputacard(puke3[i][0],puke3[i][1]);}printf("\n");for(k=0; k<8; k++){if(k==b-1){outputacard(puke2[k][0],puke2[k][1]);}elseoutputacard(puke4[k][0],puke4[k][1]);}printf("\n");system("pause");system("CLS");}else if(a>=1&&a<=8&&b>=1&&b<=8) /*如果这两张牌中任意一张已经被翻开,输出如下*/{printf("这两张牌中的某一张好像已经被你翻开了哦\n");for(k=0; k<8; k++)outputacard(puke3[k][0],puke3[k][1]);printf("\n");for(k=0; k<8; k++)outputacard(puke4[k][0],puke4[k][1]);printf("\n");system("pause");system("CLS");}else{printf("每行只有8张牌呦,请输入正确的位置,么么哒\n");for(k=0; k<8; k++)outputacard(puke3[k][0],puke3[k][1]);printf("\n");for(k=0; k<8; k++)outputacard(puke4[k][0],puke4[k][1]); printf("\n");system("pause");system("CLS");}}printf("你一共猜了%d次\n",num);if(num==8)printf("完美!!!\n");else if(num>8&&num<=10)printf("非常棒!\n");else if(num>10&&num<=16)printf("你的记忆力挺不错的!\n");elseprintf("你的记忆力一般般啦,再练练吧!\n"); system("pause");return 0;}。