实现过程
类TicTacToe的构造函数__init__()初始化棋盘board和当前玩家current_player。
- print_board()方法用于打印当前的棋盘。
- make_move(row, col)方法用于让当前玩家落子。
- check_win()方法用于检查胜负。
- play()方法是整个游戏的主流程,其中包括打印欢迎信息、打印当前的棋盘、让当前玩家落子、检查胜负等步骤。在游戏结束后会打印出结果。最后,创建一个TicTacToe对象并调用play()方法开始游戏。
class TicTacToe:
def __init__(self):
self.board = [[' ' for _ in range(3)] for _ in range(3)]
self.current_player = 'X'
def print_board(self):
for row in self.board:
print('|'.join(row))
print('-' * 5)
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("该位置已经被占据,请重新选择!")
def check_win(self):
# 检查行
for row in self.board:
if row[0] == row[1] == row[2] != ' ':
return True
# 检查列
for col in range(3):
if self.board[0][col] == self.board[1][col] == self.board[2][col] != ' ':
return True
# 检查对角线
if self.board[0][0] == self.board[1][1] == self.board[2][2] != ' ':
return True
if self.board[0][2] == self.board[1][1] == self.board[2][0] != ' ':
return True
return False
def play(self):
print("欢迎来到井字棋游戏!")
print("玩家 X 先开始。")
print("输入行和列的编号来选择位置(0-2)")
while True:
self.print_board()
row = int(input("请输入行号:"))
col = int(input("请输入列号:"))
self.make_move(row, col)
if self.check_win():
self.print_board()
print(f"玩家 {self.current_player} 获胜!")
break
if all(self.board[i][j] != ' ' for i in range(3) for j in range(3)):
self.print_board()
print("平局!")
break
# 创建游戏对象并开始游戏
game = TicTacToe()
game.play()