1 #include <stdio.h> 2 #include <Windows.h> 3 #include<time.h> 4 #define row 3 5 #define list 3 6 7 void init_Board(char board[row][list]) //对二维数组元素全部赋值为 “ ” 8 { 9 memset(board,‘ ‘,row*list*sizeof(char)); 10 } 11 12 void display_Board(char board[row][list])//画出棋谱 13 { 14 system("cls"); 15 int i = 0; 16 for (i = 0; i < row; i++) 17 { 18 printf(" %c |%c | %c\n", board[i][0], board[i][1], board[i][2]); 19 if (i != 2){ 20 printf(" --|--|--\n"); 21 } 22 } 23 printf("(X代表玩家,0代表电脑)\n") ; 24 } 25 26 void man_Play(char board[row][list]) //玩家下“子” 27 { 28 int i = 0; 29 int j = 0; 30 flag: 31 printf("选择一个坐标:\n"); 32 scanf("%d", &i); 33 if (i > 3 || i <1) 34 { 35 printf("横坐标越界,重输:\n"); 36 goto flag; 37 } 38 scanf("%d", &j); 39 if (j > 3 || j <1) 40 { 41 printf("纵坐标越界,重输:\n"); 42 goto flag; 43 } 44 if (board[i-1][j-1] == ‘ ‘) 45 board[i-1][j-1]=‘X‘; 46 else 47 { 48 printf("所选位置已被下过,请重新输入\n"); 49 goto flag; 50 } 51 } 52 53 char is_Win(char board[row][list]) 54 { 55 int i = 0; 56 int j = 0; 57 for (i = 0; i < row; i++) 58 { 59 if ((board[i][0] == board[i][1]) && (board[i][0] == board[i][2])) 60 return board[i][0]; 61 } 62 for (j = 0; j < row; j++) 63 { 64 if ((board[0][j] == board[1][j]) &&( board[0][j] == board[2][j])) 65 return board[0][j]; 66 } 67 if ((board[0][0] == board[1][1]) && (board[1][1] == board[2][2])) 68 return board[1][1]; 69 if ((board[0][2] == board[1][1]) && (board[1][1] == board[2][0])) 70 return board[1][1]; 71 return ‘ ‘; 72 } 73 void computer_Play(char board[row][list]) //电脑下“子” 74 { 75 int i = 0; 76 int j = 0; 77 while (1) 78 { 79 srand((int)time(0));//设置随机种子 80 i = rand() % 3; //产生随机数 81 j = rand() % 3; 82 if (board[i][j] == ‘ ‘) 83 { 84 board[i][j] = ‘0‘; 85 break; 86 } 87 } 88 } 89 90 int is_Full(char board[row][list]) 91 { 92 int i = 0; 93 int j = 0; 94 int count = 0; 95 for (i = 0; i < row;i++) 96 for (j = 0; j < list; j++) 97 { 98 if (board[i][j] == ‘ ‘) 99 count++; 100 } 101 return count; 102 } 103 104 int main() 105 { 106 char board[row][list]; 107 init_Board(board); 108 display_Board(board); 109 while (1) 110 { 111 if ((is_Full(board) > 0)) 112 { 113 man_Play(board); 114 display_Board(board); 115 printf("\n"); 116 if (is_Win(board) == ‘X‘) 117 { 118 printf("玩家胜\n"); 119 break; 120 } 121 } 122 else 123 { 124 printf("平局!"); 125 break; 126 } 127 if ((is_Full(board) >0)) 128 { 129 computer_Play(board); 130 display_Board(board); 131 printf("\n"); 132 if (is_Win(board) == 48) 133 { 134 printf("电脑胜\n"); 135 break; 136 } 137 } 138 else 139 { 140 printf("平局!"); 141 break; 142 } 143 } 144 printf("游戏结束!\n"); 145 system("pause"); 146 return 0; 147 }
原文:http://www.cnblogs.com/tp-16b/p/7806945.html