C语言 棋盘游戏 源代码
- 格式:doc
- 大小:20.00 KB
- 文档页数:3
C语言棋盘游戏源代码#include <stdio. h>#include <stdlib・h>char matrix[3j [3] ;/*定义游戏棋盘 */char check(void);void init_matrix(void): void get_player_move(void) : void get_computer_move(void); void disp_matrix(void);int main(){char done;printf (,z This is the game of Tic Tac Toe・ \n");printf (,z You will be playing against the computer・ \n");done 二'';init_matrix();do {disp_matrix();get_player_move ();done = check () ;/*检测输赢*/if(done!= ' ')break;/*赢了*/get_computer_move ();done = check () ;/*检测输赢 */}while (done ='');if(done==,X’) printf("You won!\n");else printf (^Computer won!\n,?);disp_matrix() ;/*显示棋了的位彗*/return 0;}/*初始化棋盘*/void init_matrix(void) {int i, j;for(i=0;i<3;i++)for (j=0;j<3;j++)matrixLiZ[j] = ' ; }/*下棋者下*/void get_player_move(void) {int x, y;printf("Enter coordinates for your X:"); scanf (//%d%d,,> &x, &y);x—; y—;if(matrix[xj[y] != '){printf (''Invalid move, try again. \n"); get_player_move();}else matrix[x][y]二'X' ; }/*计算机下*/void get_computer_move(void) {int i, j;for(i=0;i<3;i++){for (j=0;j〈3;j++)if(matrixEiZ[j]== ' *)break;if(matrixEiZ[j]== ' *)break; }if(i*j=9){printf (,/draw\n,/);exit(O);}elsematrixTiZ [j]二'O';}/ *在屏幕上显示棋盘* /void disp_matrix(void){int t;for(t=0;t<3;t++){printf("%c|%c 丨%c", matrix[t][0], matrix[tJ[1], matrix[t][2]); if (t !=2) printf ("\nT - | -\n");}printf("\n");}/*看谁是赢着*/char check(void)int i;/*检查横行*/for(i=0;i<3;i++)if (matrixliZ lOZ—matrix[iZ L12&&matrix[i_ _O_==matrixLi_[2])return matrix[i_ _0_;/*检查竖行*/for(i=0;i<3;i++)if (matrixLOZ lil==matrix[lZmatrix[0_ _i_—matrix[2] .i])return matrix[0_ _i];/*检查对角线*/if (matrixlOZ ZOZ~matrix[lZ [lZ&&matrix[lZ [1^—matrix[2] [2])return matrix[0_ _0];if (matrix[OJ [2]~matrix[lZ [lZ&&matrix[lL [1]二二matrix[2] [0])return matrix[0_[2];return '';}许多MM在减肥的过程中困难重重,用尽方法却瘦不下来,其实只有在数不清的技巧,推敲中找到属于跟适合自己的最佳方式,才能在健康的瘦身道路上走下去,下面一些瘦身的小技巧,一定可以帮到你,1、慢慢吃我们都曾在美味佳肴面前狼呑虎咽。
C语言华容道代码华容道是一个经典的逻辑游戏,其中包含一个11x11 的棋盘和15个大小不一的棋子。
游戏的目标是将红色棋子移到最下方的任意空位。
以下是一个简单的华容道游戏的C语言实现:注意:这只是一个非常基本的版本,不包括游戏图形界面或错误处理等高级特性。
c#include <stdio.h>#include <stdlib.h>#define SIZE 15typedef struct {int data[SIZE][SIZE];} board;board boardInit() {board b;for(int i=0; i<SIZE; i++) {for(int j=0; j<SIZE; j++) {b.data[i][j] = 0;}}return b;}void printBoard(board b) {for(int i=0; i<SIZE; i++) {for(int j=0; j<SIZE; j++) {printf("%d ", b.data[i][j]);}printf("\n");}}void moveUp(board *b, int x, int y) {if(x > 0 && b->data[x-1][y] == 0) {int temp = b->data[x][y];b->data[x][y] = b->data[x-1][y];b->data[x-1][y] = temp;}}void moveDown(board *b, int x, int y) {if(x < SIZE-1 && b->data[x+1][y] == 0) {int temp = b->data[x][y];b->data[x][y] = b->data[x+1][y];b->data[x+1][y] = temp;}}void moveLeft(board *b, int x, int y) {if(y > 0 && b->data[x][y-1] == 0) {int temp = b->data[x][y];b->data[x][y] = b->data[x][y-1];b->data[x][y-1] = temp;}}void moveRight(board *b, int x, int y) {if(y < SIZE-1 && b->data[x][y+1] == 0) {int temp = b->data[x][y];b->data[x][y] = b->data[x][y+1];b->data[x][y+1] = temp;}}void solve(board *b) {int visited[SIZE][SIZE];for(int i=0; i<SIZE; i++) {for(int j=0; j<SIZE; j++) {visited[i][j] = 0;}}for(int i=0; i<SIZE; i++) {for(int j=0; j<SIZE; j++) {if(b->data[i][j] == 1 && visited[i][j] == 0) { // Start from the top-left corner (red piece)visited[i][j] = 1; // Mark the current position as visited (to avoid infinite loops)if(i > 0) moveUp(b, i, j); // Move up if possible (top empty) and mark it as visited (to avoid infinite loops)if(j > 0) moveLeft(b, i, j); // Move left if possible (left empty) and mark it as visited (to avoid infinite loops)}}}} // The solution should be at the bottom of the board now (in any empty slot)。
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语言代码#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语言教程:简易五子棋程序收集于网络/* 纯用字符和数组编的五子棋,棋盘也是用字符画的。
、编了1上午了,主要是算法跟按键比较烦,发现有bug-- 按键速度过快会产生延时显示,可能是算法不好。
操作:玩家1:a,s,w,d(方向)空格(落子)玩家2:上、下、左、右回车(落子)ESC:退出编译测试环境:`*/#include <>#include <>#include <>#include <>/#define CRRU 0xbf /*右上角点197*/#define CRLU 0xda /*左上角点218*/#define CRLD 0xc0 /*左下角点192*/#define CRRD 0xd9 /*右下角点217*/<#define CRL 0xc3 /*左边195*/#define CRR 0xb4 /*右边190*/#define CRU 0xc2 /*上边194*/#define CRD 0xc1 /*下边193*/#define CR 0xc5 /*十字交叉点197*/-#define size 19char a[size][size];int i,j; int x=10;int y=3; return ;}void pressct(int m){switch(m){¥case 19200: //左if(i>0) {i--;x--;gotoxy(x,y);} break;case 20480: //下if(j<size-1){j++;y++;gotoxy(x,y);} break;case 18432: //上$if(j>0) {j--;y--;gotoxy(x,y);} break;case 19712: //右if(i<size-1){i++;x++;gotoxy(x,y);} break;case 7181: //回车if(a[i][j]!=CB&&a[i][j]!=CW){a[i][j]=CW;putch(CW);gotoxy(x,y);side=1;}break; {default: break;}return ;}>int judge(int pa) //判断是否胜利,胜利则返回1,否则返回0;// 其中i,j为当前的落子位;{int m;int sum=1;for(m=1;m<=i&&m<=j;m++) {if(a[i-m][j-m]!=pa) break;sum++;}for(m=1;m<(size-i)&&m<(size-j);m++) {if(a[i+m][j+m]!=pa) break;sum++;}if(sum>=5) return 1;else sum=1;for(m=1;m<=i;m++) {if(a[i-m][j]!=pa) break;sum++;}for(m=1;m<(size-j);m++) {if(a[i+m][j]!=pa) break;sum++;}if(sum>=5) return 1;else sum=1;for(m=1;m<=j;m++) {if(a[i][j-m]!=pa) break;sum++;}for(m=1;m<(size-j);m++) {if(a[i][j+m]!=pa) break;sum++;}if(sum>=5) return 1;else sum=1;for(m=1;m<=i&&m<(size-j);m++) {if(a[i-m][j+m]!=pa) break;sum++;}for(m=1;m<(size-i)&&m<=j;m++) {if(a[i+m][j-m]!=pa) break;sum++;}if(sum>=5) return 1;else return 0;本文章来自21视频教程网C语言教程:简易五子棋程序_C语言程序设计教程原文链接:。
using System;using;namespace wuziqi{class Program{public static void Main(string[] args){int maxsize = 19;//棋盘行列最大值int x, y;//用于定位下棋位置string x1, y1;//临时变量获取棋手输入的坐标值(此刻座标值属于字符串类型)int col_up = 0, col_down = 0;//用于统计输入座标值的上下相同棋子的个数int row_left = 0, row_right = 0;//用于统计输入座标值的左右相同棋子的个数int dia_left_up = 0, dia_left_down = 0, dia_right_up = 0, dia_right_down = 0;//对角线的英文拼写(diagonal line)用于统计对角线上相同的棋子数量int m;//临时变量,用于操纵判定相同棋子比较的次数int judgement;//用于获取判定是不是要终止棋局或继续棋局的变量string[,] qipan = new string[24, 24];//概念二维棋盘//初始化棋盘label0:{();//五子棋规那么("===============================================");("五子棋规那么说明如下:");("1、下棋坐标是从1-15");("2、下棋坐标值为整型数据类型");("3、下棋两边先组成五子连线者胜");("===============================================");for (int i = 5; i <= maxsize; i++){for (int j = 5; j <= maxsize; j++){qipan[i, j] = "╋";}}}//输出棋盘for (int i = 5; i <= maxsize; i++){for (int j = 5; j <= maxsize; j++){(qipan[i, j]);}("\n");}//走棋label2:{//甲方走棋("===============================================");("请甲方走棋(棋盘为15x15)");("x=");x1 = ();//判定输入的坐标值是不是为字母foreach(char ch in x1){if ((ch >'a'&&ch <'z')||(ch >'A'&&ch <'Z')){("你输入的坐标值非法!请正确输入你的坐标值");goto label2;}}//判定输入的棋子坐标是不是为空if (x1 == "" || x1 == null){("===============================================");("你输入的棋盘坐标为空!");goto label2;}("y=");y1 = ();//判定输入的坐标值是不是为字母foreach (char ch in y1){if ((ch > 'a' && ch < 'z') || (ch > 'A' && ch < 'Z')){("你输入的坐标值非法!请正确输入你的坐标值");goto label2;}}//判定输入的棋子坐标是不是为空if (y1 == "" || y1 == null){("===============================================");("你输入的棋盘坐标为空!");goto label2;}x = (x1);y = (y1);if (x >= 16 || y >= 16){("===============================================");("你输入的坐标超出了范围!");goto label2;}if (qipan[x + 4, y + 4] == "╋"){qipan[x + 4, y + 4] = "●";//清屏();//输出棋走后棋盘//五子棋规那么("===============================================");("五子棋规那么说明如下:");("1、下棋坐标是从1-15");("2、下棋坐标值为整型数据类型");("3、下棋两边先组成五子连线者胜");("===============================================");for (int i = 5; i <= maxsize; i++){for (int j = 5; j <= maxsize; j++){(qipan[i, j]);}("\n");}}else{("===============================================");("此处已经有棋子了");goto label2;}// goto label;//判定是不是能够连成五子//判定上下col_down = 0;col_up = 0;row_left = 0;row_right = 0;dia_left_down = 0;dia_left_up = 0;dia_right_down = 0;dia_right_up = 0;for (m = 1; m <= 4; m++){//判定上下if (qipan[x + 4, y + 4] == qipan[x - m + 4, y + 4] && qipan[x - m + 4, y + 4] != "○" && qipan[x - m + 4, y + 4] != "╋"){col_up++;}if (qipan[x + 4, y + 4] == qipan[x + m + 4, y + 4] && qipan[x - m + 4, y + 4] != "○" && qipan[x - m + 4, y + 4] != "╋"){col_down++;}//判定左右if (qipan[x + 4, y + 4] == qipan[x + 4, y - m + 4] && qipan[x - m + 4, y + 4] != "○" && qipan[x - m + 4, y + 4] != "╋"){row_left++;}if (qipan[x + 4, y + 4] == qipan[x + 4, y + m + 4] && qipan[x - m + 4, y + 4] != "○" && qipan[x - m + 4, y + 4] != "╋"){row_right++;}//判定左对角线if (qipan[x + 4, y + 4] == qipan[x - m + 4, y - m + 4] && qipan[x - m + 4, y + 4] != "○" && qipan[x - m + 4, y + 4] != "╋"){dia_left_up++;}if (qipan[x + 4, y + 4] == qipan[x + m + 4, y + m + 4] && qipan[x - m + 4, y + 4] != "○" && qipan[x - m + 4, y + 4] != "╋"){dia_left_down++;}//判定右对角线if (qipan[x + 4, y + 4] == qipan[x - m + 4, y + m + 4] && qipan[x - m + 4, y + 4] != "○" && qipan[x - m + 4, y + 4] != "╋"){dia_right_up++;}if (qipan[x + 4, y + 4] == qipan[x + m + 4, y - m + 4] && qipan[x - m + 4, y + 4] != "○" && qipan[x - m + 4, y + 4] != "╋"){dia_right_down++;}}//判定甲方是不是有组成五子if(dia_left_down == 4 || dia_left_up == 4 || col_up == 4 || col_down == 4 || row_right == 4 || row_left == 4 || dia_right_up == 4 || dia_right_down == 4){("甲方先组成五子连线,恭喜甲获胜!");("请选择:");("1、继续下一局");("2、终止棋局");judgement = ());switch (judgement){case 1: goto label0;default: goto label3;}}if (((col_down + col_up) == 4) || ((row_left + row_right == 4)) || (dia_left_down + dia_left_up == 4)|| (dia_right_down + dia_right_up == 4)){("甲方先组成五子连线,恭喜甲获胜!");("请选择:");("1、继续下一局");("2、终止棋局");judgement = ());switch (judgement){case 1: goto label0;default: goto label3;}}//乙方走棋label1:{("===============================================");("请已方走棋(棋盘为15x15)");//判定坐标值是不是为空("x=");x1 = ();//判定输入的坐标值是不是为字母foreach (char ch in x1){if ((ch > 'a' && ch < 'z') || (ch > 'A' && ch < 'Z')){("你输入的坐标值非法!请正确输入你的坐标值");goto label1;}}if (x1 == "" || x1 == null){("你输入的棋盘坐标值为空!");}x = (x1);("y=");y1 = ();//判定输入的坐标值是不是为字母foreach (char ch in y1){if ((ch > 'a' && ch < 'z') || (ch > 'A' && ch < 'Z')){("你输入的坐标值非法!请正确输入你的坐标值");goto label1;}}//判定是不是为空if (y1 == "" || y1 == null){("你输入的棋盘坐标值为空!");goto label1;}y = (y1);//对输入的棋子进行判定是不是合法if (x >= 16 || y >= 16){("你输入的坐标超出了范围!");goto label1;}if (qipan[x + 4, y + 4] == "╋"){qipan[x + 4, y + 4] = "○";//输出棋走后棋盘//清屏();("===============================================");("五子棋规那么说明如下:");("1、下棋坐标是从1-15");("2、下棋坐标值为整型数据类型");("3、下棋两边先组成五子连线者胜");("===============================================");for (int i = 5; i <= maxsize; i++){for (int j = 5; j <= maxsize; j++){(qipan[i, j]);}("\n");}}else{("此处已经有棋子了");goto label1;}//判定是不是能够连成五子col_down = 0;col_up = 0;row_left = 0;row_right = 0;dia_left_down = 0;dia_left_up = 0;dia_right_down = 0;dia_right_up = 0;for (m = 1; m <= 4; m++){//判定上下if (qipan[x + 4, y + 4] == qipan[x - m + 4, y + 4] && qipan[x - m + 4, y + 4] != "●" && qipan[x - m + 4, y + 4] != "╋"){col_up++;}if (qipan[x + 4, y + 4] == qipan[x + m + 4, y + 4] && qipan[x + m + 4, y + 4] != "●" && qipan[x + m + 4, y + 4] != "╋"){col_down++;}//判定左右if (qipan[x + 4, y + 4] == qipan[x + 4, y - m + 4] && qipan[x + 4, y - m + 4] != "●" && qipan[x + 4, y - m + 4] != "╋"){row_left++;}if (qipan[x + 4, y + 4] == qipan[x + 4, y + m + 4] && qipan[x + 4, y + m + 4] != "●" && qipan[x + 4, y + m + 4] != "╋"){row_right++;}//判定左对角线if (qipan[x + 4, y + 4] == qipan[x - m + 4, y - m + 4] && qipan[x - m + 4, y - m + 4] != "●" && qipan[x - m + 4, y - m + 4] != "╋"){dia_left_up++;}if (qipan[x + 4, y + 4] == qipan[x + m + 4, y + m + 4] && qipan[x + m + 4, y + m + 4] != "●" && qipan[x + m + 4, y + m + 4] != "╋"){dia_left_down++;}//判定右对角线if (qipan[x + 4, y + 4] == qipan[x - m + 4, y + m + 4] && qipan[x - m + 4, y + m + 4] != "●" && qipan[x - m + 4, y + m + 4] != "╋"){dia_right_up++;}if (qipan[x + 4, y + 4] == qipan[x + m + 4, y - m + 4] && qipan[x + m + 4, y - m + 4] != "●" && qipan[x + m + 4, y - m + 4] != "╋"){dia_right_down++;}}//判定甲方是不是有组成五子if (dia_left_down == 4 || dia_left_up == 4 || col_up == 4 || col_down == 4 || row_right == 4 || row_left == 4 || dia_right_up == 4 || dia_right_down == 4){("===============================================");("乙方先组成五子连线,恭喜乙获胜!");("请选择:");("1、继续下一局");("2、终止棋局");judgement = ());switch (judgement){case 1: goto label0;default: goto label3;}}if (((col_down + col_up) == 4) || ((row_left + row_right == 4)) || (dia_left_down + dia_left_up == 4) || (dia_right_down + dia_right_up == 4)){("===============================================");("乙方先组成五子连线,恭喜乙获胜!");("请选择:");("1、继续下一局");("2、终止棋局");judgement = ());switch (judgement){case 1: goto label0;default: goto label3;}}goto label2;}}//用于终止棋局label3:{}}}}。
#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;}。
五子棋#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 KEYINV ALID 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 ");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 KEYINV ALID: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 KEYINV ALID;/*按键无效*/}贪吃蛇#define N 200#include <graphics.h>#include <stdlib.h>#include <dos.h>#define LEFT 0x4b00#define RIGHT 0x4d00#define DOWN 0x5000#define UP 0x4800#define ESC 0x011bint i,key;int score=0;/*得分*/int gamespeed=50000;/*游戏速度自己调整*/ struct Food{int x;/*食物的横坐标*/int y;/*食物的纵坐标*/int yes;/*判断是否要出现食物的变量*/ }food;/*食物的结构体*/struct Snake{int x[N];int y[N];int node;/*蛇的节数*/int direction;/*蛇移动方向*/int life;/* 蛇的生命,0活着,1死亡*/}snake;void Init(void);/*图形驱动*/void Close(void);/*图形结束*/void DrawK(void);/*开始画面*/void GameOver(void);/*结束游戏*/void GamePlay(void);/*玩游戏具体过程*/void PrScore(void);/*输出成绩*//*主函数*/void main(void){Init();/*图形驱动*/DrawK();/*开始画面*/GamePlay();/*玩游戏具体过程*/Close();/*图形结束*/}/*图形驱动*/void Init(void){int gd=DETECT,gm;initgraph(&gd,&gm,"c:\\tc");cleardevice();}/*开始画面,左上角坐标为(50,40),右下角坐标为(610,460)的围墙*/ void DrawK(void){/*setbkcolor(LIGHTGREEN);*/setcolor(11);setlinestyle(SOLID_LINE,0,THICK_WIDTH);/*设置线型*/for(i=50;i<=600;i+=10)/*画围墙*/{rectangle(i,40,i+10,49); /*上边*/rectangle(i,451,i+10,460);/*下边*/}for(i=40;i<=450;i+=10){rectangle(50,i,59,i+10); /*左边*/rectangle(601,i,610,i+10);/*右边*/}}/*玩游戏具体过程*/void GamePlay(void){randomize();/*随机数发生器*/food.yes=1;/*1表示需要出现新食物,0表示已经存在食物*/snake.life=0;/*活着*/snake.direction=1;/*方向往右*/snake.x[0]=100;snake.y[0]=100;/*蛇头*/snake.x[1]=110;snake.y[1]=100;snake.node=2;/*节数*/PrScore();/*输出得分*/while(1)/*可以重复玩游戏,压ESC键结束*/{while(!kbhit())/*在没有按键的情况下,蛇自己移动身体*/{if(food.yes==1)/*需要出现新食物*/{food.x=rand()%400+60;food.y=rand()%350+60;while(food.x%10!=0)/*食物随机出现后必须让食物能够在整格内,这样才可以让蛇吃到*/ food.x++;while(food.y%10!=0)food.y++;food.yes=0;/*画面上有食物了*/}if(food.yes==0)/*画面上有食物了就要显示*/{setcolor(GREEN);rectangle(food.x,food.y,food.x+10,food.y-10);}for(i=snake.node-1;i>0;i--)/*蛇的每个环节往前移动,也就是贪吃蛇的关键算法*/{snake.x[i]=snake.x[i-1];snake.y[i]=snake.y[i-1];}/*1,2,3,4表示右,左,上,下四个方向,通过这个判断来移动蛇头*/switch(snake.direction){case 1:snake.x[0]+=10;break;case 2: snake.x[0]-=10;break;case 3: snake.y[0]-=10;break;case 4: snake.y[0]+=10;break;}for(i=3;i<snake.node;i++)/*从蛇的第四节开始判断是否撞到自己了,因为蛇头为两节,第三节不可能拐过来*/{if(snake.x[i]==snake.x[0]&&snake.y[i]==snake.y[0]){GameOver();/*显示失败*/snake.life=1;break;}}if(snake.x[0]<55||snake.x[0]>595||snake.y[0]<55||snake.y[0]>455)/*蛇是否撞到墙壁*/{GameOver();/*本次游戏结束*/snake.life=1; /*蛇死*/}if(snake.life==1)/*以上两种判断以后,如果蛇死就跳出内循环,重新开始*/ break;if(snake.x[0]==food.x&&snake.y[0]==food.y)/*吃到食物以后*/{setcolor(0);/*把画面上的食物东西去掉*/rectangle(food.x,food.y,food.x+10,food.y-10);snake.x[snake.node]=-20;snake.y[snake.node]=-20;/*新的一节先放在看不见的位置,下次循环就取前一节的位置*/snake.node++;/*蛇的身体长一节*/food.yes=1;/*画面上需要出现新的食物*/score+=10;PrScore();/*输出新得分*/}setcolor(4);/*画出蛇*/for(i=0;i<snake.node;i++)rectangle(snake.x[i],snake.y[i],snake.x[i]+10,snake.y[i]-10);delay(gamespeed);setcolor(0);/*用黑色去除蛇的的最后一节*/rectangle(snake.x[snake.node-1],snake.y[snake.node-1],snake.x[snake.node-1]+10,snake.y[snake.node-1]-10);} /*endwhile(!kbhit)*/if(snake.life==1)/*如果蛇死就跳出循环*/break;key=bioskey(0);/*接收按键*/if(key==ESC)/*按ESC键退出*/break;elseif(key==UP&&snake.direction!=4)/*判断是否往相反的方向移动*/snake.direction=3;elseif(key==RIGHT&&snake.direction!=2)snake.direction=1;elseif(key==LEFT&&snake.direction!=1)snake.direction=2;elseif(key==DOWN&&snake.direction!=3)snake.direction=4;}/*endwhile(1)*/}/*游戏结束*/void GameOver(void){cleardevice();PrScore();setcolor(RED);settextstyle(0,0,4);outtextxy(200,200,"GAME OVER");getch();}/*输出成绩*/void PrScore(void){char str[10];setfillstyle(SOLID_FILL,YELLOW);bar(50,15,220,35);setcolor(6);settextstyle(0,0,2);sprintf(str,"score:%d",score);outtextxy(55,20,str);}/*图形结束*/void Close(void){getch();closegraph();}扫雷游戏/*模拟扫雷游戏*/#include <graphics.h>#include <math.h>#include <stdio.h>#include <dos.h>#include <stdlib.h>#include <conio.h>#include <alloc.h>union REGS regs;int size=15;/*用于表示每个方块的大小(正方形的边长)*/int pix,piy=50;/*pix,piy是矩阵的偏移量*/char b[2]="1";/*用于显示方格周围的雷的个数*/int pan[30][16];/*用于记录盘面的情况:0:没有、9:有雷、1~8:周围雷的个数*/int pan1[30][16];/*pan1[][]纪录当前的挖雷情况,0:没有操作、1:打开了、2:标记了*/int tt;/*纪录时间参数*/int Eflags;/*用于标记鼠标按钮的有效性,0:有效,1:无效,2:这是鼠标的任意键等于重新开始*/int Msinit();void Draw(int x,int y,int sizex,int sizey);void Facedraw(int x,int y,int sizel,int k);void Dead(int sizel,int x,int y);void Setmouse(int xmax,int ymax,int x,int y);int Msread(int *xp,int *yp,int *bup,struct time t1,int k);void Draw1(int x,int y);int Open(int x,int y);float Random();void Have(int sum,int x,int y,int xx,int yy);void Help();void Coread();void Ddraw2(int x,int y);/*下面是主函数*/main(){int mode=VGAHI,devices=VGA;/*图形模式初始化的变量*/char ams; /*鼠标操作中的标志变量*/int xms,yms,bms; /*鼠标的状态变量*/int i,j,k,k1=0; /*i,j,k是循环变量*/int x=9,y=9,flags=0; /*x,y矩阵的大小*/int sum=10; /*sum 盘面的雷的总数目,是个x,y的函数*/int x1=0,y1=0; /*用于记录光标当前的位置*/int x11=0,y11=0; /*暂时保存鼠标位置的值*/int sizel=10; /*脸的大小*/int cflags=1; /*这是菜单操作标志变量,没有弹出1,弹出0*/struct time t1={0,0,0,0}; /*时间结构体,头文件已定义*/int co[3]; /*暂时纪录历史纪录*/void far *Map; /*用于保存鼠标图片*/char name[3][20]; /*名字字符串,用于记录名字*/FILE * p; /*文件指针用于文件操作*/Msinit(); /*鼠标初始化*//*registerbgidriver(EGA VGA_driver);*/initgraph(&devices,&mode,"C:\\tc"); /*图形模式初始化*//*为图片指针分配内存*/if((Map=farmalloc(imagesize(0,0,20,20)))==NULL)/*图片的大小是20*20*/{printf("Memory ererr!\n");printf("Press any key to out!\n");exit(1);}/*用于检验文件是否完整*/while((p = fopen("score.dat", "r")) == NULL) /*如果不能打开就新建一个*/{if((p = fopen("score.dat", "w")) == NULL)/*如果不能新建就提示错误并推出*/{printf("The file cannot open!\n");printf("Presss any key to exit!\n");getch();exit(1);}/*写入初始内容*/fprintf(p,"%d %d %d,%s\n%s\n%s\n",999,999,999,"xiajia","xiajia","xiajia");fclose(p);}/*暂时读出历史纪录。
C++棋盘程序源代码1、画棋盘Ondraw函数int i,j;for(i=0;i<800;i+=50)for(j=0;j<800;j+=50){pDC->MoveTo(i,j);pDC->LineTo(i,j+50);}for(i=0;i<800;i+=50)for(j=0;j<800;j+=50){pDC->MoveTo(j,i);pDC->LineTo(j+50,i);}pDC->MoveTo(0,i);pDC->LineTo(j,i);pDC->MoveTo(j,0);pDC->LineTo(j,i);}2、插位图(棋盘背景)Insert-Resource:Bitmap “Import”(选“所有文件”)Ondraw函数:CWuziqiDoc* pDoc = GetDocument();ASSERT_V ALID(pDoc);// TODO: add draw code for native data hereCBitmap bmp;bmp.LoadBitmap(IDB_BITMAP3);int nBmpWidth, nBmpHeight;BITMAP bmInfo;bmp.GetBitmap(&bmInfo);nBmpWidth=bmInfo.bmWidth;nBmpHeight=bmInfo.bmHeight;//获取客户区域的大小CRect clientRC;GetClientRect(clientRC);CDC memDC;memDC.CreateCompatibleDC(pDC); //内存DCmemDC.SelectObject(&bmp);//在窗口绘图pDC->StretchBlt(0,0,clientRC.Width(),clientRC.Height(), &memDC, 0, 0, nBmpWidth, nBmpHeight, SRCCOPY);//释放CPen pen;pen.CreatePen(PS_DOT, 1, RGB(255, 0, 0));(左键点cwuziqiview——add windows handler…——添加函数)3、左键画棋子CDC *pDC=GetDC();pDC->Ellipse(point.x-20,point.y-20,point.x+20,point.y+20);ReleaseDC(pDC);4、右键画黑棋子CPen pen;pen.CreatePen(PS_SOLID, 3, RGB(255, 0, 0)); //样式、宽度、颜色CBrush brush;brush.CreateSolidBrush(RGB(0, 255, 0));CPen *pDCPen=pDC->SelectObject(&pen);CBrush *pDCBrush=pDC->SelectObject(&brush);pDC->Ellipse(point.x-20,point.y-20,point.x+20,point.y+20);pDC->SelectObject(pDCPen);pDC->SelectObject(pDCBrush);。
C语言棋盘游戏源代码# include <stdio.h># include <stdlib.h>char matrix[3][3];/*定义游戏棋盘 */char check(void);void init_matrix(void); void get_player_move(void); void get_computer_move(void); void disp_matrix(void);int main(){char done;printf("This is the game of Tic Tac Toe.\n");printf("You will be playing against the computer.\n");done = ' ';init_matrix();do{disp_matrix();get_player_move();done = check();/*检测输赢*/if(done!= ' ')break;/*赢了*/get_computer_move();done = check();/*检测输赢 */}while (done == ' ');if(done=='X') printf("You won!\n");else printf("Computer won!\n");disp_matrix();/*显示棋子的位置*/return 0;}/*初始化棋盘*/void init_matrix(void) {int i,j;for(i=0;i<3;i++)for (j=0;j<3;j++)matrix[i][j] = ' '; }/*下棋者下*/void get_player_move(void) {int x,y;printf("Enter coordinates for your X:"); scanf("%d%d",&x,&y);x--;y--;if(matrix[x][y] != ' '){printf("Invalid move,try again.\n");get_player_move();}else matrix[x][y]='X'; }/*计算机下*/void get_computer_move(void) {int i,j;for(i=0;i<3;i++){for (j=0;j<3;j++)if(matrix[i][j]== ' ')break;if(matrix[i][j]== ' ')break; }if(i*j==9){printf("draw\n");exit(0);}elsematrix[i][j]='O';}/*在屏幕上显示棋盘*/void disp_matrix(void){int t;for(t=0;t<3;t++){printf("%c|%c|%c",matrix[t][0],matrix[t][1],matrix[t][2]); if(t!=2)printf("\n-|-|-\n");}printf("\n");}/*看谁是赢着*/char check(void){int i;/*检查横行*/for(i=0;i<3;i++)if(matrix[i][0]==matrix[i][1]&&matrix[i][0]==matrix[i][2])return matrix[i][0];/*检查竖行*/for(i=0;i<3;i++)if(matrix[0][i]==matrix[1][i]&&matrix[0][i]==matrix[2][i])return matrix[0][i];/*检查对角线*/if(matrix[0][0]==matrix[1][1]&&matrix[1][1]==matrix[2][2])return matrix[0][0];if(matrix[0][2]==matrix[1][1]&&matrix[1][1]==matrix[2][0])return matrix[0][2];return ' ';}许多MM在减肥的过程中困难重重,用尽方法却瘦不下来,其实只有在数不清的技巧,推敲中找到属于跟适合自己的最佳方式,才能在健康的瘦身道路上走下去,下面一些瘦身的小技巧,一定可以帮到你,1、慢慢吃我们都曾在美味佳肴面前狼吞虎咽。
#include <iostream>#include <conio.h>using namespace std;#define WIDE_AND_LONG 20 //棋盘的长和宽#define NAME_LEN 20 //输入姓名的长度typedef class Gobang{public:int InitPlayerName(char *, char *);int CheckInput(char,int);int CheckIndexInput(char, char, char);int GetPlayerName();int InitBoard();int WriteBoard(char, char, bool);int BeginOrNot();int CheckRow();int CheckColumn();int CheckTopLeft();int CheckTopRight();int CheckDownLeft();int CheckDownRight();int CheckDraw();int CheckFinish();int Chess();int ShowBoard();private:char acBoard[WIDE_AND_LONG][WIDE_AND_LONG];char acPlayerOneName[NAME_LEN];char acPlayerTwoName[NAME_LEN];}GOBANG;//初始化姓名的缺省值int GOBANG::InitPlayerName(char *pPlayerOne,char *pPlayerTwo) {strcpy(acPlayerOneName,pPlayerOne);strcpy(acPlayerTwoName,pPlayerTwo);return 0;}//检查输入姓名时是否含非法字符空格和Tab键int GOBANG::CheckInput(char ch, int iNameLen){if(' ' == ch || '\t' == ch){cout<<"含有非法字符!"<<endl;return -1;}if(iNameLen > NAME_LEN - 1){cout<<"输入超出限定长度!"<<endl;return -1;}return 0;}//将棋子放到棋盘中int GOBANG::WriteBoard(char cRow, char cColumn, bool bJudge){int iRow = 0;int iColumn = 0;if(cRow >= '0' && cRow <= '9'){iRow = static_cast<int>(cRow - '0');}else if(cRow >= 'A' && cRow <= static_cast<char>('A' + WIDE_AND_LONG - 10 - 1)){iRow = static_cast<int>((cRow - 'A') + 10);}else{iRow = static_cast<int>((cRow - 'a') + 10);}if(cColumn >= '0' && cColumn <= '9'){iColumn = static_cast<int>(cColumn - '0');}else if(cColumn >= 'A' && cColumn <= static_cast<char>('A' + WIDE_AND_LONG - 10 - 1)) {iColumn = static_cast<int>((cColumn - 'A') + 10);}else{iColumn = static_cast<int>((cColumn - 'a') + 10);}if('+' != acBoard[iRow][iColumn]){cout<<"此处已有棋子!"<<endl;return -1;}if(!bJudge){acBoard[iRow][iColumn] = static_cast<char>(1);}else{acBoard[iRow][iColumn] = static_cast<char>(2);}return 0;}//检查坐标输入是否合法int GOBANG::CheckIndexInput(char cRow,char cSeparator,char cColumn){if(!cRow || !cSeparator || !cColumn){return -1;}if(!((cRow >= '0' && cRow <= '9') || \(cRow >= 'A' && cRow <= static_cast<char>('A' + WIDE_AND_LONG - 10 - 1)) || \ (cRow >= 'a' && cRow <= static_cast<char>('a' + WIDE_AND_LONG - 10 - 1)))){return -1;}if(' ' != cSeparator && '\t' != cSeparator && ',' != cSeparator){return -1;}if(!((cColumn >= '0' && cColumn <= '9') || \(cColumn >= 'A' && cColumn <= static_cast<char>('A' + WIDE_AND_LONG - 10 - 1)) || \ (cColumn >= 'a' && cColumn <= static_cast<char>('a' + WIDE_AND_LONG - 10 - 1)))){return -1;}return 0;}//获取玩家的昵称int GOBANG::GetPlayerName(){fflush(stdin);char cTemp = 0;int iNameLen = 0;cout<<"是否自己定义昵称?是(Y),否(任意键):";cTemp = getch();cout<<endl;if(('y' != cTemp) && ('Y' != cTemp)){return 0;}fflush(stdin);memset(acPlayerOneName,0,sizeof(acPlayerOneName)); memset(acPlayerTwoName,0,sizeof(acPlayerTwoName)); cout<<"请玩家一输入昵称:";while('\n' != (cTemp = getchar())){if(-1 == CheckInput(cTemp,iNameLen)){fflush(stdin);cout<<"请玩家一输入昵称:";continue;}acPlayerOneName[iNameLen] = cTemp;iNameLen++;}if(0 == iNameLen){strcpy(acPlayerOneName,"玩家一");}iNameLen = 0;fflush(stdin);cout<<"请玩家二输入昵称:";while('\n' != (cTemp = getchar())){if(-1 == CheckInput(cTemp,iNameLen)){fflush(stdin);cout<<"请玩家二输入昵称:";continue;}acPlayerTwoName[iNameLen] = cTemp;iNameLen++;}if(0 == iNameLen){strcpy(acPlayerTwoName,"玩家一");}return 0;}//初始化棋盘int GOBANG::InitBoard(){int iRow = 0;int iColumn = 0;for(iRow = 0; iRow < WIDE_AND_LONG; iRow++){for(iColumn = 0; iColumn < WIDE_AND_LONG; iColumn++) {acBoard[iRow][iColumn] = '+';}}return 0;}//检查棋盘横向是否存在五子连珠int GOBANG::CheckRow(){int iRow = 0;int iColumn = 0;int iPlayerOneLen = 0;int iPlayerTwoLen = 0;for(iRow = 0; iRow < WIDE_AND_LONG; iRow ++){while(iColumn < WIDE_AND_LONG){if(static_cast<char>(1) == acBoard[iRow][iColumn]){iPlayerOneLen ++;iPlayerTwoLen = 0;}else if(static_cast<char>(2) == acBoard[iRow][iColumn]){iPlayerTwoLen ++;iPlayerOneLen = 0;}else{iPlayerTwoLen = 0;iPlayerOneLen = 0;}iColumn ++;}if(iPlayerOneLen >= 5){return 1;if(iPlayerTwoLen >= 5){return 2;}iPlayerOneLen = 0;iPlayerTwoLen = 0;iColumn = 0;}return 0;}//检查棋盘竖向是否存在五子连珠int GOBANG::CheckColumn(){int iRow = 0;int iColumn = 0;int iPlayerOneLen = 0;int iPlayerTwoLen = 0;for(iColumn = 0; iColumn < WIDE_AND_LONG; iColumn ++) {while(iRow < WIDE_AND_LONG){if(static_cast<char>(1) == acBoard[iRow][iColumn]){iPlayerOneLen ++;iPlayerTwoLen = 0;}else if(static_cast<char>(2) == acBoard[iRow][iColumn]){iPlayerTwoLen ++;iPlayerOneLen = 0;}else{iPlayerTwoLen = 0;iPlayerOneLen = 0;}iRow ++;}if(iPlayerOneLen >= 5){return 1;}if(iPlayerTwoLen >= 5)return 2;}iPlayerOneLen = 0;iPlayerTwoLen = 0;iRow = 0;}return 0;}//检查棋盘左上方(包括对角线)是否存在五子连珠int GOBANG::CheckTopLeft(){int iRow = 0;int iTempRow = 0;int iColumn = 0;int iPlayerOneLen = 0;int iPlayerTwoLen = 0;for(iRow = 4; iRow < WIDE_AND_LONG; iRow ++){iTempRow = iRow;while(iTempRow >= 0){if(static_cast<char>(1) == acBoard[iTempRow][iColumn]){iPlayerOneLen ++;iPlayerTwoLen = 0;if(iPlayerOneLen >= 5){return 1;}}else if(static_cast<char>(2) == acBoard[iTempRow][iColumn]) {iPlayerTwoLen ++;iPlayerOneLen = 0;if(iPlayerTwoLen >= 5){return 2;}}else{iPlayerTwoLen = 0;iPlayerOneLen = 0;iTempRow --;iColumn ++;}iPlayerOneLen = 0;iPlayerTwoLen = 0;iColumn = 0;}return 0;}//检查棋盘右上方(包括对角线)是否存在五子连珠int GOBANG::CheckTopRight(){int iRow = 0;int iColumn = 0;int iTempColumn = 0;int iPlayerOneLen = 0;int iPlayerTwoLen = 0;for(iColumn = 0; iColumn < WIDE_AND_LONG - 4; iColumn ++) {iTempColumn = iColumn;while(iTempColumn < WIDE_AND_LONG){if(static_cast<char>(1) == acBoard[iRow][iTempColumn]){iPlayerOneLen ++;iPlayerTwoLen = 0;if(iPlayerOneLen >= 5){return 1;}}else if(static_cast<char>(2) == acBoard[iRow][iTempColumn]) {iPlayerTwoLen ++;iPlayerOneLen = 0;if(iPlayerTwoLen >= 5){return 2;}}else{iPlayerTwoLen = 0;iPlayerOneLen = 0;}iRow ++;iTempColumn ++;}iPlayerOneLen = 0;iPlayerTwoLen = 0;iRow = 0;}return 0;}//检查棋盘左下方(不包括对角线)是否存在五子连珠int GOBANG::CheckDownLeft(){int iRow = 0;int iTempRow = 0;int iColumn = 0;int iPlayerOneLen = 0;int iPlayerTwoLen = 0;for(iRow = 1; iRow < WIDE_AND_LONG - 4; iRow ++){iTempRow = iRow;while(iTempRow < WIDE_AND_LONG){if(static_cast<char>(1) == acBoard[iTempRow][iColumn]){iPlayerOneLen ++;iPlayerTwoLen = 0;if(iPlayerOneLen >= 5){return 1;}}else if(static_cast<char>(2) == acBoard[iTempRow][iColumn]) {iPlayerTwoLen ++;iPlayerOneLen = 0;if(iPlayerTwoLen >= 5){return 2;}}else{iPlayerTwoLen = 0;iPlayerOneLen = 0;}iTempRow ++;iColumn ++;}iPlayerOneLen = 0;iPlayerTwoLen = 0;iColumn = 0;}return 0;}//检查棋盘右下方(不包括对角线)是否存在五子连珠int GOBANG::CheckDownRight(){int iRow = 0;int iTempRow = 0;int iColumn = WIDE_AND_LONG - 1;int iPlayerOneLen = 0;int iPlayerTwoLen = 0;for(iRow = 1; iRow < WIDE_AND_LONG - 4; iRow ++){iTempRow = iRow;while(iTempRow < WIDE_AND_LONG){if(static_cast<char>(1) == acBoard[iTempRow][iColumn]){iPlayerOneLen ++;iPlayerTwoLen = 0;if(iPlayerOneLen >= 5){return 1;}}else if(static_cast<char>(2) == acBoard[iTempRow][iColumn]) {iPlayerTwoLen ++;iPlayerOneLen = 0;if(iPlayerTwoLen >= 5){return 2;}}else{iPlayerTwoLen = 0;iPlayerOneLen = 0;}iTempRow ++;iColumn --;}iPlayerOneLen = 0;iPlayerTwoLen = 0;iColumn = WIDE_AND_LONG - 1;}return 0;}//检查是否平局int GOBANG::CheckDraw(){int iRow = 0;int iColumn = 0;for(iRow = 0; iRow < WIDE_AND_LONG; iRow++){for(iColumn = 0; iColumn < WIDE_AND_LONG; iColumn++) {if('+' == acBoard[iRow][iColumn]){return 1;}}}return 0;}//检查是否达到结束的条件(五子连珠或平局)int GOBANG::CheckFinish(){int iJudgeRow = 0;int iJudgeColumn = 0;int iJudgeTopLeft = 0;int iJudgeTopRight = 0;int iJudgeDownLeft = 0;int iJudgeDownRight = 0;int iJudgeDraw = 0;iJudgeRow = CheckRow();iJudgeColumn = CheckColumn();iJudgeTopLeft = CheckTopLeft();iJudgeTopRight = CheckTopRight();iJudgeDownLeft = CheckDownLeft();iJudgeDownRight = CheckDownRight();iJudgeDraw = CheckDraw();if(1 == iJudgeRow || 1 == iJudgeColumn || 1 == iJudgeTopLeft || \1 == iJudgeTopRight || 1 == iJudgeDownLeft || 1 == iJudgeDownRight) {cout<<"恭喜玩家<"<<acPlayerOneName<<">获胜!"<<endl;return 1;}if(2 == iJudgeRow || 2 == iJudgeColumn || 2 == iJudgeTopLeft || \2 == iJudgeTopRight || 2 == iJudgeDownLeft || 2 == iJudgeDownRight) {cout<<"恭喜玩家<"<<acPlayerTwoName<<">获胜!"<<endl;return 1;}if(0 == iJudgeDraw){cout<<"平局!"<<endl;return 1;}return 0;}//显示棋盘到控制台int GOBANG::ShowBoard(){int iRow = 0;int iColumn = 0;system("cls");cout<<" ";for(iRow = 0; iRow < WIDE_AND_LONG; iRow++){if(9 < iRow){cout<<static_cast<char>('A' + iRow - 10)<<" ";}else{cout<<iRow<<" ";}}cout<<endl;for(iRow = 0; iRow < WIDE_AND_LONG; iRow++){if(9 < iRow){cout<<static_cast<char>('A' + iRow - 10)<<" ";}else{cout<<iRow<<" ";}for(iColumn = 0; iColumn < WIDE_AND_LONG; iColumn++){cout<<acBoard[iRow][iColumn]<<' ';}cout<<endl;}return 0;}//开始下棋int GOBANG::Chess(){bool bJudge = false;while(1){char cRow = 0;char cSeparator = 0;char cColumn = 0;char cTemp = 0;int iLen =1;fflush(stdin);if(!bJudge){cout<<"请<"<<acPlayerOneName<<">输入对应的行和列(格式: a,3 或a 3 或a 3):"; }else{cout<<"请<"<<acPlayerTwoName<<">输入对应的行和列(格式: a,3 或a 3 或a 3):"; }while('\n' != (cTemp = getchar())){if(iLen > 3){cout<<"输入有误!"<<endl;fflush(stdin);if(!bJudge){cout<<"请<"<<acPlayerOneName<<">输入对应的行和列(格式: a,3 或a 3 或a 3):"; }else{cout<<"请<"<<acPlayerTwoName<<">输入对应的行和列(格式: a,3 或a 3 或a 3):"; }iLen = 1;continue;}if(1 == iLen){cRow = cTemp;}else if(2 == iLen){cSeparator = cTemp;}else{cColumn = cTemp;}iLen++;}if(-1 == CheckIndexInput(cRow,cSeparator,cColumn)){cout<<"输入有误!"<<endl;continue;}if(-1 == WriteBoard(cRow,cColumn,bJudge)){continue;}ShowBoard();if(1 == CheckFinish()){BeginOrNot();}bJudge = !bJudge;}return 0;}//判断游戏结束后玩家是否选择继续还是退出int GOBANG::BeginOrNot(){char cTemp = 0;cout<<"是否继续?是(Y),退出(任意键):"; fflush(stdin);cTemp = getch();if('y' == cTemp || 'Y' == cTemp){InitBoard();ShowBoard();Chess();}else{exit(0); //程序的出口}return 0;}int main(){GOBANG gobang;memset(&gobang,0,sizeof(GOBANG)); gobang.InitPlayerName("玩家一","玩家二"); gobang.GetPlayerName();gobang.InitBoard();gobang.ShowBoard();gobang.Chess();return 0;}。
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>#include <stdlib.h>#include <windows.h>// 定义元素类型#define ELEMENT char// 游戏行数#define ROW 10// 游戏显示延迟#define SLEEPTIME 100int main(int argc, char *argv[]){// 定义游戏的棋盘,用数组存放ELEMENT array[ROW][ROW];// 定义获胜条件int winCondition = 5;// 初始化,把棋盘清空system("cls");int i,j;for(i = 0; i < ROW; i++){for(j = 0; j < ROW; j++){array[i][j] = ' ';}}// 循环游戏,当有一方满足胜利条件时终止int tmp;int count = 0; // 存放棋子数while(1){// 依次取出玩家记录的棋子int x, y;// 如果已经有子落下,则计算是第几步if(count > 0){printf("第%d步:\n", count);}// 显示游戏棋盘for(i = 0; i < ROW; i++){printf(" ");for(j = 0; j < ROW; j++){printf("---");}printf("\n|");for(j = 0; j < ROW; j++){printf("%c |", array[i][j]);}printf("\n");}printf(" ");for(j = 0; j < ROW; j++){printf("---");}printf("\n");// 要求玩家输入放下棋子的位置printf("请玩家输入要放弃棋子的位置(1-%d)\n", ROW); printf("横坐标:");scanf("%d", &x);printf("纵坐标:");scanf("%d", &y);// 判断棋子位置是否有效if(x < 1 || x > ROW || y < 1 || y > ROW || array[x-1][y-1] != ' '){printf("输入错误!\n");system("pause");system("cls");continue;}// 把棋子记录,并计数if(count % 2 == 0){array[x-1][y-1] = 'X';}else{array[x-1][y-1] = 'O';}count++;// 判断是否有获胜者int i, j, k;int tempx, tempy;for(i = 0; i < ROW; i++){for(j = 0; j < ROW; j++){if(array[i][j] == 'X' || array[i][j] == 'O') {// 判断横向是否有获胜者tmp = 1;for(k = 1; k < winCondition; k++){// 注意边界,必须验证范围有效if(j + k > ROW - 1) break;// 如果和前一个位置的棋子相同,则计数加1,否则跳出if(array[i][j+k] == array[i][j])tmp++;else break;}// 如果计数满足获胜条件,则显示获胜者if(tmp >= winCondition){printf("玩家 %c 获胜!\n", array[i][j]);system("pause");return 0;}// 判断纵向是否有获胜者tmp = 1;for(k。
#include <stdio.h>#include <ctype.h>#define SIZE 8void display(char board[][SIZE]);int valid_moves(char board[][SIZE],int moves[][SIZE],char player);void make_move(char board[][SIZE],int row,int col,char player);void computer_move(char board[][SIZE],int moves[][SIZE],char player);int get_score(char board[][SIZE],char player);int best_move(char board[][SIZE],int moves[][SIZE],char player);int main(){char board[SIZE][SIZE]={0};int moves[SIZE][SIZE]={0};int row=0;int col=0;int no_of_games=0;int no_of_moves=0;int invalid_moves=0;int comp_score=0;int user_score=0;char y=0;char x=0;char again=0;int player=0;printf("\nREVERSI\n\n");printf("You can go first on the first game,then we will take truns.\n"); printf(" You will be white - (0)\n I will be black - (@).\n");printf("Select a square for your move by typing a digit for the row\n" "and a letter for the column with no spaces between.\n");printf("\nGood luck! press Enter to start.\n");scanf("%c",&again);do{player=++no_of_games%2;no_of_moves=4;for(row=0;row<SIZE;row++)for(col=0;col<SIZE;col++)board[row][col]=' ';board[SIZE/2-1][SIZE/2-1]=board[SIZE/2][SIZE/2]='0';board[SIZE/2-1][SIZE/2]=board[SIZE/2][SIZE/2-1]='@';do{display(board);if(player++%2){if(valid_moves(board,moves,'0')){for(;;){fflush(stdin);printf("Please enter your move (row column): ");scanf("%d%c",&x,&y);y=tolower(y)-'a';x--;if(x>=0&&y>=0&&x<SIZE&&y<SIZE&&moves[x][y]){make_move(board,x,y,'0');no_of_moves++;break;}elseprintf("Not a valid move,try again.\n");}}elseif(++invalid_moves<2){fflush(stdin);printf("\nYou have to pass,press return");scanf("%c",&again);}elseprintf("\nNeither of us can go, so the game is over.\n"); }else{if(valid_moves(board,moves,'@')){invalid_moves=0;computer_move(board,moves,'@');no_of_moves++;}else{if(++invalid_moves<2)printf("\nI have to pass, your go\n");elseprintf("\nNeither of us can go, so the game is over.\n"); }}}while(no_of_moves<SIZE*SIZE&&invalid_moves<2);display(board);comp_score=user_score=0;for(row=0;row<SIZE;row++)for(col=0;col<SIZE;col++){comp_score+=board[row][col]=='@';user_score+=board[row][col]=='0';}printf("The final score is:\n");printf("Computer %d\n User %d\n\n",comp_score,user_score);fflush(stdin);printf("Do you want to play again (y/n): ");scanf("%c",&again);}while(tolower(again)=='y');printf("\nGoodbye\n");}void display(char board[][SIZE]){int row=0;int col=0;char col_label='a';printf("\n ");for(col=0;col<SIZE;col++)printf(" %c",col_label+col);printf("\n");for(row=0;row<SIZE;row++){printf(" +");for(col=0;col<SIZE;col++)printf("---+");printf("\n%2d|",row+1);for(col=0;col<SIZE;col++)printf(" %c |",board[row][col]);printf("\n");}printf(" +");for(col=0;col<SIZE;col++)printf("---+");printf("\n");}int valid_moves(char board[][SIZE],int moves[][SIZE],char player) {int rowdelta=0;int coldelta=0;int row=0;int col=0;int x=0;int y=0;int no_of_moves=0;char opponent=(player=='0')?'@':'0';for(row=0;row<SIZE;row++)for(col=0;col<SIZE;col++)moves[row][col]=0;for(row=0;row<SIZE;row++)for(col=0;col<SIZE;col++){if(board[row][col]!=' ')continue;for(rowdelta=-1;rowdelta<=1;rowdelta++)for(coldelta=-1;coldelta<=1;coldelta++){if(row+rowdelta<0||row+rowdelta>=SIZE||col+coldelta<0||col+coldelta>=SIZE||(rowdelta==0&&coldelta==0))continue;if(board[row+rowdelta][col+coldelta]==opponent){x=row+rowdelta;y=col+coldelta;for(;;){x+=rowdelta;y+=coldelta;if(x<0||x>=SIZE||y<0||y>=SIZE)break;if(board[x][y]==' ')break;if(board[x][y]==player){moves[row][col]=1;no_of_moves++;break;}}}}}return no_of_moves;}void make_move(char board[][SIZE],int row,int col,char player) {int rowdelta=0;int coldelta=0;int x=0;int y=0;char opponent=(player=='0')?'@':'0';board[row][col]=player;for(rowdelta=-1;rowdelta<=1;rowdelta++)for(coldelta=-1;coldelta<=1;coldelta++){if(row+rowdelta<0||row+rowdelta>=SIZE||col+coldelta<0||col+coldelta>=SIZE||(rowdelta==0&&coldelta==0))continue;if(board[row+rowdelta][col+coldelta]==opponent){x=row+rowdelta;y=col+coldelta;for(;;){x+=rowdelta;y+=coldelta;if(x<0||x>=SIZE||y<0||y>=SIZE)break;if(board[x][y]==' ')break;if(board[x][y]==player){while(board[x-=rowdelta][y-=coldelta]==opponent) board[x][y]=player;break;}}}}}int get_score(char board[][SIZE],char player){int score=0;int row=0;int col=0;char opponent=player=='0'?'@':'0';for(row=0;row<SIZE;row++)for(col=0;col<SIZE;col++){score-=board[row][col]==opponent;score+=board[row][col]==player;}return score;}int best_move(char board[][SIZE],int moves[][SIZE],char player){int row=0;int col=0;int i=0;int j=0;char opponent=player=='0'?'@':'0';char new_board[SIZE][SIZE]={0};int score=0;int new_score=0;for(row=0;row<SIZE;row++)for(col=0;col<SIZE;col++){if(!moves[row][col])continue;for(i=0;i<SIZE;i++)for(j=0;j<SIZE;j++)new_board[i][j]=board[i][j];make_move(new_board,row,col,player);new_score=get_score(new_board,player);if(score<new_score)score=new_score;}return score;}void computer_move(char board[][SIZE],int moves[][SIZE],char player) {int row=0;int col=0;int best_row=0;int best_col=0;int i=0;int j=0;int new_score=0;int score=100;char temp_board[SIZE][SIZE];int temp_moves[SIZE][SIZE];char opponent=player=='0'?'@':'0';for(row=0;row<SIZE;row++)for(col=0;col<SIZE;col++){if(moves[row][col]==0)continue;for(i=0;i<SIZE;i++)for(j=0;j<SIZE;j++)temp_board[i][j]=board[i][j];make_move(temp_board,row,col,player);valid_moves(temp_board,temp_moves,opponent);new_score=best_move(temp_board,temp_moves,opponent);if(new_score<score){score=new_score;best_row=row;best_col=col;}}make_move(board,best_row,best_col,player);}。
# include <stdio.h> # include <stdlib.h>char matrix[3][3];/*定义游戏棋盘*/char check(void);void init_matrix(void);void get_player_move(void);void disp_matrix(void);int main(){char done;printf("This is the game of Tic Tac Toe.\n");done = ' ';init_matrix();do{disp_matrix();get_player_move();done = check();/*检测输赢*/if(done!= ' ')break;/*赢了*/done = check();/*检测输赢*/}while (done == ' ');if(done=='X') printf("You won!\n");else printf("Computer won!\n");disp_matrix();/*显示棋子的位置*/return 0;}/*初始化棋盘*/void init_matrix(void){int i,j;for(i=0;i<3;i++)for (j=0;j<3;j++)matrix[i][j] = ' ';}/*下棋者下*/void get_player_move(void){int x,y;printf("Enter coordinates for your X:");scanf("%d%d",&x,&y);x--;y--;if(matrix[x][y] !=' '){printf("Invalid move,try again.\n");get_player_move();}else matrix[x][y]='X';}/*计算机下*/for(i=0;i<3;i++){for (j=0;j<3;j++)if(matrix[i][j]== ' ')break;if(matrix[i][j]== ' ')break;}if(i*j==9){printf("draw\n");exit(0);}elsematrix[i][j]='O';}/*在屏幕上显示棋盘*/void disp_matrix(void){int t;for(t=0;t<3;t++){printf("%c|%c|%c",matrix[t][0],matrix[t][1],matrix[t][2]); if(t!=2)printf("\n-|-|-\n");}printf("\n");}/*看谁是赢着*/char check(void){int i;/*检查横行*/for(i=0;i<3;i++)if(matrix[i][0]==matrix[i][1]&&matrix[i][0]==matrix[i][2])return matrix[i][0];/*检查竖行*/for(i=0;i<3;i++)if(matrix[0][i]==matrix[1][i]&&matrix[0][i]==matrix[2][i])return matrix[0][i];/*检查对角线*/if(matrix[0][0]==matrix[1][1]&&matrix[1][1]==matrix[2][2]) return matrix[0][0];if(matrix[0][2]==matrix[1][1]&&matrix[1][1]==matrix[2][0]) return matrix[0][2];return ' ';}。
C语言程序设计附源代码//中国象棋#include<stdio.h>#include<Windows.h>#include<stdlib.h>//定义棋盘int board[10][9] =0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,2,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,1,0,0,0,0,0,0,0,0,0,0,0,0};//全局变量bool flag;//游戏函数声明void SetCursor(int, int); // 移动光标位置void PrintChessBoard(; // 打印棋盘void TravelChessBoard(; // 遍历棋子void MoveChess(int, int, int, int); // 移动棋子void DeleteChess(int, int); // 吃子bool CanMove(int, int, int, int); // 判断走法是否合理bool IsKing(int, int, int, int); // 是否将帅相对bool IsOver(; // 游戏是否结束//主函数int mainPrintChessBoard(;TravelChessBoard(;return 0;//打印棋盘void PrintChessBoardprintf("欢迎来到中国象棋\n");printf(" 1 2 3 4 5 6 7 8 9\n");printf(" +-----------------+\n");for(int i=0; i<9; i++) printf("%d,",i+1);for(int j=0; j<9; j++) switch(board[i][j]) case 0:printf(" ");break;case 1:printf("帅");break;case 2:printf("将");break;case 3:printf("兵");break;case 4:printf("马");break;printf("象");break;case 6:printf("炮");break;case 7:printf("车");break;}printf(" ");}printf(",\n");}printf(" +-----------------+\n"); //寻找棋子void TravelChessBoardwhile(!IsOver()//玩家1pswh = 1;。