c语言洛谷p1838三子棋
时间: 2023-06-21 20:10:52 浏览: 157
C语言实现三子棋小游戏
三子棋是一种非常经典的棋类游戏,它的规则非常简单,只需要两个人轮流将棋子放在一个3x3的棋盘上,先将三个棋子连成一条线的人获胜。下面是一个简单的 C 语言实现:
```c
#include <stdio.h>
// 棋盘大小
#define BOARD_SIZE 3
// 棋子类型
#define EMPTY 0
#define BLACK 1
#define WHITE 2
// 判断是否胜利
int check_win(int board[BOARD_SIZE][BOARD_SIZE], int player) {
// 判断横向是否连成一条线
for (int i = 0; i < BOARD_SIZE; i++) {
int win = 1;
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] != player) {
win = 0;
break;
}
}
if (win) {
return 1;
}
}
// 判断纵向是否连成一条线
for (int j = 0; j < BOARD_SIZE; j++) {
int win = 1;
for (int i = 0; i < BOARD_SIZE; i++) {
if (board[i][j] != player) {
win = 0;
break;
}
}
if (win) {
return 1;
}
}
// 判断对角线是否连成一条线
int win = 1;
for (int i = 0; i < BOARD_SIZE; i++) {
if (board[i][i] != player) {
win = 0;
break;
}
}
if (win) {
return 1;
}
win = 1;
for (int i = 0; i < BOARD_SIZE; i++) {
if (board[i][BOARD_SIZE - 1 - i] != player) {
win = 0;
break;
}
}
if (win) {
return 1;
}
return 0;
}
// 打印棋盘
void print_board(int board[BOARD_SIZE][BOARD_SIZE]) {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == BLACK) {
printf("X");
} else if (board[i][j] == WHITE) {
printf("O");
} else {
printf("-");
}
}
printf("\n");
}
}
int main() {
int board[BOARD_SIZE][BOARD_SIZE];
// 初始化棋盘
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = EMPTY;
}
}
int player = BLACK; // 黑方先手
while (1) {
// 打印当前棋盘
print_board(board);
// 判断当前玩家是否胜利
if (check_win(board, player)) {
printf("%s wins!\n", player == BLACK ? "BLACK" : "WHITE");
break;
}
// 判断是否平局
int full = 1;
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == EMPTY) {
full = 0;
break;
}
}
if (!full) {
break;
}
}
if (full) {
printf("Tie!\n");
break;
}
// 让当前玩家下棋
int row, col;
printf("%s's turn, please enter row and column (1-3): ", player == BLACK ? "BLACK" : "WHITE");
scanf("%d %d", &row, &col);
row--;
col--;
if (row < 0 || row >= BOARD_SIZE || col < 0 || col >= BOARD_SIZE || board[row][col] != EMPTY) {
printf("Invalid move, please try again!\n");
} else {
board[row][col] = player;
player = player == BLACK ? WHITE : BLACK;
}
}
return 0;
}
```
这个程序会不断循环让两个玩家轮流下棋,直到有一方获胜或者平局。在每个回合中,程序会先打印当前的棋盘状态,然后判断当前玩家是否胜利,如果胜利就输出胜利信息并结束游戏,否则判断是否平局,如果平局就输出平局信息并结束游戏,否则让当前玩家输入要下的位置,判断是否合法,如果合法就将棋子放置在棋盘上,并交换玩家。
阅读全文