C++五子棋编写(控制台版_CMD命令框版)【简单五子棋游戏,适合初学者学习,代码有详细注释】
用C语言实现五子棋小游戏

⽤C语⾔实现五⼦棋⼩游戏简介本次五⼦棋使⽤的是光标控制移动,通过按空格键(键值32)来落⼦,实现游戏的。
我们额外⽤到的头⽂件有:#include<getch.h> 通过调⽤getch()函数来识别上下左右以及空格的操作。
#include<stdlib.h> 采⽤ system(“clear”);清理屏幕,实现视觉上的⾛动效果。
include<stdbool.h>stdbool.h 头⽂件对布尔类型进⾏了模拟返回 true false⼤致思路需要的数据:(全局)1、定义棋盘⼆维数组 15* 15 空位置 ' * '2、定义棋⼦⾓⾊变量⽩棋为 ' $ ' ⿊棋为 ' @ '3、定义变量⽤于记录下棋的位置业务逻辑:(实现成⼀个个函数)是否需要初始化for( ; ; ){ 1、清理屏幕、打印棋盘 2、落⼦ 坐标合法、该位置不能有棋⼦,否则继续落⼦ 3、判断是否五⼦连珠 4、交换⾓⾊}代码#include<stdio.h>#include<stdlib.h>#include<stdbool.h>#include<getch.h>//定义棋盘char board[15][15];//⾓⾊char role='@';//落⼦坐标char key_x=7,key_y=7;//棋盘初始化void init_board(void){for(int i=0;i<15;i++){for(int j=0;j<15;j++){board[i][j]='*';}}}//打印棋盘void show_board(void){system("clear");for(int i=0;i<15;i++){for(int j=0;j<15;j++){printf(" %c",board[i][j]);printf("\n");}}//落⼦void get_key(void){for(;;){printf("\33[%d;%dH",key_x+1,2*key_y+2);//光标位置,(key_y+1)*2是因为列与列之间有空格 switch(getch()){case 183:key_x>0 && key_x--;break; //上,改变光标位置值case 184:key_x<14 && key_x++;break; //下case 185:key_y<14 && key_y++;break; //右case 186:key_y>0 && key_y--;break;//左case 32: //空格if('*'==board[key_x][key_y])//如果落⼦位置为空,落⼦{board[key_x][key_y]=role;return;}}}}//记录落⼦位置某个⽅向,连⼦的个数int count_board(int go_x,int go_y){int count=0;for(int x=key_x+go_x,y=key_y+go_y;x>=0 && y>=0 && x<15 && y<15;x+=go_x,y+=go_y){if(board[x][y]==board[key_x][key_y]){count++;}else{break;}}return count;}//判断五⼦连珠,是否胜利bool is_win(void){if(count_board(0,-1)+count_board(0,1)>=4){return true;}if(count_board(-1,-0)+count_board(1,0)>=4){return true;}if(count_board(-1,-1)+count_board(1,1)>=4){return true;}if(count_board(1,-1)+count_board(-1,1)>=4){return true;}return false;}int main(int argc,const char* argv[]){//初始化棋盘init_board();for(int i=0;i<255;i++){//清屏,打印棋盘show_board();//落⼦get_key();//是否五⼦连珠if(is_win())system("clear");show_board();printf("游戏结束,%c赢了\n",role); return 0;}//交换⾓⾊role=role=='@'?'$':'@';}}效果图以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
C语言实现简易五子棋

C语⾔实现简易五⼦棋本⽂实例为⼤家分享了C语⾔实现简易五⼦棋的具体代码,供⼤家参考,具体内容如下#define _CRT_SECURE_NO_WARNINGS#include<stdio.h>#include<stdlib.h>#include<time.h>#define ROW 5#define COL 5char g_broad[ROW][COL];void menu();void menu(){printf("-----------------------\n");printf("------1.开始游戏-------\n");printf("------0.结束游戏-------\n");printf("-----------------------\n");printf("请输⼊您的选择:");}void Init(char broad[ROW][COL]){for (int row = 0; row < ROW; ++row){for (int col = 0; col < COL; ++col){broad[row][col] = ' ';}}}void print(char broad[ROW][COL]){for (int row = 0; row < ROW; ++row){printf("| %c | %c | %c | %c | %c |\n", broad[row][0],broad[row][1], broad[row][2], broad[row][3],broad[row][4]);if (row != ROW - 1){printf(" ---|---|---|---|--- \n");}}}void playermove(char broad[ROW][COL]){printf("玩家落⼦:\n");while (1){printf("玩家请输⼊⼀组坐标:(row col)");int row = 0;int col = 0;scanf("%d %d", &row, &col);if (row < 0 || row >= ROW || col < 0 || col >= COL){printf("您输⼊的坐标⾮法,请重新输⼊:\n");continue;}else if (broad[row][col] != ' '){printf("该位置已经被占⽤,请重新输⼊:\n");continue;}else{broad[row][col] = 'x';break;}}}void computermove(char broad[ROW][COL]){printf("电脑落⼦:\n");while (1){int row = rand() % ROW;int col = rand() % COL;if (broad[row][col] != ' '){continue;}else{broad[row][col] = 'o';break;}}}int Isfull(char broad[ROW][COL]){for (int row = 0; row < ROW; ++row){for (int col = 0; col < COL; ++col){if (broad[row][col] == ' ')return 0;}}return 1;}char checkwinner(char broad[ROW][COL]) {for (int row = 0; row < ROW; ++row){if (broad[row][0] == broad[row][1]&& broad[row][0] == broad[row][2]&& broad[row][0] == broad[row][3]&& broad[row][0] == broad[row][4]&& broad[row][0] != ' '){return broad[row][0];}}for (int col = 0; col < COL; ++col){if (broad[0][col] == broad[1][col]&& broad[0][col] == broad[2][col]&& broad[0][col] == broad[3][col]&& broad[0][col] == broad[4][col]&& broad[0][col] != ' '){return broad[0][col];}}if (broad[0][0] == broad[1][1]&& broad[0][0] == broad[2][2]&& broad[0][0] == broad[3][3]&& broad[0][0] == broad[4][4]&& broad[0][0] != ' '){return broad[0][0];}if (broad[0][4] == broad[1][3]&& broad[0][4] == broad[2][2]&& broad[0][4] == broad[3][1]&& broad[0][4] == broad[4][0]&& broad[4][0] != ' '){return broad[4][0];}if (Isfull(broad)){return 'p';}elsereturn ' ';}int main(){srand((unsigned int)time(0));int input = 0;menu(g_broad); //初始化棋盘,将棋盘初始化成' 'Init(g_broad);scanf("%d", &input);char winner = ' ';while (input){//第⼀次打印棋盘print(g_broad);//玩家输⼊,提⽰玩家输⼊⼀组坐标,检查游戏是否结束 playermove(g_broad);winner = checkwinner(g_broad);if (winner != ' '){break;}//电脑输⼊,瞎下,检查游戏是否结束computermove(g_broad);winner = checkwinner(g_broad);if (winner != ' '){break;}}if (winner == 'x'){printf("玩家胜利!\n");print(g_broad);}if (winner == 'o'){printf("电脑胜利!\n");print(g_broad);}if (winner == 'p'){printf("和棋!\n");print(g_broad);}if (winner == ' '){printf("游戏结束!goodbay~\n");return 0;}return 0;}游戏运⾏结果如下:注:使⽤宏定义可以扩充棋盘更多有趣的经典⼩游戏实现专题,分享给⼤家:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
五子棋游戏C语言

五子棋游戏程序设计(C语言实现)一、设计任务与目标设计两个人对战的五子棋游戏,游戏开始界面是显示游戏的规则,然后让用户输入命令以确定游戏是否开始,如果用户确定开始,那么要显示棋盘,接下来到了最重要的几步,两个玩家交替落子,当连续五个棋子在一条直线上时,一方赢棋,游戏结束。
其中,有些问题就是平时基本的输入输出问题,例如:游戏规则,可以直接打印。
棋盘的显示也是一般的图形输出问题,但是稍微复杂一些。
需要改进的地方和达到的目标是:1、游戏的初始界面显示的是游戏规则,当玩家确定开始的时候要清除界面来显示棋盘。
2、棋盘和棋子的显示,界面(棋子和棋盘)容易分辨,这要从颜色和图形上加以区分。
3、要求一方用‘W’(上)、‘S’(下)、‘A’(左)、‘D’(右),另一方用‘↑’、‘↓’、‘←’、‘→’来移动光标,再分别用‘Z’和‘空格’键确定落子。
4、当一方走棋时,另一方的按键应该设置为无效。
5、游戏进行时打印提示信息,当一方赢棋后,要显示赢棋的字符,并询问玩家是否继续开始。
6、可以随时退出游戏或重新开始游戏。
二、方案设计与论证首先设置游戏的初始界面,采用白色背景和红色前景,这可以调用‘conio.h’库函数实现打印游戏规则。
询问玩家是不是开始游戏,通过选择Y\N来确定。
其中会遇到这样的问题:当玩家输入的不是‘Y(y)’或者‘N(n)’时应该怎么办呢?如果采用scanf函数来接收命令,这样会显示一个不满足要求的字符,于是可以用getch函数来接收命令,判断输入的字符是否为‘Y(y)’和‘N(n)’,如果是再显示出来。
为了界面的简洁,进入游戏前先清除屏幕,调用‘system()’函数来实现。
然后打印棋盘,可以把背景设置为湖蓝色,这样棋盘和棋子更容易分辨。
游戏开始后棋盘用黑色显示,这样易于区分。
具体的思路是:由于棋盘是网格状的,所以选择一个基本图形字符串‘十’,通过循环打印而构成一张大图。
接下来确定落子的位置,这需要通过改变光标的位置来实现,考虑到是在vc6.0环境下编译文件,c语言中的有些库函数并不支持,所以选择了’gotoxy()’函数并结合‘window.h’下的函数,通过键盘按键控制达到光标移动功能。
用C语言编写的五子棋游戏

Code1. #include <graphics.h>2. #include <conio.h>3. #include <dos.h>4. #include <bios.h>5. #include <malloc.h>6. #include <stdlib.h>7. #include <stdio.h>8. #define R 10 /*The size of mouse*/9. void init(void); /* BGI initialization */10. int cover(int);/*draw lines , set color, output the text*/11. void get_board(void);12. /*using the loop and the line function to draw the chessboard*/13. void word(int); /*input word,the color is come from the rand*/14. void getmouse(int *,int *,int *);15. /*get the location and the button of mouse,key=1 is the left button,key=2 is the rightbutton*/16. void visbilemouse(void);17. /*Display the mouse*//*after typing ,gets the x, y and mouse button,then return */18. void mouse(int *,int *,int *);19. /*drawing a mouse is to put an empty rectangular in the memory , then draw theshape of the mouse in the empty rectangular*/20. void change_word(int); /*show the black or the white*/21. void help(void); /*get playing help*/22. void prompt(int); /*the cancel or quit*/23. void game_player(void); /*how to realize the game*/24. int main()25. {26. int key;27. init();/*BGI initialization*/28. key=cover(0); /*the welcome interface*/29. while(key) /*only it is 1.it will running the loop*/30. {31. get_board(); /*draw the chessboard*/32. game_player(); /*control or play the games*/33. }34. closegraph();35. return 0;36. }37. void init() /* BGI initialization */38. {39. int graphdriver = DETECT, graphmode = 0;40. /* The same effect with gd =VGA and gm = VGAHI */41. registerbgidriver(EGAVGA_driver);/* After register the BGI driver needn't the support of running the BGI */42. initgraph(&graphdriver, &graphmode, "");43. return;44. }45. int cover(int choose)46. {47. int row,col,i;48. char answer;49. switch(choose)50. {51. case 0:52. setfillstyle(SOLID_FILL,BLUE); /*fill in the color*/53. bar(630,450,10,30);54. for(row=30;row<=180;row+=30) /*draw cross lines*/55. line(10,row,160,row);56. for(col=10;col<=180;col+=30) /*draw vertical lines*/57. line(col,30,col,180);58. setcolor(BLACK);59. settextstyle(0,0,3);60. outtextxy(200,200,"loading...");61. setfillstyle(1,BLACK);62. for(i=25;i<175;i+=30)63. {64. pieslice(i,i+20,0,360,14);65. sleep(1);66. }67. for(row=30;row<=180;row+=30)68. line(480,row,630,row);69. for(col=480;col<=630;col+=30)70. line(col,30,col,180);71. setcolor(WHITE);72. settextstyle(0,0,3);73. outtextxy(200,200,"loading...");74. setfillstyle(1,WHITE);75. for(i=495;i<=615;i+=30)76. {77. pieslice(i,660-i,0,360,14);78. sleep(1);79. }80. setcolor(BLUE);81. settextstyle(0,0,3);82. outtextxy(200,200,"loading...");83. settextstyle(0,0,5);84. /* fornt :DEFAULT_FONT, TRIPLEX_FONT,SMALL_FONT,SANSSERIF_FONT,GOTHIC_FONT /direction:lateral and vertical /size */85. for(i=1;i<=21;i++)86. {87. setcolor(i); /*the color of the text*/88. outtextxy(65,100,"FIVE IN A ROW"); /*output the text*/89. }90. setcolor(6);91. settextstyle(0,0,3);92. sleep(1);93. outtextxy(50,300,"Made by Hu yin feng");94. sleep(1);95. outtextxy(100,350," Xiao xin ran");96. sleep(1);97. outtextxy(100,400," Zheng yun");98. setcolor(7);99. settextstyle(0,0,2);100. sleep(2);101. outtextxy(20,430,"would you like to try?(Y/N:)");102. answer=getch();103. break;104. case 1:105. setfillstyle(SOLID_FILL,3);106. bar(640,400,451,220);107. setcolor(BLACK);108. settextstyle(0,0,2.5);109. outtextxy(455,280,"BLACK WIN!");110. sleep(1);111. setcolor(RED);112. settextstyle(0,0,2);113. outtextxy(451,320,"Try again?");114. answer=getch();115. break;116. case 2:117. setfillstyle(SOLID_FILL,3);118. bar(640,400,451,220);119. setcolor(WHITE);120. settextstyle(0,0,2.5);121. outtextxy(455,280,"WHITE WIN!");122. sleep(1);123. setcolor(RED);124. settextstyle(0,0,2);125. outtextxy(455,320,"Try again?");126. answer=getch();127. break;128. case 3:129. setfillstyle(SOLID_FILL,3);130. bar(640,400,451,220);131. settextstyle(0,0,2.5);132. setcolor(WHITE);133. outtextxy(455,280,"A Draw!");134. sleep(1);135. setcolor(RED);136. settextstyle(0,0,2);137. outtextxy(455,320,"Try again?");138. answer=getch();139. break;140. case 4:141. cleardevice();142. setbkcolor(GREEN);143. setfillstyle(SOLID_FILL,MAGENTA);144. bar(620,450,20,30);145. setcolor(RED);146. settextstyle(0,0,5);147. outtextxy(150,100,"Game Over!");148. sleep(2);149. break;150. }151. if(answer=='Y'||answer=='y')152. return 1;153. else154. exit(0);155. return 0;156. }157. void get_board()158. {159. int row,col;160. /*setbkcolor(YELLOW);set the color of background */ 161. setfillstyle(SOLID_FILL,YELLOW);162. bar(450,480,0,0);163. setcolor(BLACK); /*set the color of lines*/164. for(row=0;row<=450;row+=30) /*Draw lines*/165. line(0,row,450,row);166. for(col=0;col<=450;col+=30) /*Draw lines*/167. line(col,0,col,480);168. setcolor(BLACK);169. circle(90,90,2);170. circle(330,90,2); /*draw four small rounds in the chessboard */171. circle(90,330,2);172. circle(330,330,2);173. setfillstyle(SOLID_FILL,GREEN);174. bar(451,0,640,480); /*filling range*/175. return;176. }177. void word(int color)/*input word*/178. {179. settextstyle(0,0,4); /*display the characters of :‘five in a row’*/180. setcolor(color);181. outtextxy(461,5,"FIVE");182. setcolor(color+1);183. outtextxy(496,45,"IN");184. setcolor(color+4);185. outtextxy(500,80,"A");186. setcolor(color+4);187. outtextxy(540,80,"ROW");188. setcolor(YELLOW);189. settextstyle(0,0,1);190. rectangle(460,450,510,470);/* the help window */191. rectangle(590,450,630,470); /* the regret window */192. rectangle(520,450,580,470); /*the exit window */193. setcolor(BLACK);194. outtextxy(470,455,"help");195. outtextxy(525,455,"cancel");196. outtextxy(595,455,"exit");197. return;198. }199. void change_word(digit)200. {201. if(digit==0)202. {203. settextstyle(0,0,2); /*when choose white then hint the next one is black */ 204. setcolor(BLACK);205. outtextxy(459,130,"THE BLACK");206. setcolor(GREEN);207. outtextxy(459,180,"THE WHITE");208. }209. else if(digit==1)210. {211. settextstyle(0,0,2);212. setcolor(GREEN);213. outtextxy(459,130,"THE BLACK");214. setcolor(WHITE); /*when choose black then hint the next one is white*/ 215. outtextxy(459,180,"THE WHITE");216. }217. return;218. }219. void help()220. {221. setfillstyle(SOLID_FILL,BLUE);222. bar(640,480,0,0);223. setcolor(YELLOW);224. rectangle(0,0,639,479);225. settextstyle(0,0,3);226. outtextxy(50,10,"How to play the game");227. settextstyle(0,0,2);228. setcolor(WHITE);229. outtextxy(10,60,"1. Clicking the mouse in the chessboard"); 230. outtextxy(10,80," to start the game black is the first , "); 231. outtextxy(10,100," the changing word on the right will "); 232. outtextxy(10,120," remind you the next person to play ;"); 233. outtextxy(10,160,"2. The side will win who form a ");234. outtextxy(10,180," continuous five chess pieces in a "); 235. outtextxy(10,200," straight line no matter of horizontal,"); 236. outtextxy(10,220," vertical and oblique.");237. outtextxy(10,260,"3. Clicking the 'regret' on the right ");238. outtextxy(10,280," is to erase the last chess you'd just "); 239. outtextxy(10,300," played ;");240. outtextxy(10,340,"4. Clicking the 'exit' is to exit the ");241. outtextxy(10,360," game ,it'll jump out another window to "); 242. outtextxy(10,380," make sure if you decide to end the "); 243. outtextxy(10,400," game,if press'y'is closing the window "); 244. outtextxy(10,420," and press 'n' is to continue the game ;"); 245. settextstyle(0,0,2);246. setcolor(RED);247. outtextxy(100,450,"Please any key to continue!");248. getch();249. return;250. }251. void prompt(number)252. {253. if(number==1)254. {255. setcolor(RED); /*the exit window*/256. setfillstyle(SOLID_FILL,BLUE);257. bar(640,400,451,220);258. settextstyle(0,0,2.5);259. outtextxy(455,300,"quit?(Y/N)");260. }261. else if(number==0)262. {263. setcolor(RED); /* the regret window*/264. setfillstyle(SOLID_FILL,BLUE);265. bar(640,400,451,220);266. settextstyle(0,0,2);267. outtextxy(480,300,"Cancel?");268. }269. return;270. }271. /*get the location and the button of mouse,key=1 is the left button*/ 272. void getmouse(int *x,int *y,int *key)273. {274. union REGS inregs,outregs;275. inregs.x.ax=3; /*Obtain the position and the state of mouse can also use 3*/ 276. int86(0x33,&inregs,&outregs); /*Interrupt calls*/277. *x=outregs.x.cx; /*The X-axis is saved in cx register */278. *y=outregs.x.dx; /*The Y-axis is saved in dx register*/279. *key=outregs.x.bx;/*Bx registers are button states*/280. return;281. }282. void visbilemouse()283. {284. union REGS inregs,outregs;285. inregs.x.ax=0x01; /*Display the mouse*/286. int86(0x33,&inregs,&outregs);287. return;288. }/*after typing ,gets the x, y and mouse button,then return */289. void mouse(int *x,int *y,int *z)/*drawing a mouse is to put an empty rectangular in the memory , then draw shape of the mouse in the empty rectangular*/290. {291. int a=0,b=0,c=0,a_old=0,b_old=0; /*it's ok to be free of the value of a and b*/ 292. int color;293. float i=0;294. int *ball; /*define a pointer to point to the store of graphics*/295. ball=malloc(imagesize(a,b,a+R,b+R)); /*Returns the size of the rectangle*/ 296. getimage(a,b,a+R,b+R,ball);/*the first time to put graphics that save an empty rectangle into the memory */ 297. while(c==0)/*loop will be ended until typein */298. {299. getmouse(&a,&b,&c);/*a,is X-axis,b is Y-axis,c is the statement ofthe key */300. if(a<0) a=0; /*ensure the left of the mouse do not out of bound*/301. if(b<0) b=0; /*ensure the up of the mouse do not out of bound*/302. if(a>getmaxx()-R) a=getmaxx()-R;/*ensure the right of the mouse do not out of bound*//*ensure the down of the mouse do not out of bound*/303. if(b>getmaxy()-R) b=getmaxy()-R;304. if(a!=a_old || b!=b_old) /*When the mouse moves*/305. {306. putimage(a_old,b_old,ball,0); /*output the graphic in a_oldandb_old to erase originally mouse*/307. getimage(a,b,a+R,b+R,ball);/*the statement is to save the location of the graph of the mouse in the ball*/ 308. setcolor(BLACK);309. setlinestyle(0,0,1);310. line(a,b,a+R,b+R/2);311. line(a,b,a+R/2,b+R);312. line(a+R,b+R/2,a+R/2,b+R);313. line(a+R*3/4,b+R*3/4,a+R,b+R);/*draw the mouse*/314. }315. a_old=a;b_old=b;316. i++;317. if(i==200000) /*Flashing frequency*/318. {319. color=rand()%16;/*use the feature of the loop of mouse will get the randon color*/320. word(color);321. i=1;/*the value of the i return to 1*/322. }323. }324. /*end of while()*/325. *x=a;*y=b;*z=c; /*return the position of the mouse after typing*/326. putimage(a,b,ball,0);/*ease the mouse ,because it is a empty retangle of default-background save in the ball */ 327. free(ball);328. return;329. }/*the main idea is through storing the present graphic in the getimage,put image and imagesize to erase the preceding mouse's graphic, we also can use clearing parts of the screen */330. void game_player()331. {332. int x,y,z,row,col,i;333. char answer;334. int address[16][15]={NULL},count[2]={0};335. int temp=0,num=1;336. visbilemouse();337. do338. {339. mouse(&x,&y,&z);340. if(x<450)/*judge whether the location of the mouse is in the keyboard*/341. {342. col=x/30;343. row=y/30;344. x=30*col+15;345. y=30*row+15;346. if(address[row][col]==0) /*whether the position is available*/347. {348. temp++; /*only accumulate in no circumstance of the pieces*/ 349. count[0]=x;350. count[1]=y;/*save the coordinate of y in an array convenient for regret*/351. if(temp%2==1)352. {353. address[row][col]=1;354. setcolor(BLACK);355. setfillstyle(1,BLACK);356. pieslice(x,y,0,360,14);/*Using the method of painting fan-shaped to draw a circle*/357. change_word(1);358. }359. else360. {361. setcolor(WHITE);362. address[row][col]=2;363. setfillstyle(1,WHITE);364. pieslice(x,y,0,360,14);365. change_word(0);366. }367. /*Judgement of the situation in a row*/368. /*make the judgment of if there's five in a row*/369. for(i=1;i<=4;i++)370. {371. if(col+i<=14)372. {373. if(address[row][col]==address[row][col+i])374. num++;375. else376. break;377. }378. else379. break;380. }381. if(num!=5)382. for(i=1;i<=4;i++)383. {384. if(col-i>=0)385. {386. if(address[row][col]==address[row][col-i]) 387. num++;388. else if(num<5)389. {390. num=1; /*the num is reassigned to 1*/ 391. break;392. }393. else394. break;395. }396. else if(num<5)397. {398. num=1;399. break;400. }401. else402. break;403. }404. /*make the judgment of if there's five in a column*/405. for(i=1;i<=4;i++)406. {407. if(row+i<=15)408. {409. if(address[row][col]==address[row+i][col])410. num++;411. else412. break;413. }414. else415. break;416. }417. if(num!=5)418. for(i=1;i<=4;i++)419. {420. if(row-i>=0)421. {422. if(address[row][col]==address[row-i][col]) 423. num++;424. else if(num<5)425. {426. num=1;427. break;428. }429. else430. break;431. }432. else if(num<5)433. {434. num=1;435. break;436. }437. else438. break;439. }440. /*make judgment of if the main diagonal line have reached the five */ 441. for(i=1;i<=4;i++)442. { if(row-i>=0&&col+i<=14)443. {444. if(address[row][col]==address[row-i][col+i]) 445. num++;446. else447. break;448. }449. else450. break;451. }452. if(num!=5)453. for(i=1;i<=4;i++)454. {455. if(col-i>=0&&row+i<=15)456. {457. if(address[row][col]==address[row+i][col-i]) 458. num++;459. else if(num<5)460. {461. num=1;462. break;463. }464. else465. break;466. }467. else if(num<5)468. {469. num=1;470. break;471. }472. else473. break;474. }475. /*make judgment of if the main diagonal line have reached the five */ 476. for(i=1;i<=4;i++)477. {478. if(row-i>=0&&col-i>=0)479. {480. if(address[row][col]==address[row-i][col-i]) 481. num++;482. else483. break;484. }485. else486. break;487. }488. if(num!=5)489. for(i=1;i<=4;i++)490. {491. if(row+i<=16&&col+i<=14)492. {493. if(address[row][col]==address[row+i][col+i]) 494. num++;495. else if(num<5)496. {497. num=1;498. break;499. }500. else501. break;502. }503. else if(num<5)504. {505. num=1;506. break;507. }508. else509. break;510. }511. if(num>=5)512. {513. cover(address[row][col]);514. return;515. }516. else if(temp==240)517. {518. cover(3);519. return;520. }521. }522. }523. else if(x>460 && x<510&&y>450&&y<470)524. {525. help();526. get_board();527. game_player();528. }529. else if(x>590 && x<630&&y>450&&y<470)530. {531. prompt(1);532. answer=getch();533. if(answer=='Y'||answer=='y')534. {535. cover(4);536. exit(0);537. }538. else539. {540. setfillstyle(SOLID_FILL,GREEN);541. bar(640,400,451,220);542. continue;543. }544. }545. else if(x>520 && x<580&&y>450&&y<470)546. {547. prompt(0);548. answer=getch();549. setfillstyle(SOLID_FILL,GREEN);550. bar(640,400,451,220);551. if(answer=='Y'||answer=='y')552. {553. setcolor(YELLOW);554. setfillstyle(1,YELLOW);555. pieslice(count[0],count[1],0,360,14); /*only regrets once*/ 556. address[row][col]=0;557. temp--;558. }559. else560. continue;561. }562. else563. continue;564. }565. while(x<640 || x>0 || y<480 || y>0); /*the range of the mouse*/ 566. return;567. }。
c语言设计五子棋代码

c语言设计五子棋代码五子棋,亦称五目、五子、顺手拍子、连珠、下五子、悔棋、先手必胜等,是一种两人对弈的纯策略型棋类游戏。
通常用黑白两色的棋子在白色棋盘上进行游戏,以先把五个棋子连成一线者获胜。
实现五子棋游戏需要完成以下步骤:1. 棋盘的绘制2. 棋子的下落判断,包括判断是否胜利3. 玩家之间的交替下棋首先是棋盘的绘制。
采用二维数组来表示棋盘,用“+”、“-”、“|”等符号来绘制边框和交叉点。
同时还要用“ ”表示空白区域,用“●”和“○”代表黑白棋子。
然后是棋子的下落判断。
需要记录下棋子的位置,并判断落子是否在棋盘范围内,以及是否与已落下的棋子位置冲突。
在判断胜负时,需要遍历棋盘上所有的落子情况,检查是否存在连续的五个同色棋子。
最后是玩家之间的交替下棋。
可以使用一个计数器来记录当前下棋者,每次下完一子后,计数器加1,判断下一个下棋者,直到游戏结束为止。
下面是一份实现五子棋游戏的 C 代码:#include <stdio.h>#include <stdlib.h>#define ROW 15 // 棋盘行数#define COL 15 // 棋盘列数#define BLACK '●' // 黑色棋子#define WHITE '○' // 白色棋子#define SPACE ' ' // 空白区域char board[ROW][COL]; // 棋盘二维数组// 初始化棋盘void init_board() {for (int i = 0; i < ROW; i++) {for (int j = 0; j < COL; j++) {board[i][j] = SPACE;}}}// 打印棋盘void print_board() {for (int i = 0; i < ROW; i++) {for (int j = 0; j < COL; j++) {if (j == 0) printf("%2d ", i + 1); printf("%c ", board[i][j]);}printf("\n");}for (int i = 0; i < COL; i++) {if (i == 0) printf(" ");printf("%c ", 'A' + i);}printf("\n");}// 判断是否胜利int is_win(int row, int col, char ch) {int count = 1;// 判断横向for (int i = col - 1; i >= 0; i--) { if (board[row][i] == ch) {count++;} else {break;}}for (int i = col + 1; i < COL; i++) { if (board[row][i] == ch) {count++;} else {break;}}if (count >= 5) {return 1;}// 判断纵向count = 1;for (int i = row - 1; i >= 0; i--) { if (board[i][col] == ch) {count++;} else {break;}}for (int i = row + 1; i < ROW; i++) {if (board[i][col] == ch) {count++;} else {break;}}if (count >= 5) {return 1;}// 判断左上到右下斜向count = 1;for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) { if (board[i][j] == ch) {count++;} else {break;}}for (int i = row + 1, j = col + 1; i < ROW && j < COL; i++, j++) { if (board[i][j] == ch) {count++;} else {break;}}if (count >= 5) {return 1;}// 判断左下到右上斜向count = 1;for (int i = row + 1, j = col - 1; i < ROW && j >= 0; i++, j--) { if (board[i][j] == ch) {count++;} else {break;}}for (int i = row - 1, j = col + 1; i >= 0 && j < COL; i--, j++) { if (board[i][j] == ch) {count++;} else {break;}}if (count >= 5) {return 1;}return 0;}。
C语言五子棋代码

//五子棋小游戏纯C语言代码#include <stdio.h>#define N 14char state[N][N];void init(void);void printState(void);bool isWin(bool isBlack,int x,int y);bool isLevelWin(bool isBlack,int x,int y);bool isVerticalWin(bool isBlack,int x,int y);bool isLeftInclinedWin(bool isBlack,int x,int y);bool isRightObliqueWin(bool isBlack,int x,int y);bool isWin(bool isBlack,int x,int y)//是否有获胜{return isLevelWin(isBlack,x,y)||isVerticalWin(isBlack,x,y)||isLeftInclinedWin(isBlack,x,y)||isRightObliqueWin(isBlack,x,y);}bool isLevelWin(bool isBlack,int x,int y)//确定水平直线上是否有五子连珠{char c = isBlack ? '@':'O';int count;while(y>0 && state[x][y] == c){y--;}count =0;if(state[x][y] == c) count = 1;y++;while(y < N && state[x][y] == c){count++;if(count == 5){return true;}y++;}return false;}bool isVerticalWin(bool isBlack,int x,int y)//确定竖直直线是否有五子连珠{char c = isBlack ? '@':'O';int count;while(x>0 && state[x][y] == c){x--;}count =0;if(state[x][y] == c) count = 1;x++;while(x < N && state[x][y] == c){count++;if(count == 5){return true;}x++;}return false;}bool isLeftInclinedWin(bool isBlack,int x,int y)//确定左斜线是否有五子连珠{char c = isBlack ? '@':'O';int count;while(x>0 && y>0 && state[x][y] == c){y--;x--;}count =0;if(state[x][y] == c) count = 1;x++;y++;while(x < N && y < N && state[x][y] == c){count++;if(count == 5){return true;}x++;y++;}return false;}bool isRightObliqueWin(bool isBlack,int x,int y)//确定右斜线是否有五子连珠{char c = isBlack ? '@':'O';int count;while(x>0 && y<N && state[x][y] == c){y++;x--;}count =0;if(state[x][y] == c) count = 1;x++;y--;while(x < N && y >= 0 && state[x][y] == c){count++;if(count == 5){return true;}x++;y--;}return false;}void init(void)//开局初始化数组{int i,j;for(i=0;i<N;i++){for(j=0;j<N;j++){state[i][j] = '*';}}}void printState(void)//打印棋盘{int i,j;printf("%3c",' ');for(i=0;i<N;i++)printf("%3d",i);printf("\n");for(i=0;i<N;i++){printf("%3d",i);for(j=0;j<N;j++){printf("%3c",state[i][j]);}printf("\n");}}int main(void){int x,y;bool isBlack = true;init();printf("五子棋小游戏\n\n@代表黑子,0代表白子,*代表棋盘空白\n");printf("------------------------------------------------------\n");printState();while(1){printf("请%s 方走棋:\n",(isBlack?"黑":"白"));//请黑(白)方走棋的说明printf("输入所下位置坐标,如: 1-2\n");//走棋方法示例scanf("%d-%d",&x,&y);if(state[x][y]=='@' || state[x][y]=='O')//若此点已经存在棋子,则重新下一步棋在别处{printf("this position to have pieces\n");continue;}state[x][y] = (isBlack?'@':'O');//规定@代表黑子,0代表白子printState();//打印棋盘情况if(isWin(isBlack,x,y))//每下一步棋,判断一次是否有人获胜{printf("%s 方胜利\n",(isBlack?"黑":"白"));break;}isBlack = !isBlack;}}。
用C开发一个迷你的五子棋游戏

用C开发一个迷你的五子棋游戏迷你五子棋游戏是一种简化版的五子棋游戏,它具有简洁的界面和简单易懂的规则,非常适合初学者。
本文将介绍如何使用C语言开发一个迷你的五子棋游戏,以供大家学习参考。
一、游戏规则迷你五子棋游戏的规则非常简单,玩家分别执黑子和白子,轮流在棋盘上落子。
当任一玩家在横、竖、斜四个方向上连成五个自己的棋子时,即可获胜。
若棋盘填满且无一方连成五子,则为平局。
二、游戏实现为了实现迷你五子棋游戏,我们需要使用C语言和一些基本的图形库函数。
在开始编写代码之前,我们先引入必要的头文件,并定义一些常量和全局变量。
#include <stdio.h>#include <conio.h>#include <graphics.h>#define ROW 10 // 棋盘行数#define COL 10 // 棋盘列数#define SIZE 40 // 每个格子的大小#define WIDTH COL*SIZE // 棋盘的宽度#define HEIGHT ROW*SIZE // 棋盘的高度int chessboard[ROW][COL]; // 棋盘数组,用来保存棋盘中每个位置的棋子信息int currentPlayer; // 当前玩家,0代表黑子,1代表白子接下来,我们需要进行一些初始化操作,包括创建图形窗口、初始化棋盘和设置玩家初始状态。
void init() {int driver, mode;driver = VGA;mode = VGAHI;initgraph(&driver, &mode, "");setbkcolor(WHITE);cleardevice();currentPlayer = 0;memset(chessboard, 0, sizeof(chessboard));}在绘制棋盘的函数中,我们使用for循环和线段绘制函数line()来绘制出棋盘的网格。
五子棋C语言代码

#include "graphics.h" /*图形系统头文件*/#define LEFT 0x4b00 /*光标左键值*/#define RIGHT 0x4d00 /*光标右键值*/#define DOWN 0x5000 /*光标下键值*/#define UP 0x4800 /*光标上键值*/#define ESC 0x011b /* ESC键值*/#define ENTER 0x1c0d /* 回车键值*/int a[8][8]={0},key,score1,score2;/*具体分数以及按键与存放棋子的变量*/ char playone[3],playtwo[3];/*两个人的得分转换成字符串输出*/void playtoplay(void);/*人人对战函数*/void DrawQp(void);/*画棋盘函数*/void SetPlayColor(int x);/*设置棋子第一次的颜色*/void MoveColor(int x,int y);/*恢复原来棋盘状态*/int QpChange(int x,int y,int z);/*判断棋盘的变化*/void DoScore(void);/*处理分数*/void PrintScore(int n);/*输出成绩*/void playWin(void);/*输出胜利者信息*//******主函数*********/void main(void){int gd=DETECT,gr;initgraph(&gd,&gr,"c:\\tc"); /*初始化图形系统*/DrawQp();/*画棋盘*/playtoplay();/*人人对战*/getch();closegraph();/*关闭图形系统*/}void DrawQp()/*画棋盘*/{int i,j;score1=score2=0;/*棋手一开始得分都为0*/setbkcolor(BLUE);for(i=100;i<=420;i+=40){line(100,i,420,i);/*画水平线*/line(i,100,i,420); /*画垂直线*/}setcolor(0);/*取消圆周围的一圈东西*/setfillstyle(SOLID_FILL,15);/*白色实体填充模式*/fillellipse(500,200,15,15); /*在显示得分的位置画棋*/setfillstyle(SOLID_FILL,8); /*黑色实体填充模式*/fillellipse(500,300,15,15);a[3][3]=a[4][4]=1;/*初始两个黑棋*/a[3][4]=a[4][3]=2;/*初始两个白棋*/setfillstyle(SOLID_FILL,WHITE);fillellipse(120+3*40,120+3*40,15,15);fillellipse(120+4*40,120+4*40,15,15);setfillstyle(SOLID_FILL,8);fillellipse(120+3*40,120+4*40,15,15);fillellipse(120+4*40,120+3*40,15,15);score1=score2=2; /*有棋后改变分数*/DoScore();/*输出开始分数*/}void playtoplay()/*人人对战*/{int x,y,t=1,i,j,cc=0;while(1)/*换棋手走棋*/{x=120,y=80;/*每次棋子一开始出来的坐标,x为行坐标,y为列坐标*/ while(1) /*具体一个棋手走棋的过程*/{PrintScore(1);/*输出棋手1的成绩*/PrintScore(2);/*输出棋手2的成绩*/SetPlayColor(t);/*t变量是用来判断棋手所执棋子的颜色*/fillellipse(x,y,15,15);key=bioskey(0);/*接收按键*/if(key==ESC)/*跳出游戏*/break;elseif(key==ENTER)/*如果按键确定就可以跳出循环*/{if(y!=80&&a[(x-120)/40][(y-120)/40]!=1&&a[(x-120)/40][(y-120)/40]!=2)/*如果落子位置没有棋子*/{if(t%2==1)/*如果是棋手1移动*/a[(x-120)/40][(y-120)/40]=1;else/*否则棋手2移动*/a[(x-120)/40][(y-120)/40]=2;if(!QpChange(x,y,t))/*落子后判断棋盘的变化*/{a[(x-120)/40][(y-120)/40]=0;/*恢复空格状态*/cc++;/*开始统计尝试次数*/if(cc>=64-score1-score2) /*如果尝试超过空格数则停步*/{MoveColor(x,y);fillellipse(x,y,15,15);break;}elsecontinue;/*如果按键无效*/}DoScore();/*分数的改变*/break;/*棋盘变化了,则轮对方走棋*/ }else/*已经有棋子就继续按键*/continue;}else /*四个方向按键的判断*/if(key==LEFT&&x>120)/*左方向键*/{MoveColor(x,y);fillellipse(x,y,15,15);SetPlayColor(t);x-=40;fillellipse(x,y,15,15);}elseif(key==RIGHT&&x<400&&y>80)/*右方向键*/ {MoveColor(x,y);fillellipse(x,y,15,15);SetPlayColor(t);x+=40;fillellipse(x,y,15,15);}elseif(key==UP&&y>120)/*上方向键*/{MoveColor(x,y);fillellipse(x,y,15,15);SetPlayColor(t);y-=40;fillellipse(x,y,15,15);}elseif(key==DOWN&&y<400)/*下方向键*/{MoveColor(x,y);fillellipse(x,y,15,15);SetPlayColor(t);y+=40;fillellipse(x,y,15,15);}}if(key==ESC)/*结束游戏*/break;if((score1+score2)==64||score1==0||score2==0)/*格子已经占满或一方棋子为0判断胜负*/{playWin();/*输出最后结果*/break;}t=t%2+1; /*一方走后,改变棋子颜色即轮对方走*/cc=0; /*计数值恢复为0*/} /*endwhile*/}void SetPlayColor(int t)/*设置棋子颜色*/{if(t%2==1)setfillstyle(SOLID_FILL,15);/*白色*/elsesetfillstyle(SOLID_FILL,8);/*灰色*/}void MoveColor(int x,int y)/*走了一步后恢复原来格子的状态*/{if(y<100)/*如果是从起点出发就恢复蓝色*/setfillstyle(SOLID_FILL,BLUE);else/*其他情况如果是1就恢复白色棋子,2恢复黑色棋子,或恢复蓝色棋盘*/ switch(a[(x-120)/40][(y-120)/40]){case 1:setfillstyle(SOLID_FILL,15);break; /*白色*/case 2:setfillstyle(SOLID_FILL,8);break; /*黑色*/default:setfillstyle(SOLID_FILL,BLUE); /*蓝色*/}}int QpChange(int x,int y,int t)/*判断棋盘的变化*/{int i,j,k,kk,ii,jj,yes;yes=0;i=(x-120)/40; /*计算数组元素的行下标*/j=(y-120)/40; /*计算数组元素的列下标*/SetPlayColor(t);/*设置棋子变化的颜色*//*开始往8个方向判断变化*/if(j<6)/*往右边*/{for(k=j+1;k<8;k++)if(a[i][k]==a[i][j]||a[i][k]==0)/*遇到自己的棋子或空格结束*/ break;if(a[i][k]!=0&&k<8){for(kk=j+1;kk<k&&k<8;kk++)/*判断右边*/{a[i][kk]=a[i][j]; /*改变棋子颜色*/fillellipse(120+i*40,120+kk*40,15,15);}if(kk!=j+1) /*条件成立则有棋子改变过颜色*/yes=1;}}if(j>1)/*判断左边*/{for(k=j-1;k>=0;k--)if(a[i][k]==a[i][j]||!a[i][k])break;if(a[i][k]!=0&&k>=0){for(kk=j-1;kk>k&&k>=0;kk--){a[i][kk]=a[i][j];fillellipse(120+i*40,120+kk*40,15,15);}if(kk!=j-1)yes=1;}}if(i<6)/*判断下边*/{for(k=i+1;k<8;k++)if(a[k][j]==a[i][j]||!a[k][j])break;if(a[k][j]!=0&&k<8){for(kk=i+1;kk<k&&k<8;kk++){a[kk][j]=a[i][j];fillellipse(120+kk*40,120+j*40,15,15);}if(kk!=i+1)yes=1;}}if(i>1)/*判断上边*/{for(k=i-1;k>=0;k--)if(a[k][j]==a[i][j]||!a[k][j])break;if(a[k][j]!=0&&k>=0){for(kk=i-1;kk>k&&k>=0;kk--){a[kk][j]=a[i][j];fillellipse(120+kk*40,120+j*40,15,15); }if(kk!=i-1)yes=1;}}if(i>1&&j<6)/*右上*/{for(k=i-1,kk=j+1;k>=0&&kk<8;k--,kk++) if(a[k][kk]==a[i][j]||!a[k][kk])break;if(a[k][kk]&&k>=0&&kk<8){for(ii=i-1,jj=j+1;ii>k&&k>=0;ii--,jj++){a[ii][jj]=a[i][j];fillellipse(120+ii*40,120+jj*40,15,15); }if(ii!=i-1)yes=1;}}if(i<6&&j>1)/*左下*/{for(k=i+1,kk=j-1;k<8&&kk>=0;k++,kk--) if(a[k][kk]==a[i][j]||!a[k][kk])break;if(a[k][kk]!=0&&k<8&&kk>=0){for(ii=i+1,jj=j-1;ii<k&&k<8;ii++,jj--){a[ii][jj]=a[i][j];fillellipse(120+ii*40,120+jj*40,15,15);}if(ii!=i+1)yes=1;}}if(i>1&&j>1)/*左上*/{for(k=i-1,kk=j-1;k>=0&&kk>=0;k--,kk--)if(a[k][kk]==a[i][j]||!a[k][kk])break;if(a[k][kk]!=0&&k>=0&&kk>=0){for(ii=i-1,jj=j-1;ii>k&&k>=0;ii--,jj--){a[ii][jj]=a[i][j];fillellipse(120+ii*40,120+jj*40,15,15);}if(ii!=i-1)yes=1;}}if(i<6&&j<6)/* 右下*/{for(k=i+1,kk=j+1;kk<8&&kk<8;k++,kk++)if(a[k][kk]==a[i][j]||!a[k][kk])break;if(a[k][kk]!=0&&kk<8&&k<8){for(ii=i+1,jj=j+1;ii<k&&k<8;ii++,jj++){a[ii][jj]=a[i][j];fillellipse(120+ii*40,120+jj*40,15,15);}if(ii!=i+1)yes=1;}}return yes;/*返回是否改变过棋子颜色的标记*/ }void DoScore()/*处理分数*/{int i,j;score1=score2=0;/*重新开始计分数*/for(i=0;i<8;i++)for(j=0;j<8;j++)if(a[i][j]==1)/*分别统计两个人的分数*/score1++;elseif(a[i][j]==2)score2++;}void PrintScore(int playnum)/*输出成绩*/{if(playnum==1)/*清除以前的成绩*/{setfillstyle(SOLID_FILL,BLUE);bar(550,100,640,400);}setcolor(RED);settextstyle(0,0,4);/*设置文本输出样式*/if(playnum==1)/*判断输出哪个棋手的分,在不同的位置输出*/ {sprintf(playone,"%d",score1);outtextxy(550,200,playone);}else{sprintf(playtwo,"%d",score2);outtextxy(550,300,playtwo);}setcolor(0);}void playWin()/*输出最后的胜利者结果*/{settextstyle(0,0,4);setcolor(12);if(score2>score1)/*开始判断最后的结果*/outtextxy(100,50,"black win!");elseif(score2<score1)outtextxy(100,50,"white win!");elseouttextxy(60,50,"you all win!");}。
C语言实现五子棋游戏

C语⾔实现五⼦棋游戏本⽂实例为⼤家分享了C语⾔实现五⼦棋的具体代码,供⼤家参考,具体内容如下#include <stdio.h>#include <bios.h>#include <ctype.h>#include <conio.h>#include <dos.h>#define CROSSRU 0xbf /*右上⾓点*/#define CROSSLU 0xda /*左上⾓点*/#define CROSSLD 0xc0 /*左下⾓点*/#define CROSSRD 0xd9 /*右下⾓点*/#define CROSSL 0xc3 /*左边*/#define CROSSR 0xb4 /*右边*/#define CROSSU 0xc2 /*上边*/#define CROSSD 0xc1 /*下边*/#define CROSS 0xc5 /*⼗字交叉点*//*定义棋盘左上⾓点在屏幕上的位置*/#define MAPXOFT 5#define MAPYOFT 2/*定义1号玩家的操作键键码*/#define PLAY1UP 0x1157/*上移--'W'*/#define PLAY1DOWN 0x1f53/*下移--'S'*/#define PLAY1LEFT 0x1e41/*左移--'A'*/#define PLAY1RIGHT 0x2044/*右移--'D'*/#define PLAY1DO 0x3920/*落⼦--空格键*//*定义2号玩家的操作键键码*/#define PLAY2UP 0x4800/*上移--⽅向键up*/#define PLAY2DOWN 0x5000/*下移--⽅向键down*/#define PLAY2LEFT 0x4b00/*左移--⽅向键left*/#define PLAY2RIGHT 0x4d00/*右移--⽅向键right*/#define PLAY2DO 0x1c0d/*落⼦--回车键Enter*//*若想在游戏中途退出, 可按 Esc 键*/#define ESCAPE 0x011b/*定义棋盘上交叉点的状态, 即该点有⽆棋⼦ *//*若有棋⼦, 还应能指出是哪个玩家的棋⼦ */#define CHESSNULL 0 /*没有棋⼦*/#define CHESS1 'O'/*⼀号玩家的棋⼦*/#define CHESS2 'X'/*⼆号玩家的棋⼦*//*定义按键类别*/#define KEYEXIT 0/*退出键*/#define KEYFALLCHESS 1/*落⼦键*/#define KEYMOVECURSOR 2/*光标移动键*/#define KEYINVALID 3/*⽆效键*//*定义符号常量: 真, 假 --- 真为1, 假为0 */#define TRUE 1#define FALSE 0/**********************************************************//* 定义数据结构 *//*棋盘交叉点坐标的数据结构*/struct point{int x,y;};/**********************************************************//*⾃定义函数原型说明 */void Init(void);int GetKey(void);int CheckKey(int press);int ChangeOrder(void);int ChessGo(int Order,struct point Cursor);void DoError(void);void DoOK(void);void DoWin(int Order);void MoveCursor(int Order,int press);void DrawCross(int x,int y);void DrawMap(void);int JudgeWin(int Order,struct point Cursor);int JudgeWinLine(int Order,struct point Cursor,int direction); void ShowOrderMsg(int Order);void EndGame(void);/**********************************************************//**********************************************************//* 定义全局变量 */int gPlayOrder; /*指⽰当前⾏棋⽅ */struct point gCursor; /*光标在棋盘上的位置 */char gChessBoard[19][19];/*⽤于记录棋盘上各点的状态*/ /**********************************************************//**********************************************************//*主函数*/void main(){int press;int bOutWhile=FALSE;/*退出循环标志*/printf("Welcome [url][/url]");Init();/*初始化图象,数据*/while(1){press=GetKey();/*获取⽤户的按键值*/switch(CheckKey(press))/*判断按键类别*/{/*是退出键*/case KEYEXIT:clrscr();/*清屏*/bOutWhile = TRUE;break;/*是落⼦键*/case KEYFALLCHESS:if(ChessGo(gPlayOrder,gCursor)==FALSE)/*⾛棋*/ DoError();/*落⼦错误*/else{DoOK();/*落⼦正确*//*如果当前⾏棋⽅赢棋*/if(JudgeWin(gPlayOrder,gCursor)==TRUE){DoWin(gPlayOrder);bOutWhile = TRUE;/*退出循环标志置为真*/}/*否则*/else/*交换⾏棋⽅*/ChangeOrder();ShowOrderMsg(gPlayOrder);}break;/*是光标移动键*/case KEYMOVECURSOR:MoveCursor(gPlayOrder,press);break;/*是⽆效键*/case KEYINVALID:break;}if(bOutWhile==TRUE)break;}/*游戏结束*/EndGame();}/**********************************************************//*界⾯初始化,数据初始化*/void Init(void){int i,j;char *Msg[]={"Player1 key:"," UP----w"," DOWN--s"," LEFT--a"," RIGHT-d"," DO----space","","Player2 key:"," UP----up"," DOWN--down"," LEFT--left"," RIGHT-right"," DO----ENTER","","exit game:"," ESC",NULL,};/* 先⼿⽅为1号玩家 */gPlayOrder = CHESS1;/* 棋盘数据清零, 即棋盘上各点开始的时候都没有棋⼦ */ for(i=0;i<19;i++)for(j=0;j<19;j++)gChessBoard[i][j]=CHESSNULL;/*光标初始位置*/gCursor.x=gCursor.y=0;/*画棋盘*/textmode(C40);DrawMap();/*显⽰操作键说明*/i=0;textcolor(BROWN);while(Msg[i]!=NULL){gotoxy(25,3+i);cputs(Msg[i]);i++;}/*显⽰当前⾏棋⽅*/ShowOrderMsg(gPlayOrder);/*光标移⾄棋盘的左上⾓点处*/gotoxy(gCursor.x+MAPXOFT,gCursor.y+MAPYOFT); }/*画棋盘*/void DrawMap(void){int i,j;clrscr();for(i=0;i<19;i++)for(j=0;j<19;j++)DrawCross(i,j);}/*画棋盘上的交叉点*/void DrawCross(int x,int y){gotoxy(x+MAPXOFT,y+MAPYOFT);/*交叉点上是⼀号玩家的棋⼦*/if(gChessBoard[x][y]==CHESS1){textcolor(LIGHTBLUE);putch(CHESS1);return;}/*交叉点上是⼆号玩家的棋⼦*/if(gChessBoard[x][y]==CHESS2) {textcolor(LIGHTBLUE);putch(CHESS2);return;}textcolor(GREEN);/*左上⾓交叉点*/if(x==0&&y==0){putch(CROSSLU);return;}/*左下⾓交叉点*/if(x==0&&y==18){putch(CROSSLD);return;}/*右上⾓交叉点*/if(x==18&&y==0){putch(CROSSRU);return;}/*右下⾓交叉点*/if(x==18&&y==18){putch(CROSSRD);return;}/*左边界交叉点*/if(x==0){putch(CROSSL);return;}/*右边界交叉点*/if(x==18){putch(CROSSR);return;}/*上边界交叉点*/if(y==0){putch(CROSSU);return;}/*下边界交叉点*/if(y==18){putch(CROSSD);return;}/*棋盘中间的交叉点*/putch(CROSS);}/*交换⾏棋⽅*/int ChangeOrder(void)if(gPlayOrder==CHESS1)gPlayOrder=CHESS2;elsegPlayOrder=CHESS1;return(gPlayOrder);}/*获取按键值*/int GetKey(void){char lowbyte;int press;while (bioskey(1) == 0);/*如果⽤户没有按键,空循环*/press=bioskey(0);lowbyte=press&0xff;press=press&0xff00 + toupper(lowbyte);return(press);}/*落⼦错误处理*/void DoError(void){sound(1200);delay(50);nosound();}/*赢棋处理*/void DoWin(int Order){sound(1500);delay(100);sound(0); delay(50);sound(800); delay(100);sound(0); delay(50);sound(1500);delay(100);sound(0); delay(50);sound(800); delay(100);sound(0); delay(50);nosound();textcolor(RED+BLINK);gotoxy(25,20);if(Order==CHESS1)cputs("PLAYER1 WIN!");elsecputs("PLAYER2 WIN!");gotoxy(25,21);cputs(" \\<^+^>/");getch();}/*⾛棋*/int ChessGo(int Order,struct point Cursor){/*判断交叉点上有⽆棋⼦*/if(gChessBoard[Cursor.x][Cursor.y]==CHESSNULL) {/*若没有棋⼦, 则可以落⼦*/gotoxy(Cursor.x+MAPXOFT,Cursor.y+MAPYOFT); textcolor(LIGHTBLUE);putch(Order);gotoxy(Cursor.x+MAPXOFT,Cursor.y+MAPYOFT); gChessBoard[Cursor.x][Cursor.y]=Order;return TRUE;}elsereturn FALSE;}/*判断当前⾏棋⽅落⼦后是否赢棋*/int JudgeWin(int Order,struct point Cursor)int i;for(i=0;i<4;i++)/*判断在指定⽅向上是否有连续5个⾏棋⽅的棋⼦*/if(JudgeWinLine(Order,Cursor,i))return TRUE;return FALSE;}/*判断在指定⽅向上是否有连续5个⾏棋⽅的棋⼦*/int JudgeWinLine(int Order,struct point Cursor,int direction) {int i;struct point pos,dpos;const int testnum = 5;int count;switch(direction){case 0:/*在⽔平⽅向*/pos.x=Cursor.x-(testnum-1);pos.y=Cursor.y;dpos.x=1;dpos.y=0;break;case 1:/*在垂直⽅向*/pos.x=Cursor.x;pos.y=Cursor.y-(testnum-1);dpos.x=0;dpos.y=1;break;case 2:/*在左下⾄右上的斜⽅向*/pos.x=Cursor.x-(testnum-1);pos.y=Cursor.y+(testnum-1);dpos.x=1;dpos.y=-1;break;case 3:/*在左上⾄右下的斜⽅向*/pos.x=Cursor.x-(testnum-1);pos.y=Cursor.y-(testnum-1);dpos.x=1;dpos.y=1;break;}count=0;for(i=0;i<testnum*2+1;i++)/*i<testnum*2-1*/{if(pos.x>=0&&pos.x<=18&&pos.y>=0&&pos.y<=18){if(gChessBoard[pos.x][pos.y]==Order){count++;if(count>=testnum)return TRUE;}elsecount=0;}pos.x+=dpos.x;pos.y+=dpos.y;}return FALSE;}/*移动光标*/void MoveCursor(int Order,int press){switch(press){case PLAY1UP:if(Order==CHESS1&&gCursor.y>0)gCursor.y--;break;case PLAY1DOWN:if(Order==CHESS1&&gCursor.y<18)gCursor.y++;break;case PLAY1LEFT:if(Order==CHESS1&&gCursor.x>0)gCursor.x--;break;case PLAY1RIGHT:if(Order==CHESS1&&gCursor.x<18)gCursor.x++;break;case PLAY2UP:if(Order==CHESS2&&gCursor.y>0)gCursor.y--;break;case PLAY2DOWN:if(Order==CHESS2&&gCursor.y<18)gCursor.y++;break;case PLAY2LEFT:if(Order==CHESS2&&gCursor.x>0)gCursor.x--;break;case PLAY2RIGHT:if(Order==CHESS2&&gCursor.x<18)gCursor.x++;break;}gotoxy(gCursor.x+MAPXOFT,gCursor.y+MAPYOFT); }/*游戏结束处理*/void EndGame(void){textmode(C80);}/*显⽰当前⾏棋⽅*/void ShowOrderMsg(int Order){gotoxy(6,MAPYOFT+20);textcolor(LIGHTRED);if(Order==CHESS1)cputs("Player1 go!");elsecputs("Player2 go!");gotoxy(gCursor.x+MAPXOFT,gCursor.y+MAPYOFT); }/*落⼦正确处理*/void DoOK(void){sound(500);delay(70);sound(600);delay(50);sound(1000);delay(100);nosound();}/*检查⽤户的按键类别*/int CheckKey(int press){if(press==ESCAPE)return KEYEXIT;/*是退出键*/elseif( ( press==PLAY1DO && gPlayOrder==CHESS1) || ( press==PLAY2DO && gPlayOrder==CHESS2))return KEYFALLCHESS;/*是落⼦键*/elseif( press==PLAY1UP || press==PLAY1DOWN ||press==PLAY1LEFT || press==PLAY1RIGHT ||press==PLAY2UP || press==PLAY2DOWN ||press==PLAY2LEFT || press==PLAY2RIGHT)return KEYMOVECURSOR;/*是光标移动键*/elsereturn KEYINVALID;/*按键⽆效*/}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
五子棋游戏程序(c)

closegraph(); //按Esc键结束
}
char Inputbox(void)
{
char a;
a=getch(); //读入用户输入
if(a!='0')
return a;
else
return '0';
}
////////////////////////////////
//判断五子连珠
////////////////////////////////
{
m++;
n=0;
if(m>=5)
{
drawtext("play1 win!", &r, DT_LEFT);
break;
}
}
else if(*(*(p+i*20)+i*20)=='W')
{
n++;
m=0;
if(n>=5)
{
drawtext("play2 win!", &r, DT_LEFT);
break;
//开始游戏模块
/////////////////////////////////
void start(char (*p)[400])
{
void win(char (*p)[400]);
int x,y,m,n,flag=0,e=1;
char a;
char Inputbox(void);
char s6[]="Input error!";
五子棋游戏程序
规则:1.执黑先行
2.最先在棋盘横向、纵向或斜向形成连续的
C语言实现简易五子棋小游戏

C语⾔实现简易五⼦棋⼩游戏本⽂实例为⼤家分享了C语⾔实现简单五⼦棋⼩游戏的具体代码,供⼤家参考,具体内容如下效果图如下:设计思路:棋盘设计为15×15格,初始状态光标在棋盘的中央,⽩棋先⾛,轮流落⼦,当⼀⽅连成五⼦或下满棋盘时,游戏结束(连成五⼦的⼀⽅获胜,下满棋盘为和棋)。
当游戏⼀⽅胜利后显⽰胜利信息,提⽰信息利⽤汉字点阵输出。
程序游戏是⼀个⼆维平⾯图,可⽤⼆维数组来实现,数组两个下标可以表⽰棋盘上的位置,数组元素的值代表棋格上的状态,共有三种情况,分别是0代表空格,1代表⽩棋,2代表⿊棋。
程序的主要⼯作是接收棋⼿按键操作,棋⼿1⽤设定四个键控制光标移动,回车键表⽰落⼦。
棋⼿2⽤另四个键控制光标移动,空格键表⽰落⼦。
接收到回车键或空格键,说明棋⼿落⼦,先判断是否是有效位置,即有棋⼦的位置不能重叠落⼦。
落⼦成功后,马上判断以该位置为中⼼的⼋个⽅向:上、下、左、右、左上、左下、右上、右下是否有相同颜⾊的棋⼦连成五⼦,如果连成五⼦,则游戏结束。
#include<stdio.h>#include<stdlib.h>#include<windows.h>#pragma comment(lib, "WINMM.LIB")#include <mmsystem.h>#include<conio.h>#include<time.h>#define width 32 //棋盘总宽度#define high 31 //棋盘总⾼度#define MAX_X 15 //棋盘横向格⼦数#define MAX_Y 15 //棋盘纵向格⼦数#define WIDTH (16+width) //游戏总⾼度#define HIGH (high+4) //游戏总⾼度#define player1 1 //⽩⼦玩家#define player2 2 //⿊⼦玩家#define emptyPlayer 0//⽆⼦#define Unplayer -2 //中途退出游戏,⽆玩家获胜typedef struct Stack{//记录下每次落⼦的坐标int x[MAX_X*MAX_Y];int y[MAX_X*MAX_Y];//相当于栈顶指针int top;}Stack;int pos[MAX_X][MAX_Y];//存储棋盘上各位置处的状态⽐如有⽩⼦为1,有⿊⼦为2,⽆⼦为0int px,py; //光标位置int player = 1;//记录当前玩家默认玩家从⽩⽅开始int flag1 = 0;//标志游戏开始int gameOver_player = -1;//判断结束的标志int pre_px = -1, pre_py = -1;//记录下上⼀次的坐标位置void gotoxy(int x,int y);//设置CMD窗⼝光标位置void hide_cursor(); //隐藏CMD窗⼝光标void map();//打印地图void game_Description();//打印动态游戏说明void initMapState();//初始化游戏位置数据void mapState(int qizi);//数组记录下对应位置的状态int isGoPlay();//判断是否可以落⼦int hasGoPlay(int Player);//以落⼦处为中⼼,判断已经落⼦后的棋盘是否五⼦相连void goPlay(int Player, Stack* p);//落⼦ Player 1 2 0void yiDongKuang();//移动框void player1_move();//玩家1_移动void player2_move();//玩家2_移动int gameOver();//判断游戏是否结束Stack* createStack();//创建空栈void push(Stack* p, int x, int y);//⼊栈void color(const unsigned short textColor);//⾃定义函根据参数改变颜⾊//void setColor(unsigned short backColor);//设置游戏背景颜⾊void gotoxy(int x,int y)//设置CMD窗⼝光标位置{COORD coord;coord.X = x;coord.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);}void hide_cursor() //隐藏CMD窗⼝光标{CONSOLE_CURSOR_INFO cci;cci.bVisible = FALSE;cci.dwSize = sizeof(cci);HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);SetConsoleCursorInfo(handle, &cci);}void color(const unsigned short textColor) //⾃定义函根据参数改变颜⾊{if(textColor>0 && textColor<=15) //参数在0-15的范围颜⾊SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), textColor); //⽤⼀个参数,改变字体颜⾊ else //默认的字体颜⾊是⽩⾊SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);}//打印地图void map(){int x, y;color(02);/*开始打印棋盘格⼦*///打印横向图格for(y = 2; y < high - 1; y+=2){for(x = 1; x < width - 2; x+=2){gotoxy(x , y);printf("-+");}}//打印竖向图格for(y = 1; y < high; y += 2) {for(x = 2; x < width-2; x += 2){gotoxy(x , y);printf("|");}}/*打印棋盘格⼦结束*//*开始打印图框*///打印棋盘图框for (y = 0; y < high; y++){for (x = 0; x < width; x+=2){if (x == 0 || x == width - 2){gotoxy(x, y);printf("|");}if(y == 0 || y == high - 1 ){gotoxy(x, y);printf("--");}}}//打印右图框for(y = 0; y < high; y++){for(x = width; x < WIDTH; x+=2){if (x == WIDTH - 2){gotoxy(x, y);printf("|");}if(y == 0 || y == high - 1 ){gotoxy(x, y);printf("--");}}}//打印下图框 y->high ~ HiGH-1 x->0 ~ WIDTH-2 for(y = high; y < HIGH; y++){for(x = 0; x < WIDTH; x+=2){if (x == 0 || x == WIDTH - 2){gotoxy(x, y);printf("|");}if(y == high || y == HIGH - 1 ){gotoxy(x, y);printf("--");}}}//打印下图框内容gotoxy( 1, high+1);printf(" 欢迎来到五⼦棋游戏!");//打印右图框内容gotoxy( width-1, 1);printf("游戏说明:");gotoxy( width-1, 3);printf("1)X表⽰玩家⼀棋");gotoxy( width-1, 4);printf("⼦,⽽O表⽰玩家");gotoxy( width-1, 5);printf("⼆棋⼦");gotoxy( width-1, 7);printf("2)X先、O后,交替");gotoxy( width-1, 8);printf("下⼦,每次只能下");gotoxy( width-1, 9);printf("⼀⼦");gotoxy( width-1, 11);printf("3)棋⼦下在棋盘");gotoxy( width-1, 12);printf("的格⼦内,棋⼦下");gotoxy( width-1, 13);printf("定后,不得向其它");gotoxy( width-1, 14);printf("点移动");gotoxy( width-1, 16);printf("4)最先连成五⼦");gotoxy( width-1, 17);printf("的⼀⽅即为获胜");gotoxy( width-1, 19);printf("玩家⼀移动键:");gotoxy( width-1, 20);printf("w上 s下 a左 d右");gotoxy( width-1, 21);printf("下⼦: 空格键");gotoxy( width-1, 23);printf("玩家⼆移动键:");gotoxy( width-1, 24);printf("i上 k下 j左 l右");gotoxy( width-1, 25);printf("下⼦:回车键");gotoxy( width+1, 27);color(4);printf("退出键: Y");gotoxy( width+1, 29);color(6);printf("悔棋键: G");/*打印图框结束*/color(02);/*打印棋盘上的四个标记点*/gotoxy( 3*2+2 , 3*2+2);printf("*");gotoxy( (MAX_X-4)*2 , 3*2+2);printf("*");gotoxy( 3*2+2 , (MAX_Y-4)*2);printf("*");gotoxy( (MAX_X-4)*2 , (MAX_Y-4)*2); printf("*");/*打印结束*//*开始修边*//*gotoxy(width - 1, 0);printf(" ");gotoxy(width - 1, high - 1);printf(" ");*//*修边结束*//*打印地图完成*/}//打印动态游戏说明void game_Description(){//打印下图框内容gotoxy( 1, high+1);printf(" ");if(player == player1){gotoxy( 1, high+1);color(2);printf(" 玩家⼀下棋中..."); }else if(player == player2){gotoxy( 1, high+1);color(2);printf(" 玩家⼆下棋中..."); }}//初始化游戏位置数据void initMapState(){for(int i = 0 ; i < MAX_Y; i++){for(int j = 0; j < MAX_X; j++){pos[i][j] = 0;//初始状态全为空}}//注意光标的位置和存储在数组中的位置是不同的px = 7;py = 7;gotoxy(py*2+1,px*2+1);//初始位置}//数组记录下对应位置的状态void mapState(int qizi){ //2*px+1 = x //2*py+1 = y //px->0~14 //py->0~14if(px >= MAX_X || px < 0 || py >= MAX_Y || py < 0) return;//其他情况不可以记录状态pos[px][py] = qizi;}//判断是否可以落⼦int isGoPlay(){if(px >= MAX_X || px < 0 || py >= MAX_Y || py < 0)return 0;//其他情况不可以记录状态if(pos[px][py] == emptyPlayer){//说明⽆⼦return 1;}else{//说明有⼦return 0;}}//以落⼦处为中⼼,判断已经落⼦后的棋盘是否五⼦相连int hasGoPlay(int Player){ //分为两部分,先记录⼀部分的相同Player的个数//再记录下另余部分的个数,相加为相连棋⼦总个数 int port1 = 0, port2 = 0;int x, y, count;//上下查找x = px, y = py-1;while(pos[x][y]==Player && y >= 0){++port1;//上部分个数--y;//上移}y = py+1;while(pos[x][y]==Player && y < MAX_Y){++port2;//下部分个数++y;//下移}//计算总数count = port1 + port2 + 1;if(count >= 5) return 1;//左右查找port1 = 0, port2 = 0;x = px-1, y = py;while(pos[x][y]==Player && x >= 0){++port1;//上部分个数--x;//左移}x = px+1;while(pos[x][y]==Player && x < MAX_X){++port2;//下部分个数++x;//右移}//计算总数count = port1 + port2 + 1;if(count >= 5) return 1;//左上右下查找port1 = 0, port2 = 0;x = px-1, y = py-1;while(pos[x][y]==Player && x >= 0 && y >= 0){++port1;//上部分个数--x;//左移--y;//上移}x = px+1, y = py+1;while(pos[x][y]==Player && x < MAX_X && y < MAX_Y){++port2;//下部分个数++x;//右移++y;//下移}//计算总数count = port1 + port2 + 1;if(count >= 5) return 1;//右上左下查找port1 = 0, port2 = 0;x = px+1, y = py-1;while(pos[x][y]==Player && x < MAX_X && y >= 0){++port1;//上部分个数++x;//左移--y;//上移}x = px-1, y = py+1;while(pos[x][y]==Player && x >= 0 && y < MAX_Y){++port2;//下部分个数--x;//右移++y;//下移}//计算总数count = port1 + port2 + 1;if(count >= 5) return 1;return 0;}//落⼦ Player 1 2 0void goPlay(int Player, Stack* p){if(isGoPlay()){//说明可以落⼦mapState(Player);//将对应位置的情况记录在数组中if(hasGoPlay(Player)){//如果五⼦相连,则 gameovergameOver_player = Player; //记录此刻胜利玩家,结束游戏 }/*⼊栈*/push(p, px, py);/*⾓⾊切换*/if(Player == player1){player = player2;//切换成玩家1gotoxy(px*2+1, py*2+1 );//将光标移动到对应位置color(07);printf("X");//打印玩家1game_Description();// 动态说明}else if(Player == player2){player = player1;//切换成另⼀个玩家2gotoxy( px*2+1, py*2+1);//将光标移动到对应位置 color(07);printf("O");//打印玩家2game_Description();// 动态说明}}}//⼊栈void push(Stack* p, int x, int y){//将此刻的坐标⼊栈int top = p->top;++p->top;//移动栈针p->x[top] = x;p->y[top] = y;return;}//出栈void pop(Stack* p){int x, y;//出栈,移动栈顶指针//如果栈为空,则不弹出if(p->top <= 0) return;--p->top;int top = p->top;//记录下弹出的位置x = p->x[top];y = p->y[top];//在弹出位置打印空格gotoxy(x*2+1, y*2+1);printf(" ");//抹除记录pos[x][y] = 0;}//移动框void yiDongKuang(){//打印移动框gotoxy(px*2, py*2+1);color(11);printf("[");gotoxy(px*2+2, py*2+1);printf("]");//打印移动框结束if(pre_px != -1 && pre_py != -1){if(pre_px > px && pre_py == py){//当向左移动时//将上⼀个位置的右边保持原样gotoxy(pre_px*2+2, pre_py*2+1);color(2);printf("|");}else if(pre_px < px && pre_py == py){//当向右移动时//将上⼀个位置的左边保持原样gotoxy(pre_px*2, pre_py*2+1);color(2);printf("|");}else{//当向上下移动时//将上⼀个位置的左右边保持原样gotoxy(pre_px*2+2, pre_py*2+1);color(2);printf("|");gotoxy(pre_px*2, pre_py*2+1);color(2);printf("|");}}pre_px = px;pre_py = py;}//玩家1 移动void player1_move(Stack* p){char key;if (_kbhit())//检测是否按键{fflush(stdin);key = _getch();//保存按键game_Description();//动态说明}switch(key){case 'w': py--;yiDongKuang();break;//上case 'a': px--;yiDongKuang();break;//左case 'd': px++;yiDongKuang();break;//右case 's': py++;yiDongKuang();break;//下case ' ': goPlay(player1, p);break;//落⼦case 'y': gameOver_player = -2; gameOver();//退出游戏 case 'Y': gameOver_player = -2; gameOver();//退出游戏case 'g': pop(p); pop(p); break;//悔棋case 'G': pop(p); pop(p); break;//悔棋default: break;}//限制光标范围if(py < 0) py = MAX_Y-1;else if(py >= MAX_Y) py = 0;else if(px < 0) px = MAX_X-1;else if(px >= MAX_X) px = 0;gotoxy(2*py+1, 2*px+1);}//玩家2 移动void player2_move(Stack* p){char key;if (_kbhit())//检测是否按键{fflush(stdin);key = _getch();//保存按键game_Description();//动态说明}switch(key){case 'i': py--;yiDongKuang();break;//上case 'j': px--;yiDongKuang();break;//左case 'l': px++;yiDongKuang();break;//右case 'k': py++;yiDongKuang();break;//下case '\r': goPlay(player2, p);break;//落⼦case 'y': gameOver_player = -2; gameOver();//退出游戏case 'Y': gameOver_player = -2; gameOver();//退出游戏case 'g': pop(p); pop(p); break;//悔棋case 'G': pop(p); pop(p); break;//悔棋default: break;}//限制光标范围if(py < 0) py = MAX_Y-1;else if(py >= MAX_Y) py = 0;else if(px < 0) px = MAX_X-1;else if(px >= MAX_X) px = 0;gotoxy(2*px+1, 2*py+1);}//创建空栈Stack* createStack(){//申请空间Stack* p = (Stack* )malloc(sizeof(Stack));//如果未申请到空间if(p==NULL) return NULL;p->top = 0;//初始化栈顶return p;}//判断游戏是否结束int gameOver(){ //gamerOver_player -1 表⽰继续游戏 1 表⽰⽩⽅胜利 2 表⽰⿊⽅胜利 0 表⽰平局 //五⼦相连⼀⽅取胜 y->high ~ HiGH-1 x->0 ~ WIDTH-2if(gameOver_player == -1){return 1;}else if(gameOver_player == player1){//⽩⽅胜利gotoxy( 1, high+1);printf("玩家1胜利");return 0;}else if(gameOver_player == player2){//⿊⽅胜利gotoxy( 1, high+1);printf("玩家2胜利");return 0;}else if(gameOver_player == emptyPlayer){//棋盘满棋平局gotoxy( 1, high+1);printf("平局");return 0;}else if(gameOver_player == Unplayer){//中途退出gotoxy( 1, high+1);printf("正在退出游戏中...");exit(1);}return 1;}int main(){//调整游戏框system("mode con cols=48 lines=35");//打印地图map();//初始化游戏位置数据initMapState();//创建空栈Stack* p = createStack();//隐藏光标hide_cursor();//游戏循环控制移动while(gameOver()){//不断调换⼈物if(player == player1)player1_move(p);// 切换玩家1else if(player == player2)player2_move(p);// 切换玩家2}free(p);}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
五子棋游戏 C语言 代码 源代码

#include <stdio.h>#include <stdlib.h>#define m 30int main (void){int count;//计数器算横纵行的结果int w,h;int u;int l;int i,size;//i声明步数。
size声明int r[m][m] = {0};//数组声明(棋子位置)int x, y;//声明落子坐标int n;//声明棋盘大小nchar a[20],b[20];printf ("请输入棋盘大小n\n");//编辑棋盘直到棋盘长度宽度大于4小于30 scanf ("%d", &n);if (n<=4 || n>m){do{printf ("输入的棋盘大小:4<n<%d\n", m);scanf ("%d", &n);}while (n<=4 || n>m);}getchar ();//声明玩家printf ("请输入玩家1姓名:\n");gets(a);printf ("请输入玩家2姓名:\n");gets(b);for ( i = 1, size = n*n;i <= size; i++)//编辑棋盘{if (i%2 == 1)//如果i能被2整除,为玩家a相关信息{do//玩家a棋子信息{printf ("%s该你下棋了,第%d个棋子\n", a, i);scanf ("%d%d", &x, &y);if (x > n || x < 0)//判断坐标是否在棋盘内,如果不是则重新输入{do{printf ("0<=横坐标<=%d请重新输入横坐标\n", n);scanf ("%d", &x);}while (x>m || x<0);}if (y > n || y < 0)//判断坐标是否在棋盘内,如果不是则重新输入{do{printf ("0<=纵坐标<=%d请重新输入纵坐标\n", n);scanf ("%d", &y);}while (y < 0 || y > n);}}while ((r[x][y] == 1 && (printf ("这个位置上已经有棋子了,请重新输入\n")))|| r[x][y] == 2&& (printf ("这个位置上已经有棋子了,请重新输入\n")) );r[x][y] = 1;for (u = 0;u < n; u++)//不同情况下判断玩家a获胜方式{for (l = 0;l < n;l++){count = 0;for (w = u,h = l;r[w][h] == 1 && h < n; h++)count++;if (count == 5){printf ("%s是胜利者\n", a);goto e;//直接跳转,其余代码不在运行count = 0;for (w = u, h = l; r[w][h] == 1 && w < n; w++)count ++;if (count == 5){printf ("%s是胜利者\n", a);goto e;}count = 0;for (w = u,h = l; r[w][h] == 1 && w < n && h<n;w++,h++)count++;if (count == 5){printf ("%s是胜利者\n", a);goto e;}count = 0;for (w =u ,h =l;r[w][h] == 1 && h > 0;h--)count++;if (count == 5){printf ("%s是胜利者\n", a);goto e;}}}}system("cls");for (int j = n;j>=0;j--){printf ("%-2d", j);for (int k = 0;k < n;k++)//画棋盘,声明两玩家棋子图片{if (r[k][j] == 0)printf ("╋");else if(r[k][j] == 1)printf ("○");else if (r[k][j] == 2)printf ("●"); }printf ("\n");}printf (" ");for (int k = 0;k < n;k++)printf ("%-2d", k);}else if (i%2 == 0)//如果i不能被2整除,为玩家b相关信息{do{printf ("\n%s该你下棋了,第%d个棋子\n", b, i);scanf ("%d%d", &x, &y);if (x > n || x < 0){do{printf ("0<=横坐标<=%d请重新输入横坐标\n", n);scanf ("%d", &x);}while (x>n || x<0);}if (y >n|| y < 0){do{printf ("0<=纵坐标<=%d请重新输入纵坐标\n", n);scanf ("%d", &y);}while (y < 0 || y > n);}}while ((r[x][y] == 1 && (printf ("这个位置上已经有棋子了,请重新输入\n")))|| r[x][y] == 2&& (printf ("这个位置上已经有棋子了,请重新输入\n")) );r[x][y] = 2;system("cls");for (int j = n;j>=0;j--){printf ("%-2d", j);for (int k = 0;k < n;k++){if (r[k][j] == 0)printf ("╋");else if(r[k][j] == 1)printf ("○");else if (r[k][j] == 2)printf ("●");}printf ("\n");}printf (" ");for (int k = 0;k < n;k++)printf ("%-2d", k); printf ("\n");count = 0;for (u = 0;u < n; u++){for (l = 0;l < n;l++){count = 0;for (w = u,h = l;r[w][h] == 2 && h < n; h++)count++;if (count == 5){printf ("%s是胜利者\n", b);goto e;}count = 0;for (w = u, h = l; r[w][h] == 2 && w < n; w++)count ++;if (count == 5){printf ("%s是胜利者\n", b);goto e;}count = 0;for (w = u,h = l; r[w][h] == 2 && w < n && h<n;w++,h++)count++;if (count == 5){printf ("%s是胜利者\n", b);goto e;}count = 0;for (w =u ,h =l;r[w][h] == 2 && h > 0;h--)count++;if (count == 5){printf ("%s是胜利者\n", b);goto e;}}}}}e: for (int j = n;j>=0;j--)//游戏结束界面棋盘固定重新显示{printf ("%-2d", j);for (int k = 0;k < n;k++){if (r[k][j] == 0)printf ("╋");else if(r[k][j] == 1)printf ("○");else if (r[k][j] == 2)printf ("●");}printf ("\n");}printf (" ");for (int k = 0;k < n;k++)printf ("%-2d", k); printf ("\n");printf ("\a游戏愉快,Powered by Techmessager\n");//结束语句return 0;}。
用C编写一个五子棋游戏

用C编写一个五子棋游戏五子棋,又称连珠棋、五目棋,是一种源于中国古代的传统策略棋类游戏。
其规则简单,但却充满足智慧和挑战性。
在本文中,我将介绍如何用C语言编写一个基于控制台的五子棋游戏。
一、游戏规则五子棋游戏的目标是在棋盘上先形成连续的五个棋子。
棋盘由15×15个网格组成,玩家轮流在空白格上下子。
第一个连成五个棋子的玩家即为胜利者。
二、游戏实现为了编写五子棋游戏,我们需要运用C语言中的某些基本概念和技巧。
首先,我们需要使用二维数组来表示棋盘。
每个格子可以用空格、黑子或白子来表示。
接下来,我们需要使用循环来实现玩家间的轮流下子。
通过判断每个下子位置是否满足游戏规则来决定是否胜利。
下面是一个简单的五子棋游戏的C代码示例:```c#include <stdio.h>#define SIZE 15char board[SIZE][SIZE];void init_board() {for (int i = 0; i < SIZE; i++) {for (int j = 0; j < SIZE; j++) { board[i][j] = ' ';}}}void print_board() {printf(" ");for (int i = 0; i < SIZE; i++) { printf("%2d", i);}printf("\n");for (int i = 0; i < SIZE; i++) { printf("%2d", i);for (int j = 0; j < SIZE; j++) { printf("%2c", board[i][j]); }printf("\n");}}int is_valid_move(int x, int y) {return (x >= 0 && x < SIZE && y >= 0 && y < SIZE && board[x][y] == ' ');}int is_winner(int x, int y, char player) {int dx[] = {-1, 0, 1, 1};int dy[] = {1, 1, 1, 0};for (int i = 0; i < 4; i++) {int count = 1;int nx = x;int ny = y;while (count < 5) {nx += dx[i];ny += dy[i];if (nx >= 0 && nx < SIZE && ny >= 0 && ny < SIZE && board[nx][ny] == player) {count++;} else {break;}}if (count == 5) {return 1;}}return 0;}int main() {init_board();print_board();int x, y;char player = 'X';while (1) {printf("Player %c's turn. Enter x y: ", player); scanf("%d %d", &x, &y);if (is_valid_move(x, y)) {board[x][y] = player;print_board();if (is_winner(x, y, player)) {printf("Player %c wins!\n", player);break;}player = (player == 'X') ? 'O' : 'X';} else {printf("Invalid move. Please try again.\n");}}return 0;}```以上代码仅为五子棋游戏的简单实现,还有许多细节和优化可以添加。
c语言简易五子棋cmd程序代码

p=0;
}
}
p=0;
k=panding(i,j,h,s);/*判定*//*用上面定义的panding()判定这个子是否与其他子相连大于等于5个*/
}
while(b==2&&k==0)/*白棋步骤与黑棋类似*/
char h=2,w=1;/*用于上面panding()函数的输入,在上一个函数最后需要输入来判定胜利的是黑子还是白子*/
while(i<25)/*将横向数组用‘+’和‘ ’间隔表示*/
{
while(j<=50)
{
s[i][j]='+';/*将可以下子的位置显示为‘+’方便计算和观察*/
while(b==1&&k==0)/*在黑子步骤且无人胜利的情况下进行黑子步骤*/
{
printf("请下黑棋\n");
while(p==0)/*下子之前计算好输入值如实际值的对应,这里用循环是需要判定输入的坐标是否符合要求,如不符合则循环输入直到符合为止*/
{
while(p=;p);
if(p==1)
{
k=0;
b=1;
p=1;
i=0;
j=0;
while(i<25)
{
{
printf("请下白棋\n");
while(p==0)
{
scanf("%d%d",&j,&i);
if(s[24-i][j*2]=='+'&&i>0&&i<25&&j>0&&j<25)
五子棋游戏代码—C语言

C语言游戏之五子棋源代码#include<stdio.h>#include<stdlib.h>#include<graphics.h>#include<bios.h>#include<conio.h>#define LEFT 0x4b00#define RIGHT 0x4d00#define DOWN 0x5000#define UP 0x4800#define ESC 0x011b#define SPACE 0x3920#define BILI 20#define JZ 4#define JS 3#define N 19int box[N][N];int step_x,step_y ;int key ;int flag=1 ;void draw_box();void draw_cicle(int x,int y,int color); void change();void judgewho(int x,int y);void judgekey();int judgeresult(int x,int y);void attentoin();void attention(){char ch ;window(1,1,80,25);textbackground(LIGHTBLUE);textcolor(YELLOW);clrscr();gotoxy(15,2);printf("游戏操作规则:");gotoxy(15,4);printf("Play Rules:");gotoxy(15,6);printf("1、按左右上下方向键移动棋子");gotoxy(15,8);printf("1. Press Left,Right,Up,Down Key to move Piece");gotoxy(15,10);printf("2、按空格确定落棋子");gotoxy(15,12);printf("2. Press Space to place the Piece");gotoxy(15,14);printf("3、禁止在棋盘外按空格");gotoxy(15,16);printf("3. DO NOT press Space outside of the chessboard");gotoxy(15,18);printf("你是否接受上述的游戏规则(Y/N)");gotoxy(15,20);printf("Do you accept the above Playing Rules? [Y/N]:");while(1){gotoxy(60,20);ch=getche();if(ch=='Y'||ch=='y')break ;else if(ch=='N'||ch=='n'){window(1,1,80,25);textbackground(BLACK);textcolor(LIGHTGRAY);clrscr();exit(0);}gotoxy(51,12);printf(" ");}}void draw_box(){int x1,x2,y1,y2 ;setbkcolor(LIGHTBLUE);setcolor(YELLOW);gotoxy(7,2);printf("Left, Right, Up, Down KEY to move, Space to put, ESC-quit.");for(x1=1,y1=1,y2=18;x1<=18;x1++) line((x1+JZ)*BILI,(y1+JS)*BILI,(x 1+JZ)*BILI,(y2+JS)*BILI);for(x1=1,y1=1,x2=18;y1<=18;y1++) line((x1+JZ)*BILI,(y1+JS)*BILI,(x 2+JZ)*BILI,(y1+JS)*BILI);for(x1=1;x1<=18;x1++)for(y1=1;y1<=18;y1++)box[x1][y1]=0 ;}void draw_circle(int x,int y,int color) {setcolor(color);setlinestyle(SOLID_LINE,0,1);x=(x+JZ)*BILI ;y=(y+JS)*BILI ;circle(x,y,8);}void judgekey(){int i ;int j ;switch(key){case LEFT :if(step_x-1<0)break ;else{for(i=step_x-1,j=step_y;i>=1;i --)if(box[i][j]==0){draw_circle(step_x,step_y,LIGHTBLU E);break ;}if(i<1)break ;step_x=i ;judgewho(step_x,step_y);break ;}case RIGHT :if(step_x+1>18)break ;else{for(i=step_x+1,j=step_y;i<=18 ;i++)if(box[i][j]==0){draw_circle(step_x,step_y,LIGH TBLUE);break ;}if(i>18)break ;step_x=i ;judgewho(step_x,step_y);break ;}case DOWN :if((step_y+1)>18)break ;else{for(i=step_x,j=step_y+1;j<=18 ;j++)if(box[i][j]==0){draw_circle(step_x,step_y,LIGHTBLU E);break ;}if(j>18)break ;step_y=j ;judgewho(step_x,step_y);break ;}case UP :if((step_y-1)<0)break ;else{for(i=step_x,j=step_y-1;j>=1;j --)if(box[i][j]==0){draw_circle(step_x,step_y,LIGHTBLU E);break ;}if(j<1)break ;step_y=j ;judgewho(step_x,step_y);break ;}case ESC :break ;case SPACE :if(step_x>=1&&step_x<=18&&s tep_y>=1&&step_y<=18){if(box[step_x][step_y]==0){box[step_x][step_y]=flag ; if(judgeresult(step_x,step_y)==1){sound(1000);delay(1000);nosound();gotoxy(30,4);if(flag==1){setbkcolor(BLUE);cleardevice(); setviewport(100,100,540,380,1);/*定义一个图形窗口*/setfillstyle(1,2);/*绿色以实填充*/setcolor(YELLOW);rectangle(0,0,439,279);floodfill(50,50,14);setcolor(12);settextstyle(1,0,5);/*三重笔划字体, 水平放?5倍*/ outtextxy(20,20,"The White Win !");setcolor(15);settextstyle(3,0,5);*无衬笔划字体, 水平放大5倍*/ uttextxy(120,120,"The White Win !");setcolor(14);settextstyle(2,0,8);getch();closegraph();exit(0);}if(flag==2){setbkcolor(BLUE);cleardevice();setviewport(100,100,540,380,1);/*定义一个图形窗口*/setfillstyle(1,2);/*绿色以实填充*/setcolor(YELLOW);rectangle(0,0,439,279);floodfill(50,50,14);setcolor(12);settextstyle(1,0,8);笔划字体, 水平放大8倍*/ outtextxy(20,20,"The Red Win !");setcolor(15);settextstyle(3,0,5);/*无衬笔划字体, 水平放大5倍*/outtextxy(120,120,"The Red Win !");setcolor(14);settextstyle(2,0,8);getch();closegraph();exit(0);}}change();break ;}}elsebreak ;}}void change(){if(flag==1)flag=2 ;elseflag=1 ;}void judgewho(int x,int y){if(flag==1)draw_circle(x,y,15);if(flag==2)draw_circle(x,y,4);}int judgeresult(int x,int y){ int j,k,n1,n2 ;while(1){ n1=0 ;n2=0 ;/*水平向左数*/for(j=x,k=y;j>=1;j--){ if(box[j][k]==flag)n1++;elsebreak ;}/*水平向右数*/for(j=x,k=y;j<=18;j++) {if(box[j][k]==flag)n2++;elsebreak ;}if(n1+n2-1>=5){return(1);break ;}/*垂直向上数*/n1=0 ;n2=0 ;for(j=x,k=y;k>=1;k--) {if(box[j][k]==flag)n1++;elsebreak ;}/*垂直向下数*/for(j=x,k=y;k<=18;k++) {if(box[j][k]==flag)n2++;elsebreak ;}if(n1+n2-1>=5){return(1);break ;}/*向左上方数*/n1=0 ;n2=0 ;for(j=x,k=y;j>=1,k>=1;j--,k--){if(box[j][k]==flag)n1++;elsebreak ;}/*向右下方数*/for(j=x,k=y;j<=18,k<=18;j++,k+ +){if(box[j][k]==flag)n2++;elsebreak ;}if(n1+n2-1>=5){return(1);break ;}/*向右上方数*/n1=0 ;n2=0 ;for(j=x,k=y;j<=18,k>=1;j++,k--){if(box[j][k]==flag)n1++;elsebreak ;}/*向左下方数*/for(j=x,k=y;j>=1,k<=18;j--,k++){if(box[j][k]==flag)n2++;elsebreak ;}if(n1+n2-1>=5){ return(1);break ;}return(0);break ;} }void main(){int gdriver=VGA,gmode=VGAHI;clrscr();attention();initgraph(&gdriver,&gmode,"c:\\tc" );/* setwritemode(XOR_PUT);*/flag=1 ;draw_box();do{step_x=0 ;step_y=0 ;/*draw_circle(step_x,step_y,8); */judgewho(step_x-1,step_y-1);do{while(bioskey(1)==0);key=bioskey(0);judgekey();}while(key!=SPACE&&key!=ESC);}while(key!=ESC);closegraph();}。
c五子棋简易游戏代码

#include<stdio.h>#define N 10void welcome();void initqipan();void showqi(int i);void save(int p);void panduan(int p);void heqi();void over();int zouqihang();int zouqilie();/******************结构体*****************/ struct zuobiao{int x[N * N];int y[N * N];} weizhi[N * N];/******************主函数*****************/ int main(){int p = 0;welcome();initqipan();for (p = 1; p <= N * N; p++){weizhi[p].x[p] = zouqihang();weizhi[p].y[p] = zouqilie();save(p);showqi(p);panduan(p);}if (p == N * N)heqi();over();}/******************建立棋盘*****************/void initqipan(){int i, j;for (i = 0; i < N; i++){printf("%d", i);printf(" ");}printf("\n");for (i = 1; i < N; i++){for (j = 0; j < N; j++){if (j == 0)printf("%d", i);elseprintf("·");}printf("\n");}}/******************显示棋子*****************/void showqi(int p){int i, j, k, m;int a[N * N], b[N * N];FILE *fp;fp = fopen("wuzi_list", "rb");for (i = 1; i <= N * N; i++){fread(&weizhi[i], sizeof(struct zuobiao), 1, fp);a[i] = weizhi[i].x[i];b[i] = weizhi[i].y[i];} for (m = 1; m < p; m++){while(weizhi[p].x[p] == a[m] && weizhi[p].y[p] == b[m]){printf("error!\n");weizhi[p].x[p] = zouqihang();weizhi[p].y[p] = zouqilie();m = 1;}}for (i = 0; i < N; i++){printf("%d", i);printf(" ");}printf("\n");for (i = 1; i < N; i++){for (j = 1; j < N; j++){if (j == 1)printf("%d", i);for (k = 1; k <= p; k++){if (i == weizhi[k].x[k] && j == weizhi[k].y[k]){if (k % 2 == 1){printf("○");break;}else if (k % 2 == 0){printf("●");break;}}}if (k > p)printf("·");elsecontinue;}printf("\n");}}/******************走棋行*****************/int zouqihang(){int x;printf("请输入要走棋子所在行数!\n");printf("x=");scanf("%d", &x);while (x > N - 1 || x < 1){printf("error!\n");printf("请输入要走棋子所在行数!\n");printf("x=");scanf("%d", &x);}return x;}/******************走棋列*****************/int zouqilie(){int y;printf("请输入要走棋子所在列数!\n");printf("y=");scanf("%d", &y);while (y > N - 1 || y < 1){printf("error!\n");printf("请输入要走棋子所在列数!\n");printf("y=");scanf("%d", &y);}return y;}/******************文件保存*****************/void save(int i){FILE *fp;fp = fopen("wuzi_list", "wb");fwrite(&weizhi[i], sizeof(struct zuobiao), 1, fp);} /****************判断输赢*******************/ void panduan(int p){int i, j, k[8] = { 1, 1, 1, 1, 1, 1, 1, 1, };int a[N * N], b[N * N];FILE *fp;fp = fopen("wuzi_list", "rb");for (i = 1; i <= p; i++){fread(&weizhi[i], sizeof(struct zuobiao), 1, fp);a[i] = weizhi[i].x[i];b[i] = weizhi[i].y[i];} /*****************判断行******************/ for (i = 1; i <= p; i++) {if (i % 2 == 1){for (j = 1; j <= p; j = j + 2){if ((a[i] == a[j]) && (b[i] == b[j] - 1)){k[0]++;continue;}else if ((a[i] == a[j]) && (b[i] == b[j] - 2)){k[0]++;continue;}else if ((a[i] == a[j]) && (b[i] == b[j] - 3)){k[0]++;continue;}else if ((a[i] == a[j]) && (b[i] == b[j] - 4)){k[0]++;continue;}else if (k[0] == 5){printf("Player 1 wins!!!\n");}elsecontinue;}if (k[0] == 5)break;k[0] = 1;}else if (k[0] == 5)break;else if (i % 2 == 0){for (j = 2; j <= p; j = j + 2){if ((a[i] == a[j]) && (b[i] == b[j] - 1)){k[1]++;continue;}else if ((a[i] == a[j]) && (b[i] == b[j] - 2)){k[1]++;continue;}else if ((a[i] == a[j]) && (b[i] == b[j] - 3)){k[1]++;continue;}else if ((a[i] == a[j]) && (b[i] == b[j] - 4)){k[1]++;continue;}else if (k[1] == 5){printf("Player 2 wins!!!\n");}elsecontinue;}if (k[1] == 5)break;k[1] = 1;}}/**********************判断列************************/for (i = 1; i <= p; i++){if (k[0] == 5 || k[1] == 5)break;else if (i % 2 == 1){for (j = 1; j <= p; j = j + 2){if ((a[i] == a[j] - 1) && (b[i] == b[j])){k[2]++;continue;}else if ((a[i] == a[j] - 2) && (b[i] == b[j])){k[2]++;continue;}else if ((a[i] == a[j] - 3) && (b[i] == b[j])){k[2]++;continue;}else if ((a[i] == a[j] - 4) && (b[i] == b[j])){k[2]++;continue;}else if (k[2] == 5){printf("Player 1 wins!!!\n");}elsecontinue;}if (k[2] == 5)break;k[2] = 1;}else if (k[2] == 5)break;else if (i % 2 == 0){for (j = 2; j <= p; j = j + 2){if ((a[i] == a[j] - 1) && (b[i] == b[j])){k[3]++;continue;}else if ((a[i] == a[j] - 2) && (b[i] == b[j])){k[3]++;continue;}else if ((a[i] == a[j] - 3) && (b[i] == b[j])){k[3]++;continue;}else if ((a[i] == a[j] - 4) && (b[i] == b[j])){k[3]++;continue;}else if (k[3] == 5){printf("Player 2 wins!!!\n");}elsecontinue;}if (k[3] == 5)break;k[3] = 1;}} /****************判断对角(左上-右下)******************/for (i = 1; i <= p; i++){if (k[0] == 5 || k[1] == 5 || k[2] == 5 || k[3] == 5)break;else if (i % 2 == 1){for (j = 1; j <= p; j = j + 2){if ((a[i] == a[j] - 1) && (b[i] == b[j] - 1)){k[4]++;continue;}else if ((a[i] == a[j] - 2) && (b[i] == b[j] - 2)){k[4]++;continue;}else if ((a[i] == a[j] - 3) && (b[i] == b[j] - 3)){k[4]++;continue;}else if ((a[i] == a[j] - 4) && (b[i] == b[j] - 4)){k[4]++;continue;}else if (k[4] == 5){printf("Player 1 wins!!!\n");}elsecontinue;}if (k[4] == 5)break;k[4] = 1;}else if (k[2] == 5)break;else if (i % 2 == 0){for (j = 2; j <= p; j = j + 2){if ((a[i] == a[j] - 1) && (b[i] == b[j] - 1)){k[5]++;continue;}else if ((a[i] == a[j] - 2) && (b[i] == b[j] - 2)){k[5]++;continue;}else if ((a[i] == a[j] - 3) && (b[i] == b[j] - 3)){k[5]++;continue;}else if ((a[i] == a[j] - 4) && (b[i] == b[j] - 4)){k[5]++;continue;}else if (k[5] == 5){printf("Player 2 wins!!!\n");}elsecontinue;}if (k[5] == 5)break;k[5] = 1;}}/**********判断对角(左下-右上)************/ for (i = 1; i <= p; i++){if (k[0] == 5 || k[1] == 5 || k[2] == 5 || k[3] == 5 || k[4] == 5|| k[5] == 5)break;else if (i % 2 == 1){for (j = 1; j <= p; j = j + 2){if ((a[i] == a[j] + 1) && (b[i] == b[j] - 1)){k[6]++;continue;}else if ((a[i] == a[j] + 2) && (b[i] == b[j] - 2)){k[6]++;continue;}else if ((a[i] == a[j] + 3) && (b[i] == b[j] - 3)){k[6]++;continue;}else if ((a[i] == a[j] + 4) && (b[i] == b[j] - 4)){k[6]++;continue;}else if (k[6] == 5){printf("Player 1 wins!!!\n");}elsecontinue;}if (k[6] == 5)break;k[6] = 1;}else if (k[6] == 5)break;else if (i % 2 == 0){for (j = 2; j <= p; j = j + 2){if ((a[i] == a[j] + 1) && (b[i] == b[j] - 1)){k[7]++;continue;}else if ((a[i] == a[j] + 2) && (b[i] == b[j] - 2)){k[7]++;continue;}else if ((a[i] == a[j] + 3) && (b[i] == b[j] - 3)){k[7]++;continue;}else if ((a[i] == a[j] + 4) && (b[i] == b[j] - 4)){k[7]++;continue;}else if (k[7] == 5){printf("Player 2 wins!!!\n");}elsecontinue;}if (k[7] == 5)break;k[7] = 1;}}}/****************和棋*******************/void heqi(){printf("************************** **********\n");printf(" Tie!!!\n");printf("************************** **********\n");} /****************游戏结束*******************/ void over() {printf("************************** **********\n");printf(" game over!!!\n");printf("************************** **********\n");} /****************游戏开始*******************/ void welcome() {printf(" Welcome!!!\n");printf("************************** **********\n");}。
C++五子棋编写(控制台版_CMD命令框版)【简单五子棋游戏_适合初学者学习_代码有详细注释】

jieC++五子棋Ver2.1程序+代码[带AI、悔棋等]【控制台版】这是用C++编写的一个简单五子棋游戏,带AI(电脑)、悔棋等功能。
支持单人游戏(与电脑对战)和双人对战。
使用的C++知识也很简单,只需要懂基本的语法,不需要用到API。
这个游戏不是图形界面的。
是DOS版或者说控制台版的。
游戏的运行界面如下:这其实是第三版,添加了悔棋,修复AI[电脑]的几个BUG,以及悔棋的一个小问题。
当然了,若是还有什么BUG可以指出,我们的QQ:775904764,有问题也可以找我。
代码如下://--------------------------------------------------------------------------//// 简单五子棋(控制台版)代码[Ver2.1]// 修复了AI越界的问题,简化评分函数,修复输赢判断函数的BUG。
// AI评分函数规则有部分改变,代码也更加简练。
// 新增悔棋功能,仅与AI对战时可用,新增重新开始功能。
// 修复悔棋的一个小BUG,修复AI随机落子部分的定义错误。
// 作者:落叶化尘 QQ:775904764//--------------------------------------------------------------------------//#include "五子棋类.h"#include <time.h>#include <iostream>using namespace std;static const char ch[11][4]={"┌","┬","┐","├","┼","┤","└","┴","┘","○","●"}; //可供选用的字符,输出棋盘或者棋子用static int Record[15][15]={0}; //记录棋子static int Score[15][15]={0}; //评分static int Sum=0,Renum=0;int main(){int Default[15][15]={ 0,1,1,1,1,1,1,1,1,1,1,1,1,1,2, //空棋盘3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,6,7,7,7,7,7,7,7,7,7,7,7,7,7,8 };int value[15][15]={0};FiveChess Start;do{Start.StartGame(value,Default); //开始游戏}while (Start.Continue); //若是要退出就修改这个值return 0;}//------------------------------开始游戏------------------------------------------// void FiveChess::StartGame(int value[][15],int Default[][15]){Empty(value,Default); //初始化棋盘adExWhile=true;while(ExWhile){Choice=MainMenu(); //调用主菜单,并把用户选择的值储存在Choice里switch(Choice){case 1:flag=1;ExWhile=false;break; //把标志设置为1,与AI对战case 2:flag=2;ExWhile=false;break; //把标志设置为2,双人对战case 3:Select=Introduce();ExWhile=Select;Continue=false;break; //游戏说明函数case 4:Select=Coder();ExWhile=Select;Continue=false;break; //作者介绍函数case 5:Exit();ExWhile=false;Continue=false;break; //退出游戏函数default:cin.fail();cin.clear();cin.sync();cout<<"输出错误,请重新输入!\n";system("pause>nul 2>nul");ExWhile=true;break; //其它}}if (flag==1) //如果标志等于1,说明为单人游戏{Single(value);}else if (flag==2) //如果标志等于2,说明为双人游戏{Double(value);}flag=0;}//------------------------清空棋盘或初始化棋盘-----------------------------------// void FiveChess::Empty(int value[][15],int Default[][15]) //清空棋盘{for (int i=0;i<15;i++){for (int j=0;j<15;j++){value[i][j]=Default[i][j];}}}void FiveChess::Exit() //退出游戏{system("cls");cout<<"┌—————————————————————————┐\n";cout<<"│感谢您使用:简单五子棋 Ver2.1 │\n";cout<<"││\n";cout<<"│[游戏制作]:落叶化尘│\n";cout<<"│[联系Q Q ]: 775904764 │\n";cout<<"│[联系邮箱]:lxhdjwg@ │\n";cout<<"│[简单说明]:游戏结束界面,谢谢您的使用!│\n";cout<<"└—————————————————————————┘\n";cout<<"感谢您的使用,谢谢!按任意键退出游戏...\n";system("pause>nul 2>nul");}bool FiveChess::Introduce() //游戏介绍{system("cls");cout<<"┌—————————————————————————┐\n";cout<<"│简单五子棋 Ver2.1[游戏介绍界面] │\n";cout<<"││\n";cout<<"│[单人游戏]:玩家和AI(人工智能)对战,AI智商不高。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
C++五子棋Ver2.1程序+代码[带AI、悔棋等]【控制台版】这是用C++编写的一个简单五子棋游戏,带AI(电脑)、悔棋等功能。
支持单人游戏(与电脑对战)和双人对战。
使用的C++知识也很简单,只需要懂基本的语法,不需要用到API。
这个游戏不是图形界面的。
是DOS版或者说控制台版的。
游戏的运行界面如下:这其实是第三版,添加了悔棋,修复AI[电脑]的几个BUG,以及悔棋的一个小问题。
当然了,若是还有什么BUG可以指出,我们的QQ:775904764,有问题也可以找我。
代码如下://--------------------------------------------------------------------------//// 简单五子棋(控制台版)代码[Ver2.1]// 修复了AI越界的问题,简化评分函数,修复输赢判断函数的BUG。
// AI评分函数规则有部分改变,代码也更加简练。
// 新增悔棋功能,仅与AI对战时可用,新增重新开始功能。
// 修复悔棋的一个小BUG,修复AI随机落子部分的定义错误。
// 作者:落叶化尘 QQ:775904764//--------------------------------------------------------------------------//#include "五子棋类.h"#include <time.h>#include <iostream>using namespace std;static const char ch[11][4]={"┌","┬","┐","├","┼","┤","└","┴","┘","○","●"}; //可供选用的字符,输出棋盘或者棋子用static int Record[15][15]={0}; //记录棋子static int Score[15][15]={0}; //评分static int Sum=0,Renum=0;int main(){int Default[15][15]={ 0,1,1,1,1,1,1,1,1,1,1,1,1,1,2, //空棋盘3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,3,4,4,4,4,4,4,4,4,4,4,4,4,4,5,6,7,7,7,7,7,7,7,7,7,7,7,7,7,8 };int value[15][15]={0};FiveChess Start;do{Start.StartGame(value,Default); //开始游戏}while (Start.Continue); //若是要退出就修改这个值return 0;}//------------------------------开始游戏------------------------------------------// void FiveChess::StartGame(int value[][15],int Default[][15]){Empty(value,Default); //初始化棋盘adExWhile=true;while(ExWhile){Choice=MainMenu(); //调用主菜单,并把用户选择的值储存在Choice里switch(Choice){case 1:flag=1;ExWhile=false;break; //把标志设置为1,与AI对战case 2:flag=2;ExWhile=false;break; //把标志设置为2,双人对战case 3:Select=Introduce();ExWhile=Select;Continue=false;break; //游戏说明函数case 4:Select=Coder();ExWhile=Select;Continue=false;break; //作者介绍函数case 5:Exit();ExWhile=false;Continue=false;break; //退出游戏函数default:cin.fail();cin.clear();cin.sync();cout<<"输出错误,请重新输入!\n";system("pause>nul 2>nul");ExWhile=true;break; //其它}}if (flag==1) //如果标志等于1,说明为单人游戏{Single(value);}else if (flag==2) //如果标志等于2,说明为双人游戏{Double(value);}flag=0;}//------------------------清空棋盘或初始化棋盘-----------------------------------// void FiveChess::Empty(int value[][15],int Default[][15]) //清空棋盘{for (int i=0;i<15;i++){for (int j=0;j<15;j++){value[i][j]=Default[i][j];}}}void FiveChess::Exit() //退出游戏{system("cls");cout<<"┌—————————————————————————┐\n";cout<<"│感谢您使用:简单五子棋 Ver2.1 │\n";cout<<"││\n";cout<<"│[游戏制作]:落叶化尘│\n";cout<<"│[联系Q Q ]: 775904764 │\n";cout<<"│[联系邮箱]:***************│\n";cout<<"│[简单说明]:游戏结束界面,谢谢您的使用!│\n";cout<<"└—————————————————————————┘\n";cout<<"感谢您的使用,谢谢!按任意键退出游戏...\n";system("pause>nul 2>nul");}bool FiveChess::Introduce() //游戏介绍{system("cls");cout<<"┌—————————————————————————┐\n";cout<<"│简单五子棋 Ver2.1[游戏介绍界面] │\n";cout<<"││\n";cout<<"│[单人游戏]:玩家和AI(人工智能)对战,AI智商不高。
│\n";cout<<"││\n";cout<<"│[双人游戏]: 可以两个玩家一起对战,可能不是很方便。
│\n";cout<<"││\n";cout<<"│[游戏方法]:输入X Y坐标落子,输入双-1悔棋。
│\n";cout<<"││\n";cout<<"│[特别提示]:若游戏中想突然退出,按Ctrl+C即可中断。
│\n";cout<<"││\n";cout<<"└—————————————————————————┘\n";cout<<"是否返回?[Y-返回 N-退出]:";char choice;cin>>choice;if (choice=='N'||choice=='n'){cout<<"感谢您的使用,谢谢!按任意键退出游戏...\n";system("pause>nul 2>nul");return false;}else{return true;}}bool FiveChess::Coder() //作者介绍{system("cls");cout<<"┌—————————————————————————┐\n";cout<<"│简单五子棋 Ver2.1[作者介绍界面] │\n";cout<<"││\n";cout<<"│[游戏制作]:落叶化尘│\n";cout<<"│[联系Q Q ]: 775904764 │\n";cout<<"│[联系邮箱]:***************│\n";cout<<"│[简单介绍]:游戏制作简陋,还请见谅^_^!│\n"; cout<<"│[附加说明]:作者正在努力学习C++中,嘿嘿~ │\n";cout<<"└—————————————————————————┘\n";cout<<"是否返回?[Y-返回 N-退出]:";char choice;cin>>choice;if (choice=='N'||choice=='n'){cout<<"感谢您的使用,谢谢!按任意键退出游戏...\n";system("pause>nul 2>nul");return false;}else{return true;}}//-------------------------------选择主菜单-----------------------------//int FiveChess::MainMenu(){system("cls"); //清屏system("title 五子棋游戏 By--落叶化尘 QQ:775904764"); //修改窗口标题system("color 3f"); //定义窗口颜色system ("mode con cols=56 lines=20"); //设置窗口大小cout<<"┌—————————————————————————┐\n";cout<<"│简单五子棋 Ver2.1 │\n";cout<<"│[1]、单人游戏│\n";cout<<"││\n";cout<<"│[2]、双人游戏│\n";cout<<"││\n";cout<<"│[3]、游戏介绍│\n";cout<<"││\n";cout<<"│[4]、关于作者│\n";cout<<"││\n";cout<<"│[5]、退出│\n";cout<<"└—————————————————————————┘\n";cout<<"请选择:";int select;cin>>select;return select; //返回用户选择的值}//--------------------------------胜利界面--------------------------------// void FiveChess::Victory(int Num){system ("mode con cols=56 lines=20"); //设置窗口大小system("cls");if (Num==1){system("color 1f");cout<<"┌—————————————————————————┐\n";cout<<"│恭喜玩家1[黑棋]获得胜利!│\n";cout<<"││\n";cout<<"│[胜利玩家]:玩家1 │\n";cout<<"│[所属棋子]: 黑色│\n";cout<<"│[祝福话语]:不错哦^_^!恭喜您获得了胜利!│\n";cout<<"││\n";cout<<"└—————————————————————————┘\n"; }else if (Num==2){system("color 2f");cout<<"┌—————————————————————————┐\n";cout<<"│恭喜玩家2[白棋]获得胜利!│\n";cout<<"││\n";cout<<"│[胜利玩家]:玩家2 │\n";cout<<"│[所属棋子]: 白色│\n";cout<<"│[祝福话语]:恭喜您获得了胜利,再接再厉哈^_^!│\n";cout<<"││\n";cout<<"└—————————————————————————┘\n"; }else if(Num==3){system("color 3f");cout<<"┌—————————————————————————┐\n";cout<<"│恭喜您,获得了胜利│\n";cout<<"││\n";cout<<"│[胜利玩家]:自己│\n";cout<<"│[所属棋子]: 黑色│\n";cout<<"│[祝福话语]:不错哦,打败了AI,恭喜!│\n";cout<<"││\n";cout<<"└—————————————————————————┘\n"; }else if(Num==4){system("color 5f");cout<<"┌—————————————————————————┐\n";cout<<"│非常遗憾,您输了! │\n";cout<<"││\n";cout<<"│[胜利玩家]:AI(电脑)│\n";cout<<"│[所属棋子]: 白色│\n";cout<<"│[祝福话语]:加油吧,下次一定要把AI打败哦! │\n";cout<<"││\n";cout<<"└—————————————————————————┘\n"; }else{system("color 5f");cout<<"┌—————————————————————————┐\n";cout<<"│势均力敌——平局│\n";cout<<"││\n";cout<<"│[胜利玩家]:无[平局] │\n";cout<<"│[所属棋子]: 黑色或白色│\n";cout<<"│[祝福话语]:棋盘居然被走满了,不错不错~!│\n";cout<<"││\n";cout<<"└—————————————————————————┘\n";}cout<<"是否返回主界面?[Y-返回 N-退出]:";char choice;cin>>choice;if (choice=='N'||choice=='n'){cout<<"感谢您的使用,谢谢!按任意键退出游戏...\n";system("pause>nul 2>nul");Continue=false;}else{Continue=true;}}//----------------------------悔棋-------------------------------//void FiveChess::Retract(int &x1,int &y1,int &x2,int &y2,int value[][15]) {if (Sum>=1){Sum--;}if ((x1==-1)&&(y1==-1)&&(x2==-1)&&(y2==-1)){cout<<"当前无法悔棋,棋盘上没有棋子!";system("pause>nul");}else if (Renum>=6){cout<<"悔棋超过6次,为了公平,您不能再次悔棋!";system("pause>nul");}else{Renum++;if (x1==0&&y1==0){value[x1][y1]=0;Record[x1][y1]=0;}else if (x1==0&&y1==14){value[x1][y1]=2;Record[x1][y1]=0;}else if (x1==14&&y1==0){value[x1][y1]=6;Record[x1][y1]=0;}else if (x1==14&&y1==14){value[x1][y1]=8;Record[x1][y1]=0;}else if (x1==14&&(y1>0&&y1<14)){value[x1][y1]=7;Record[x1][y1]=0;}else if (y1==14&&(x1>0&&x1<14)){value[x1][y1]=5;Record[x1][y1]=0;}else if (x1==0&&(y1>0&&y1<14)){value[x1][y1]=1;Record[x1][y1]=0;}else if (y1==0&&(x1>0&&x1<14)){value[x1][y1]=3;Record[x1][y1]=0;}else {value[x1][y1]=4;Record[x1][y1]=0;}if (x2==0&&y2==0){value[x2][y2]=0;Record[x2][y2]=0;}else if (x2==0&&y2==14){value[x2][y2]=2;Record[x2][y2]=0;}else if (x2==14&&y2==0){value[x2][y2]=6;Record[x2][y2]=0;}else if (x2==14&&y2==14){value[x2][y2]=8;Record[x2][y2]=0;}else if (x2==14&&(y2>0&&y2<14)){value[x2][y2]=7;Record[x2][y2]=0;}else if (y2==14&&(x2>0&&x2<14)){value[x1][y2]=5;Record[x2][y2]=0;}else if (x2==0&&(y2>0&&y2<14)){value[x2][y2]=1;Record[x2][y2]=0;}else if (y2==0&&(x2>0&&x2<14)){value[x2][y2]=3;Record[x2][y2]=0;}else {value[x2][y2]=4;Record[x2][y2]=0;}cout<<"每盘最多允许悔棋6次,且最多只能回到上一步!";system("pause>nul");}}//-----------------------------判断用户输入的坐标合法性-------------------------// int FiveChess::Position(int *x,int *y,int value[][15]){if (cin.fail()||*x<0||*x>=15||*y<0||*y>=15){cin.clear();cin.sync();return 1; //返回1表示不在范围内或者输入的不是数字}else if (value[*x][*y]==9||value[*x][*y]==10){return 2; //存在棋子}else{return 0; //返回 0 表示坐标正常}}//---------------------------判断该哪个玩家先走----------------------------//int FiveChess::NextPlayer(int value[][15]){int i,j;int player1=0,player2=0;for (i=0;i<15;i++){for (j=0;j<15;j++){if (value[i][j]==10){player1++; //统计棋盘上面黑子的个数}else if (value[i][j]==9){player2++; //统计棋盘上白子的个数}}}if (player1>player2||player1<player2){return 2; //该玩家2走了(白子)}else{return 1; //该玩家1走了(黑子)}}//---------------------------判断棋子落在这点,是否胜利或者平局-----------------------------------------//int FiveChess::Win(int *x,int *y,int ChessNum,int value[][15]){int i,j,k; //返回-1:平局返回0:没有谁胜利返回1:传递过来ChessNum号的那一方胜利int number=0;Sumchess=0;for (i=-1;i<=1;i++){for (j=-1;j<=1;j++) //循环8次,分别计算这个点的8个方向是否构成5连{if (i!=0 || j!=0) //i或者j等于0,不就代表的是ChessNum的值嘛{for (k=1;k<5;k++) //循环4次{ //这是不越界判断//存在棋子数目+1if(*x+k*i>=0 &&*x+k*i<=14 && *y+k*j>=0 &&*y+k*j<=14 &&value[*x+k*i][*y+k*j]==ChessNum){number++;} //如果这个点有棋子else {break;} //没有棋子就跳出}for (k=-1;k>-5;k--) //与上面相对的方向的判断{if(*x+k*i>=0 &&*x+k*i<=14 && *y+k*j>=0 &&*y+k*j<=14 && value[*x+k*i][*y+k*j]==ChessNum){number++;}else {break;} //没有棋子就跳出}if(number>=4) //如果>=4就说明5连了,返回ChessNum表示传递过来的这个玩家得下子点能构成5个,胜利了{return 1;}else{number=0; //清空统计}}}}for (i=0;i<15;i++) //棋盘是否满了{for(j=0;j<15;j++){if (value[i][j]==9||value[i][j]==10){Sumchess++; //统计黑子和白子的总个数}}}if (Sumchess>=225){return -1; //棋盘满了}else{return 0; //没胜利也没和棋}}//---------------------------------绘制棋盘、落子函数-----------------------------------------//void FiveChess::PrintBord(int *x,int *y,int value[][15],int player){system("cls");int i,j;if (player==1){value[*x][*y]=9; //黑棋}else if (player==2){value[*x][*y]=10; //白棋}cout<<" 0 1 2 3 4 5 6 7 8 9 10 1 2 3 4\n"; //输出参考坐标for (i=0;i<15;i++){if(i!=0){cout<<" "<<i%10;}else{cout<<" 0";}for (j=0;j<15;j++){cout<<ch[value[i][j]];}cout<<"\n";}}//------------------------------------双人对战-----------------------------// void FiveChess::Double(int value[][15]){cout<<"您选择了双人对战模式,请按任意键继续!";system("pause>nul 2>nul");system("cls");system ("mode con cols=43 lines=20");system("color 3f");system("title 五子棋-双人对战模式");PrintBord(&x,&y,value,-1); //先绘制个空棋盘ExWhile=true; //退出循环用的memset(Record,0,sizeof(Record)); //先把记录落子的数组清0while(ExWhile){int play=NextPlayer(value); //先得到该哪个玩家走棋了cout<<"请(玩家"<<play<<")输入坐标[用空格隔开]:";cin>>x>>y;Check=Position(&x,&y,value); //检测坐标合法性if (Check==0) //坐标没问题{PrintBord(&x,&y,value,play); //再绘制落子棋盘Record[x][y]=play; //记录这个点,1表示黑子,2表示白子cout<<"玩家["<<play<<"]的棋子落在了:[X:"<<x<<"] [Y:"<<y<<"]\n";Check1=Win(&x,&y,play,Record); //检测是否有一方胜利或者和棋if (Check1==-1) //和棋{cout<<"游戏棋盘满啦,还没分出胜负,都很厉害哈!\n";cout<<"本次游戏结束,按任意键继续...";system("pause>nul 2>nul");Victory(5); //跳转胜利界面ExWhile=false;}else if(Check1==1) //当前玩家paly胜利{cout<<"恭喜[玩家"<<play<<"]获得胜利!\n";cout<<"本次游戏结束,按任意键继续...";system("pause>nul 2>nul");Victory(play); //跳转胜利界面ExWhile=false;}else //没谁胜利{ExWhile=true; //不退出循环}}else if(Check==1){cout<<"输入范围错误,请重新输入!\n";ExWhile=true;}else{cout<<"您输入的坐标已经存在棋子,请重新输入!\n";ExWhile=true;}}}//-------------------------------与AI对战------------------------------//void FiveChess::Single(int value[][15]){cout<<"您选择了与AI对战的模式,请按任意键继续!";system("pause>nul 2>nul");system("cls");system ("mode con cols=43 lines=20");system("color 3f");system("title 五子棋-与AI的对战模式");PrintBord(&x,&y,value,-1); //先绘制个空棋盘ExWhile=true; //退出循环用的Sum=0,Renum=0;memset(Record,0,sizeof(Record)); //先把记录落子的数组清0int x1=-1,y1=-1,x2=-1,y2=-1;while(ExWhile){ExWhile1=true;cout<<"请[玩家]输入坐标[双(-1)为悔棋]:";cin>>x>>y;Check=Position(&x,&y,value);if ((x==-1)&&(y==-1)) //悔棋{Retract(x1,y1,x2,y2,value);PrintBord(&x,&y,value,-1); //绘制落子棋盘ExWhile=true;}else if (Check==0) //坐标没问题{value[x][y]=9;Record[x][y]=1; //记录这个点,1表示黑子,2表示白子x1=x;y1=y; //记录当前坐标悔棋用Sum++;if (Win(&x,&y,1,Record)==0){Robot(&x,&y,&Sum,value); //调用AI函数PrintBord(&x,&y,value,2); //绘制落子棋盘x2=x;y2=y; //记录当前坐标悔棋用cout<<"玩家棋子数:"<<Sum<<" 电脑的棋子落在了[X:"<<x<<"] [Y:"<<y<<"]\n";//cout<<"玩家坐标:"<<x1<<" "<<y1<<"电脑坐标:"<<x2<<" "<<y2<<endl;if (Win(&x,&y,2,Record)==1){cout<<"非常遗憾,您输了,AI获得了胜利!\n";cout<<"本次游戏结束,按任意键继续...";system("pause>nul 2>nul");Victory(4); //跳转胜利界面ExWhile=false;}else if(Win(&x,&y,2,Record)==-1){cout<<"游戏棋盘满啦,还没分出胜负,都很厉害哈!\n";cout<<"本次游戏结束,按任意键继续...";system("pause>nul 2>nul");Victory(5); //跳转平局界面ExWhile=false;}else {ExWhile=true;}}else if(Win(&x,&y,1,Record)==1){PrintBord(&x,&y,value,-1); //绘制棋盘cout<<"恭喜[玩家]获得胜利!\n";cout<<"本次游戏结束,按任意键继续...";system("pause>nul 2>nul");Victory(3); //跳转胜利界面ExWhile=false;}else if(Win(&x,&y,1,Record)==-1){PrintBord(&x,&y,value,-1); //绘制棋盘cout<<"游戏棋盘满啦,还没分出胜负,都很厉害哈!\n";cout<<"本次游戏结束,按任意键继续...";system("pause>nul 2>nul");Victory(5); //跳转平局界面ExWhile=false;}}else if(Check==1){cout<<"输入范围错误,请重新输入!\n";}else{cout<<"您输入的坐标已经存在棋子,请重新输入!\n";}}}//-----------------------------电脑落子函数-------------------------------// void FiveChess::Robot(int *x,int *y,int *Sum,int value[][15]){ExWhile1=true;if (*Sum==1){while(ExWhile1){ChessOne(*x,*y,value);if (Position(x,y,value)==0){ExWhile1=false;}}Record[*x][*y]=2; //记录这个点}else //从第2步开始,使用评分系统{Findscore(*x,*y);}}//-----------------------------查找评分最高的坐标-------------------------// void FiveChess::Findscore(int &x,int &y){srand( (unsigned)time( NULL ) );int i,j,x1,x2,y1,y2,lx;int Max=0;ChessScore(); //调用评分函数for (i=0;i<15;i++){for (j=0;j<15;j++){if(Score[i][j]>Max){Max=Score[i][j]; //获取所有点中,评分最高的x1=i;y1=j;}}}x2=x1;y2=y1;for (i=0;i<15;i++) //可能的话,有评分相同的多个点{for (j=0;j<15;j++){if(Score[i][j]==Max&&i!=x2&&j!=y2) //在这么多个相同分数的点中,随机找一个{lx=rand()%10;if (lx<5){x2=i,y2=j;break;}}}}if (x2!=x1 || y2!=y1) //棋盘上有2个最高分{lx=rand()%10; //随机一个^_^if (lx>6){x=x1,y=y1;}else{x=x2,y=y2;}}else //棋盘上只有一个最高分{x=x1,y=y1;}Max=0; //清空最大值Record[x][y]=2; //记录这个点}//------------------------------玩家走第1步时的落子-------------------------------// inline void FiveChess::ChessOne(int &x,int &y,int value[][15]){int i,j;srand( (unsigned)time( NULL ) ); //随机数随着时间的改变而改变for (i=0;i<15;i++){for(j=0;j<15;j++){if (value[i][j]==9) //如果找到了玩家的棋子,在它的8个方的任意一点落子{int lx=rand()%7;if(lx==0){x=i+1;y=j+1;if (Position(&x,&y,value)==0){break;}}else if(lx==1){x=i+1;y=j-1;if (Position(&x,&y,value)==0){break;}}else if(lx==2){x=i-1;y=j-1;if (Position(&x,&y,value)==0){break;}}else if(lx==3){x=i-1;y=j+1;if (Position(&x,&y,value)==0){break;}}else if(lx==4){x=i-1;y=j; //上if (Position(&x,&y,value)==0){break;}}else if(lx==5){x=i;y=j-1; //左if (Position(&x,&y,value)==0){break;}}else if(lx==6){x=i;y=j+1; //右if (Position(&x,&y,value)==0){break;}}else{x=i+1;y=j; //下if (Position(&x,&y,value)==0){break;}}}}}}//-----------------------------------AI评分函数---------------------------------------//void FiveChess::ChessScore(){int x,y,i,j,k; //循环变量int number1=0,number2=0; //number用来统计玩家或电脑棋子连成个数int empty=0; //empty用来统计空点个数memset(Score,0,sizeof(Score)); //把评分数组先清零for(x=0;x<15;x++){for(y=0;y<15;y++){if(Record[x][y]==0) //如果这个点为空{for(i=-1;i<=1;i++){for(j=-1;j<=1;j++) //判断8个方向{if(i!=0 || j!=0) //若是都为0的话,那不就是原坐标嘛{//-------------------------------------对玩家落点评分---------------------------------------//for(k=1;i<=4;k++) //循环4次{ //这点没越界//且这点存在黑子(玩家)if(x+k*i>=0 && x+k*i<=14 && y+k*j>=0 && y+k*j<=14 && Record[x+k*i][y+k*j]==1 ){number1++;}else if(Record[x+k*i][y+k*j]==0){empty++;break;} //这点是个空点,+1后退出else {break;} //否则是墙或者对方的棋子了}for(k=-1;k>=-4;k--) //向它的相反方向判断{ //这点没越界 //且这点存在黑子(玩家)if(x+k*i>=0 && x+k*i<=14 && y+k*j>=0 && y+k*j<=14 && Record[x+k*i][y+k*j]==1 ){number1++;}else if(Record[x+k*i][y+k*j]==0){empty++;break;} //同上条else {break;}}if(number2==1) {Score[x][y]+=1;} //2个棋子else if(number1==2) //3个棋子{if(empty==1) {Score[x][y]+=5;} //有一个空点+5分 //死3else if(empty==2) {Score[x][y]+=10;} //有两个空点+10分 //活3}else if(number1==3) //4个棋子{if(empty==1) {Score[x][y]+=20;} //有一个空点+20分 //死4else if(empty==2) {Score[x][y]+=100;} //有2个空点+100分 //活4}else if(number1>=4) {Score[x][y]+=1000;} //对方有5个棋子,分数要高点,先堵empty=0; //统计空点个数的变量清零//---------------------------------------对电脑落点评分---------------------------------------//for(k=1;i<=4;k++) //循环4次{ //这点没越界 //且这点存在白子(电脑)if(x+k*i>=0 && x+k*i<=14 && y+k*j>=0 && y+k*j<=14 && Record[x+k*i][y+k*j]==2 ){number2++;}else if(Record[x+k*i][y+k*j]==0){empty++;break;} //空点else {break;}}for(k=-1;k>=-4;k--) //向它的相反方向判断{if(x+k*i>=0 && x+k*i<=14 && y+k*j>=0 && y+k*j<=14 && Record[x+k*i][y+k*j]==2 ){number2++;}else if(Record[x+k*i][y+k*j]==0){empty++;break;}else {break;} //这里顶上判断玩家的都做解释了,不再介绍}if (number2==0) {Score[x][y]+=1;} //1个棋子else if(number2==1) {Score[x][y]+=2;} //2个棋子else if(number2==2) //3个棋子{if(empty==1) {Score[x][y]+=8;} //死3else if(empty==2) {Score[x][y]+=30;} //活3}else if(number2==3) //4个棋子{if(empty==1) {Score[x][y]+=50;} //死4else if(empty==2) {Score[x][y]+=200;} //活4}else if(number2>=4) {Score[x][y]+=10000;} //自己落在这点能形成5个,也就能胜利了,分数最高number1=0;number2=0; //清零,以便下次重新统计empty=0;}}}}}}}下载后,文件内容如下:这个游戏用到了C++基本的语法知识,包括:类class、指针、循环语句、引用、多维数组。