三子棋代码
1 #define _CRT_SECURE_NO_WARNINGS 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <time.h> 5 #define ROW 3 6 #define COL 3 7 char ch[ROW][COL]; 8 /* 9 1..初始化 全部为' '空格 10 2..人棋子标记为 'p' 11 3..机器棋子标记为 'a' 12 4..人成功返回 'p' 13 5..机器成功返回 'a' 14 6..平局返回 'e' 15 7..other返回 ' '空格 16 17 */ 18 //检验是否棋盘满 19 int isFull(){ 20 for (int row = 0; row < ROW; row++){ 21 for (int col = 0; col < COL; col++){ 22 if (ch[row][col] == ' '){ 23 return 0; 24 } 25 } 26 } 27 return 1; 28 } 29 //初始化 30 void init(){ 31 for (int row = 0; row < ROW; row++){ 32 for (int col = 0; col < COL; col++){ 33 ch[row][col] = ' '; 34 } 35 } 36 } 37 //打印棋盘 38 void print(){ 39 for (int row = 0; row < ROW; row++){ 40 printf("| %c | %c | %c | ", ch[row][0], ch[row][1],ch[row][2]); 41 if (row < 2){ 42 printf(" --- --- --- "); 43 } 44 } 45 } 46 //人落棋 47 void PresonMoveChess(){ 48 //1.提示 49 printf("请输入坐标:> "); 50 int row = 0; 51 int col = 0; 52 while (1){ 53 scanf("%d %d", &row, &col); 54 if (row < 0 || row >= ROW || col < 0 || col >= COL){ 55 printf("输入有误,请重新输入:> "); 56 continue; 57 } 58 ch[row][col] = 'p'; 59 break; 60 } 61 } 62 //机器落棋 63 void AlMoveChess(){ 64 int row = 0; 65 int col = 0; 66 while (1){ 67 row = rand() % ROW; 68 col = rand() % COL; 69 if (row < 0 || row >= ROW || col < 0 || col >= COL){ 70 continue; 71 } 72 if (ch[row][col] != ' '){ 73 continue; 74 } 75 ch[row][col] = 'a'; 76 break; 77 } 78 } 79 //检验是否成功 80 char checkIsSuccess(){ 81 //1.检查列 82 for (int row = 0; row < ROW; row++){ 83 if (ch[row][0] == ch[row][1] && ch[row][0] == ch[row][2] && ch[row][0] != ' '){ 84 return ch[row][0]; 85 } 86 } 87 //2.检查列 88 for (int col = 0; col < COL; col++){ 89 if (ch[0][col] == ch[1][col] && ch[0][col] == ch[2][col] && ch[0][col] != ' '){ 90 return ch[col][0]; 91 } 92 } 93 //3.检查对角线 94 if (ch[0][0] == ch[1][1] && ch[0][0] == ch[2][2] && ch[0][0] != ' '){ 95 return ch[0][0]; 96 } 97 if (ch[0][2] == ch[1][1] && ch[0][2] == ch[2][0] && ch[2][0] != ' '){ 98 return ch[0][2]; 99 } 100 //4.检查是否为平局 101 if (isFull()){ 102 return 'e'; 103 } 104 return ' '; 105 } 106 107 int main(){ 108 srand((unsigned int)time(0)); 109 //1.初始化棋盘 110 init(); 111 print(); 112 char winner = 'k'; 113 while (1){ 114 //2.人落棋 115 PresonMoveChess(); 116 //3.检查人是否成功 117 winner = checkIsSuccess(); 118 if (winner != ' '){ 119 break; 120 } 121 //4.机器落棋 122 AlMoveChess(); 123 //5.检验机器是否成功 124 winner = checkIsSuccess(); 125 if (winner != ' '){ 126 break; 127 } 128 system("cls"); 129 print(); 130 } 131 if (winner == 'p'){ 132 printf("nice "); 133 } 134 else if (winner == 'a'){ 135 printf("lowbbbbbbb "); 136 } 137 else { 138 printf("lowb "); 139 } 140 141 system("pause"); 142 return 0; 143 }