```python
class TicTacToe:
def __init__(self):
self.board = [' ' for _ in range(9)] 初始化游戏棋盘
self.current_player = 'X' 当前玩家,初始为X
def print_board(self):
for i in range(0, 9, 3):
print(self.board[i], '|', self.board[i+1], '|', self.board[i+2])
if i != 6:
print('-' * 5)
def make_move(self, position):
if self.board[position] == ' ':
self.board[position] = self.current_player 在棋盘上放置当前玩家的棋子
self.current_player = 'O' if self.current_player == 'X' else 'X' 切换当前玩家
else:
print('Invalid move! Please choose an empty position.')
def check_winner(self):
判断是否有玩家胜利
win_patterns = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]
for pattern in win_patterns:
if all([self.board[i] == self.current_player for i in pattern]):
return True
return False
主程序
def main():
game = TicTacToe()
while True:
game.print_board()
game.make_move(int(input("玩家 {},请输入位置 (1-9): ".format(game.current_player))))
if game.check_winner():
game.print_board()
print("玩家 {} 获胜!".format(game.current_player))
break
if ' ' not in game.board:
print("平局!")
break
game.current_player = 'O' if game.current_player == 'X' else 'X'
if __name__ == "__main__":
main()
```
代码说明:
初始化棋盘:
使用一个长度为9的列表来表示3x3的棋盘,每个位置初始化为空格。
打印棋盘:
通过循环打印棋盘的每一行。
玩家移动:
获取玩家输入的位置,并在棋盘上放置相应玩家的棋子,同时切换当前玩家。
检查胜利:
通过检查所有可能的胜利模式来判断是否有玩家获胜。
主程序:
循环进行游戏,直到有玩家获胜或棋盘填满。
你可以根据需要修改和扩展这个示例代码,例如添加电脑玩家、记录游戏历史等。