普普通通的娱乐程序,技术含量较低。
import numpy as np
class TicTacToe:
def __init__(self):
self.board = np.array([[' ' for _ in range(3)] for _ in range(3)]) # 创建3x3的空棋盘
self.current_player = 'X' # 当前玩家,默认为'X'
self.game_over = False # 游戏是否结束的标志
def print_board(self):
print(self.board)
def make_move(self, row, col):
if self.board[row][col] == ' ':
self.board[row][col] = self.current_player
self.current_player = 'O' if self.current_player == 'X' else 'X' # 切换玩家
else:
print("Invalid move!")
def check_winner(self):
# 检查行
for i in range(3):
if self.board[i][0] == self.board[i][1] == self.board[i][2] != ' ':
return self.board[i][0]
# 检查列
for j in range(3):
if self.board[0][j] == self.board[1][j] == self.board[2][j] != ' ':
return self.board[0][j]
# 检查对角线
if self.board[0][0] == self.board[1][1] == self.board[2][2] != ' ':
return self.board[0][0]
if self.board[0][2] == self.board[1][1] == self.board[2][0] != ' ':
return self.board[0][2]
# 检查平局
if ' ' not in self.board:
return 'Draw'
return None
# 示例使用
game = TicTacToe()
while not game.game_over:
game.print_board()
row = int(input("Enter row: "))
col = int(input("Enter column: "))
game.make_move(row, col)
winner = game.check_winner()
if winner:
print("Winner: ", winner)
game.game_over = True
本文仅为娱乐之作,如有错误欢迎指出。