C语言实现三子棋实例代码攻略
一、实现思路
- 三子棋的棋盘大小为3x3,可以定义一个3x3的二维数组表示;
- 玩家和电脑轮流下棋,可以用一个变量记录当前下棋方,如0代表玩家,1代表电脑;
- 玩家可以通过输入坐标来下棋,电脑可以随机生成坐标;
- 每下一步棋都需要检查胜负情况,即检查当前是否有连续的3个棋子相连。
二、实现代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 定义棋盘大小
#define ROW 3
#define COL 3
// 定义棋子类型
#define PLAYER 'X'
#define COMPUTER 'O'
#define EMPTY ' '
// 打印棋盘
void print_board(char board[ROW][COL]) {
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
printf("%c |", board[i][j]);
}
printf("\n----------\n");
}
}
// 判断当前位置是否可下棋
int is_valid_move(char board[ROW][COL], int row, int col) {
if (row < 0 || row >= ROW || col < 0 || col >= COL) {
return 0;
} else if (board[row][col] != EMPTY) {
return 0;
} else {
return 1;
}
}
// 判断是否有连续的3个相同棋子
int check_winner(char board[ROW][COL], char player) {
// 判断行
for (int i = 0; i < ROW; i++) {
if (board[i][0] == player && board[i][1] == player && board[i][2] == player) {
return 1;
}
}
// 判断列
for (int j = 0; j < COL; 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;
} else if (board[0][2] == player && board[1][1] == player && board[2][0] == player) {
return 1;
}
return 0;
}
// 玩家下棋
void player_move(char board[ROW][COL]) {
int row, col;
printf("请输入下棋的坐标(以逗号分隔):");
scanf("%d,%d", &row, &col);
if (is_valid_move(board, row, col)) {
board[row][col] = PLAYER;
} else {
printf("该位置不可下棋,请重新输入\n");
player_move(board);
}
}
// 电脑下棋
void computer_move(char board[ROW][COL]) {
int row, col;
srand(time(NULL));
do {
row = rand() % ROW;
col = rand() % COL;
} while (!is_valid_move(board, row, col));
printf("电脑下棋坐标为:%d,%d\n", row, col);
board[row][col] = COMPUTER;
}
// 判断是否棋盘已满
int is_full(char board[ROW][COL]) {
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
if (board[i][j] == EMPTY) {
return 0;
}
}
}
return 1;
}
// 游戏主循环
void game_loop(char board[ROW][COL]) {
int turn = 0;
while (1) {
print_board(board);
if (turn % 2 == 0) {
player_move(board);
if (check_winner(board, PLAYER)) {
print_board(board);
printf("恭喜你获得胜利!\n");
break;
}
} else {
computer_move(board);
if (check_winner(board, COMPUTER)) {
print_board(board);
printf("很遗憾,电脑获胜!\n");
break;
}
}
turn++;
if (is_full(board)) {
print_board(board);
printf("平局!\n");
break;
}
}
}
// 主函数
int main() {
char board[ROW][COL] = {
{EMPTY, EMPTY, EMPTY},
{EMPTY, EMPTY, EMPTY},
{EMPTY, EMPTY, EMPTY},
};
game_loop(board);
return 0;
}
三、示例说明
示例1:玩家输入非法坐标
请输入下棋的坐标(以逗号分隔):3,0
该位置不可下棋,请重新输入
请输入下棋的坐标(以逗号分隔):
示例2:玩家获胜
X | |
----------
| X | O
----------
| O | X
----------
X | |
----------
| X | O
----------
| O | X
----------
恭喜你获得胜利!
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C语言实现三子棋实例代码 - Python技术站