From 4707562a43920c4cb6605b017d5bdb8a259106cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=A8=E4=BA=95=E6=BA=90?= <2692463272.@example.com> Date: Sun, 28 Sep 2025 19:58:30 +0800 Subject: [PATCH] wuziqi1.py --- wuziqi1.py | 100 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 wuziqi1.py diff --git a/wuziqi1.py b/wuziqi1.py new file mode 100644 index 0000000..d960442 --- /dev/null +++ b/wuziqi1.py @@ -0,0 +1,100 @@ +# wuziqi.py +class WuziqiGame: + def __init__(self, board_size=15): + self.board_size = board_size + self.board = [['-' for _ in range(board_size)] for _ in range(board_size)] + self.current_player = 'X' + + def print_board(self): + """打印棋盘""" + print(' ', end='') + for i in range(self.board_size): + print(f'{i:2}', end='') + print() + + for i in range(self.board_size): + print(f'{i:2}', end='') + for j in range(self.board_size): + print(f' {self.board[i][j]}', end='') + print() + + def make_move(self, row, col): + """下棋""" + if 0 <= row < self.board_size and 0 <= col < self.board_size: + if self.board[row][col] == '-': + self.board[row][col] = self.current_player + if self.check_win(row, col): + print(f"玩家 {self.current_player} 获胜!") + return True + self.current_player = 'O' if self.current_player == 'X' else 'X' + return False + else: + print("该位置已有棋子!") + return False + else: + print("位置超出棋盘范围!") + return False + + def check_win(self, row, col): + """检查是否获胜""" + directions = [ + [(0, 1), (0, -1)], # 水平 + [(1, 0), (-1, 0)], # 垂直 + [(1, 1), (-1, -1)], # 主对角线 + [(1, -1), (-1, 1)] # 副对角线 + ] + + player = self.board[row][col] + + for direction_pair in directions: + count = 1 # 当前位置已经有一个棋子 + + # 检查每个方向的两个相反方向 + for dx, dy in direction_pair: + temp_row, temp_col = row, col + + # 沿着一个方向检查连续的棋子 + for _ in range(4): + temp_row += dx + temp_col += dy + + if (0 <= temp_row < self.board_size and + 0 <= temp_col < self.board_size and + self.board[temp_row][temp_col] == player): + count += 1 + else: + break + + if count >= 5: + return True + + return False + +def main(): + """主函数""" + game = WuziqiGame() + + print("欢迎来到五子棋游戏!") + print("玩家X先手,玩家O后手") + print("输入行号和列号来下棋(0-14)") + + while True: + game.print_board() + print(f"当前玩家: {game.current_player}") + + try: + row = int(input("请输入行号: ")) + col = int(input("请输入列号: ")) + + if game.make_move(row, col): + game.print_board() + break + + except ValueError: + print("请输入有效的数字!") + except KeyboardInterrupt: + print("\n游戏结束!") + break + +if __name__ == "__main__": + main() \ No newline at end of file