跟brocode用c语言做tictoktoe井字棋 - 指南
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#include
//这是c语言代码,使用cpp高亮
char board[3][3];
const char Player = 'X';
const char Computer = 'O';
void resetBoard();
void printBoard();
int checkFreeSpace();
void playerMove();
void computerMove();
char checkWinner();
void printWinner(char);
int main() {char winner = ' ';char response;do {winner = ' ';response = ' ';resetBoard();while (winner == ' ' && checkFreeSpace() != 0){printBoard();playerMove();winner = checkWinner();if (winner != ' ' || checkFreeSpace() == 0){break;}computerMove();winner = checkWinner();if (winner != ' ' || checkFreeSpace() == 0){break;}}printBoard();printWinner(winner);printf("would you like to play again(Y/N)");while (getchar() != '\n');scanf("%c", &response);while (getchar() != '\n');response = toupper(response);} while(response == 'Y');printf("thanks for playing");return 0;
}
void resetBoard()
{for (int i = 0; i < 3; i++){for (int j = 0; j < 3; j++){board[i][j] = ' ';}}
}
void printBoard()
{printf(" %c | %c | %c ", board[0][0], board [0][1], board[0][2]);printf("\n---|---|---\n");printf(" %c | %c | %c ", board[1][0], board[1][1], board[1][2]);printf("\n---|---|---\n");printf(" %c | %c | %c ", board[2][0], board[2][1], board[2][2]);printf("\n---|---|---\n");printf("\n");
}
int checkFreeSpace() {int freeSpaces = 9;for (int i = 0; i < 3; i++){for (int j = 0; j < 3; j++){if (board[i][j] != ' '){freeSpaces--;}}}return freeSpaces;
}
void playerMove() {int x;int y;do {printf("enter row #(1-3)");scanf("%d", &x);while (getchar() != '\n');x--;printf("enter column");scanf("%d", &y);while (getchar() != '\n');y--;if (board[x][y] != ' '){printf("invalid move!\n");}else{board[x][y] = Player;break;}} while (board[x][y]!= ' ');
}
void computerMove()
{srand(time(0));int x;int y;if (checkFreeSpace() > 0){do{x = rand() % 3;y = rand() % 3;} while (board[x][y] != ' ');board[x][y] = Computer;}else{printWinner(' ');}
}
char checkWinner()
{for (int i = 0; i < 3; i++){if (board[i][0] == board[i][1] && board[i][1] == board[i][2]){return board[i][0];}}for (int j = 0; j < 3; j++){if (board[j][0] == board[j][1] && board[j][1] == board[j][2]){return board[j][0];}}if (board[0][0] == board[1][1] && board[1][1] == board[2][2]){return board[0][0];}if (board[0][2] == board[1][1] && board[1][1] == board[2][0]){return board[2][0];}return ' ';
}
void printWinner(char winner)
{if (winner == Player){printf("you win");}else if (winner == Computer){printf("you lose");}else{printf("its a tie");}
}
利用ide为vs
目前运行中有以下几个问题:
1.一开始scanf函数一直报不安全,改成scanf_s函数后忘了什么原因但也一直不能正常运行,在前面加了一个引用处理。
2.一开始无法正常进行第二轮游戏,但在对内容进行修改后变得无法识别游戏结束了,即使已经赢了也得下满9子才能表现,未发现原因。
暂时无法解决上述问题,先搁置,备份,过几周再回来看。
现在计组刚看完存储器那章,这门东西好多啊……
目前在设想如何实现五子棋作用,以及其他项目。
