三子棋、井字棋 -python版本代码-C语言版本代码
原创
一、引言
三子棋,又称井字棋,是一种两人对弈的易懂游戏。本文将提供三子棋游戏的Python和C语言版本的代码实现,帮助读者更好地明白这一经典游戏。
二、Python版本代码
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 5)
def check_winner(board, player):
for row in board:
if all([s == player for s in row]):
return True
for col in range(3):
if all([board[row][col] == player for row in range(3)]):
return True
if all([board[i][i] == player for i in range(3)]) or all([board[i][2 - i] == player for i in range(3)]):
return True
return False
def play():
board = [[" " for _ in range(3)] for _ in range(3)]
current_player = "X"
while True:
print_board(board)
row, col = map(int, input(f"玩家{current_player},请输入行和列(1-3): ").split())
if board[row - 1][col - 1] == " ":
board[row - 1][col - 1] = current_player
if check_winner(board, current_player):
print_board(board)
print(f"玩家{current_player}获胜!")
break
current_player = "O" if current_player == "X" else "X"
else:
print("该位置已被占用,请重新输入。")
if __name__ == "__main__":
play()
三、C语言版本代码
#include <stdio.h>
#include <stdbool.h>
void print_board(char board[3][3]);
bool check_winner(char board[3][3], char player);
void play();
int main() {
play();
return 0;
}
void print_board(char board[3][3]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf(" %c ", board[i][j]);
if (j != 2) {
printf("|");
}
}
printf("");
if (i != 2) {
printf("--- --- ---");
}
}
}
bool check_winner(char board[3][3], char player) {
for (int i = 0; i < 3; i++) {
if (board[i][0] == player && board[i][1] == player && board[i][2] == player) {
return true;
}
if (board[0][i] == player && board[1][i] == player && board[2][i] == player) {
return true;
}
}
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;
}
void play() {
char board[3][3] = {
{' ', ' ', ' '},
{' ', ' ', ' '},
{' ', ' ', ' '}
};
char current_player = 'X';
while (true) {
print_board(board);
int row, col;
printf("玩家%d,请输入行和列(1-3): ", current_player);
scanf("%d %d", &row, &col);
row--; col--;
if (board[row][col] == ' ') {
board[row][col] = current_player;
if (check_winner(board, current_player)) {
print_board(board);
printf("玩家%d获胜!", current_player);
break;
}
current_player = (current_player == 'X') ? 'O' : 'X';
} else {
printf("该位置已被占用,请重新输入。");
}
}
}
四、总结
本文展示了三子