devc++ c语言井字棋
时间: 2023-07-15 10:12:35 浏览: 111
c语言井字棋
好的,我可以为您提供一个简单的 C 语言井字棋游戏,使用 Dev-C++ 编写:
```c
#include <stdio.h>
#include <stdlib.h>
char board[3][3]; // 存放棋盘状态的二维数组
void init_board(); // 初始化棋盘
void print_board(); // 打印棋盘
int check_win(char); // 检查是否获胜
int check_full(); // 检查是否棋盘已满
int main()
{
char player = 'X'; // 玩家先手,使用 X 表示
int row, col;
init_board(); // 初始化棋盘
print_board(); // 打印棋盘
while (1) {
printf("Player %c, enter row and column: ", player);
scanf("%d %d", &row, &col);
if (row < 1 || row > 3 || col < 1 || col > 3) { // 判断输入是否合法
printf("Invalid input! Please enter again.\n");
continue;
}
if (board[row-1][col-1] != ' ') { // 判断该位置是否已经有棋子
printf("This place has been occupied! Please enter again.\n");
continue;
}
board[row-1][col-1] = player; // 在该位置放置棋子
print_board(); // 打印棋盘
if (check_win(player)) { // 判断玩家是否获胜
printf("Player %c wins!\n", player);
break;
}
if (check_full()) { // 判断棋盘是否已满
printf("The game is draw!\n");
break;
}
player = (player == 'X') ? 'O' : 'X'; // 切换玩家
}
return 0;
}
void init_board()
{
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
board[i][j] = ' ';
}
}
}
void print_board()
{
int i, j;
printf(" 1 2 3\n");
for (i = 0; i < 3; i++) {
printf("%d ", i+1);
for (j = 0; j < 3; j++) {
printf("%c", board[i][j]);
if (j != 2) {
printf("|");
}
}
printf("\n");
if (i != 2) {
printf(" -----\n");
}
}
}
int check_win(char player)
{
int i, j;
for (i = 0; i < 3; i++) {
if (board[i][0] == player && board[i][1] == player && board[i][2] == player) { // 检查行
return 1;
}
if (board[0][i] == player && board[1][i] == player && board[2][i] == 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;
}
return 0;
}
int check_full()
{
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
if (board[i][j] == ' ') { // 只要有一个空格,就说明棋盘未满
return 0;
}
}
}
return 1;
}
```
这个程序实现了一个简单的井字棋游戏,可以在 Dev-C++ 中编译并运行。
阅读全文