三子棋是黑白棋的一种。三子棋是一种民间传统游戏,又叫九宫棋、圈圈叉叉、一条龙、井字棋等。将正方形对角线连起来,相对两边依次摆上三个双方棋子,只要将自己的三个棋子走成一条线,对方就算输了。但是,有很多时候会出现和棋的情况。
#define _CRT_SECURE_NO_WARNINGS #include#include #include #include #define MAX_ROW 3 #define MAX_COL 3 利用宏定义来定义棋盘的大小,因为井字棋需要一个3*3的棋盘,为了避免魔幻数字(在后续代码中出现,不能很直观的看出是长还是宽)的出现,我们用ROW和COl来代替 void init(char board[MAX_ROW][MAX_COL]) { for (int row = 0; row < MAX_ROW; row++) { for (int col = 0; col < MAX_COL; col++) { board[row][col] = ' '; } } srand((unsigned int)time(0)); } //给用户打印一个棋盘 void printBoard(char board[MAX_ROW][MAX_COL]) { system("cls"); for (int row = 0; row < MAX_ROW; row++) { printf("+--+--+--+n"); for (int col = 0; col < MAX_COL; col++) { printf("| %c", board[row][col]); } printf("|"); printf("n"); } printf("+--+--+--+n"); } //玩家落子函数 void playerMove(char board[MAX_ROW][MAX_COL]) { while (1) { printf("请玩家落子!"); printf("请输入你要落子的位置(row col):"); int row = 0; int col = 0; scanf("%d %d", &row, &col); if (row < 0 || row > MAX_ROW || col < 0 || col > MAX_COL) { printf("你的输入有误,请重新输入!n"); continue; } if (board[row][col] != ' ') { printf("你输入的位置已经有子,无法继续落子!n"); continue; } board[row][col] = 'x'; break; } } //电脑落子函数 void computerMove(char board[MAX_ROW][MAX_COL]) { printf("轮到电脑落子!n"); while (1) { int row = rand() % MAX_ROW; int col = rand() % MAX_COL; if (board[row][col] == 'x') { continue; } board[row][col] = 'o'; break; } } //判断是否和棋 int isFull(char board[MAX_ROW][MAX_COL]) { for (int row = 0; row < MAX_ROW; row++) { for (int col = 0; col < MAX_COL; col++) { if (board[row][col] == ' ') return 0; } } return 1; } //判断是否连成一条线 char checkWinner(char board[MAX_ROW][MAX_COL]) { int row = 0; int col = 0; for (row = 0; row < MAX_ROW; row++) { if (board[row][col] != ' ' && board[row][0] == board[row][1] && board[row][0] == board[row][2]) { return board[row][0]; } } for (col = 0; col < MAX_COL; col++) { if (board[0][col] != ' ' && board[0][col] == board[1][col] && board[0][col] == board[2][col]) { return board[0][col]; } } if (board[0][0] != ' ' && board[0][0] == board[1][1] && board[0][0] == board[2][2]) { return board[0][0]; } if (board[0][2] != ' ' && board[0][2] == board[1][1] && board[0][2] == board[2][0]) { return board[0][2]; } if (isFull(board)) { //棋盘满返回一个q return 'q'; } //棋盘没满返回一个空字符 return ' '; } int main() { char board[MAX_ROW][MAX_COL] = { 0 }; char winner = ' '; init(board); while (1) { printBoard(board); //system("pause"); playerMove(board); checkWinner(board); winner = checkWinner(board); if (winner != ' ') { printBoard(board); break; } computerMove(board); winner = checkWinner(board); if (winner != ' ') { break; } } if (winner == 'x') { printf("恭喜你,你赢了!!!"); } else if (winner == 'o') { printf("你真菜,竟然输了"); } else { printf("你和人工智障五五开"); } return 0; }
以上就是三子棋的全部内容,欢迎大家提出问题.
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)