#include<stdio.h> #include<stdlib.h> #include<time.h> #define ROW 3 #define COL 3
//初始化棋盘的 voidInitBoard(char board[ROW][COL], int row, int col); //打印棋盘 voidDisplayBoard(char board[ROW][COL],int row,int col); //玩家下棋 voidplayer_move(char board[ROW][COL], int row, int col); //电脑下棋 voidcomputer_move(char board[ROW][COL], int row, int col); //判断输赢 charisWinner(char board[ROW][COL], int row, int col);
下面是game.c文件的各个函数的定义
首先是初始化棋盘,便利3x3的数组,将数组内的元素置为空格字符
1 2 3 4 5 6 7 8 9 10
//初始化棋盘的 voidInitBoard(char board[ROW][COL], int row, int col){ int i = 0; for (i = 0; i < row; i++) { int j = 0; for (j = 0; j < col; j++) { board[i][j] = ' '; } } }
//电脑下棋 voidcomputer_move(char board[ROW][COL], int row, int col){ int x = 0; int y = 0; printf("电脑下棋\n"); while(1) { x = rand() % row; y = rand() % col; if(board[x][y] == ' ') {
intisPeace(char board[ROW][COL], int row, int col){ int i = 0; for (i = 0; i < row; i++) { int j = 0; for (j = 0; j < col; j++) { if (board[i][j] == ' ') { return0; } } return1; } } //判断输赢 charisWinner(char board[ROW][COL], int row, int col) {
//判断行 int i = 0; for (i = 0; i < row; i++) { if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][1] != ' ') { return board[i][1]; } } //判断列 int j = 0; for (j = 0; j < col; j++) { if (board[0][j] == board[1][j] && board[1][j] == board[2][j] && board[1][j] != ' ') { return board[1][j]; } } //判断对角线 if (board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[0][0] != ' ') { return board[1][1]; } if (board[0][2] == board[1][1] && board[0][2] == board[2][0] && board[0][2] != ' ') { return board[1][1]; } //判断平局 if (isPeace(board, row, col) == 1) { return'Q'; } else { return'C'; } }