用C语言写一个三子棋游戏
时间: 2023-12-19 20:04:46 浏览: 28
好的,下面是一个简单的三子棋游戏的代码,仅供参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define SIZE 3
void initialize_board(char board[][SIZE]);
void display_board(char board[][SIZE]);
bool check_win(char board[][SIZE], char player);
bool check_tie(char board[][SIZE]);
int main(void)
{
char board[SIZE][SIZE];
char player = 'X';
int row, col;
bool win = false;
bool tie = false;
initialize_board(board);
do {
display_board(board);
printf("Player %c's turn.\n", player);
do {
printf("Enter row (1-3): ");
scanf("%d", &row);
printf("Enter column (1-3): ");
scanf("%d", &col);
} while (board[row-1][col-1] != ' ');
board[row-1][col-1] = player;
win = check_win(board, player);
tie = check_tie(board);
if (win) {
printf("Player %c wins!\n", player);
display_board(board);
break;
}
if (tie) {
printf("It's a tie!\n");
display_board(board);
break;
}
player = (player == 'X') ? 'O' : 'X';
} while (!win && !tie);
return 0;
}
void initialize_board(char board[][SIZE])
{
int i, j;
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
board[i][j] = ' ';
}
}
}
void display_board(char board[][SIZE])
{
int i, j;
printf("\n");
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
printf(" %c ", board[i][j]);
if (j < SIZE - 1) {
printf("|");
}
}
printf("\n");
if (i < SIZE - 1) {
printf("---+---+---\n");
}
}
printf("\n");
}
bool check_win(char board[][SIZE], char player)
{
int i;
// check rows
for (i = 0; i < SIZE; i++) {
if (board[i][0] == player && board[i][1] == player && board[i][2] == player) {
return true;
}
}
// check columns
for (i = 0; i < SIZE; i++) {
if (board[0][i] == player && board[1][i] == player && board[2][i] == player) {
return true;
}
}
// check diagonals
if (board[0][0] == player && board[1][1] == player && board[2][2] == player) {
return true;
}
if (board[0][2] == player && board[1][1] == player && board[2][0] == player) {
return true;
}
return false;
}
bool check_tie(char board[][SIZE])
{
int i, j;
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
if (board[i][j] == ' ') {
return false;
}
}
}
return true;
}
```
这个代码实现了一个简单的三子棋游戏,玩家可以选择行列下棋,程序会自动判断胜负和平局。需要注意的是,这个代码没有实现人机对战,只能让两个人玩。