用c语言写一个三子棋代码
时间: 2023-03-20 08:00:14 浏览: 138
好的,以下是一个简单的用C语言实现三子棋的代码,供参考:
```
#include <stdio.h>
#include <stdlib.h>
// 定义棋盘大小
#define ROWS 3
#define COLS 3
// 定义棋子类型
#define EMPTY ' '
#define PLAYER 'X'
#define COMPUTER 'O'
// 初始化棋盘
void initializeBoard(char board[ROWS][COLS]) {
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
board[i][j] = EMPTY;
}
}
}
// 打印棋盘
void printBoard(char board[ROWS][COLS]) {
int i, j;
printf("\n");
for (i = 0; i < ROWS; i++) {
printf(" %c | %c | %c ", board[i][0], board[i][1], board[i][2]);
if (i != ROWS - 1) {
printf("\n---|---|---\n");
}
}
printf("\n");
}
// 获取玩家输入
void getPlayerMove(char board[ROWS][COLS], int *row, int *col) {
printf("请输入您下棋的位置(行和列),以逗号分隔:");
scanf("%d,%d", row, col);
while (board[*row-1][*col-1] != EMPTY) {
printf("该位置已有棋子,请重新输入:");
scanf("%d,%d", row, col);
}
}
// 判断游戏是否结束
int isGameOver(char board[ROWS][COLS], char player) {
int i, j, isTie = 1;
// 判断行
for (i = 0; i < ROWS; i++) {
if (board[i][0] == player && board[i][1] == player && board[i][2] == player) {
return 1;
}
if (board[i][0] == EMPTY || board[i][1] == EMPTY || board[i][2] == EMPTY) {
isTie = 0;
}
}
// 判断列
for (j = 0; j < COLS; j++) {
if (board[0][j] == player && board[1][j] == player && board[2][j] == player) {
return 1;
}
}
// 判断对角线
if (board[0][0] == player && board[1][1] == player && board[2][2] == player) {
return 1;
}
if (board[0][2] == player && board[1][1] == player && board[2][0] == player) {
return 1;
}
// 判断是否平局
if (isTie == 1) {
return 2;
}
return 0;
}
// 计算电脑下棋的位置
void getComputerMove(char board[ROWS][COLS], int *row, int *col) {
int i, j, count = 0, maxCount = 0, maxRow = 0, maxCol = 0;
// 遍历棋盘
for (i = 0
阅读全文