72 lines
2.4 KiB
Python
72 lines
2.4 KiB
Python
import random
|
|
from typing import Optional
|
|
|
|
class TicTacToeGame:
|
|
def __init__(self):
|
|
self.board = [" "] * 9
|
|
self.player_symbol = "X"
|
|
self.computer_symbol = "O"
|
|
self.current_player = "X" # X先走
|
|
|
|
def print_board(self) -> str:
|
|
"""返回棋盘字符串"""
|
|
board_str = (
|
|
f"\n {self.board[0]} | {self.board[1]} | {self.board[2]} \n"
|
|
"-----------\n"
|
|
f" {self.board[3]} | {self.board[4]} | {self.board[5]} \n"
|
|
"-----------\n"
|
|
f" {self.board[6]} | {self.board[7]} | {self.board[8]} \n"
|
|
)
|
|
return board_str
|
|
|
|
def check_winner(self) -> Optional[str]:
|
|
"""检查是否有玩家获胜"""
|
|
win_combinations = [
|
|
[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 combo in win_combinations:
|
|
if self.board[combo[0]] == self.board[combo[1]] == self.board[combo[2]] != " ":
|
|
return self.board[combo[0]]
|
|
return None
|
|
|
|
def is_board_full(self) -> bool:
|
|
"""检查棋盘是否已满"""
|
|
return " " not in self.board
|
|
|
|
def computer_move(self) -> int:
|
|
"""电脑AI移动"""
|
|
for i in range(9):
|
|
if self.board[i] == " ":
|
|
self.board[i] = self.computer_symbol
|
|
if self.check_winner() == self.computer_symbol:
|
|
return i
|
|
self.board[i] = " "
|
|
|
|
for i in range(9):
|
|
if self.board[i] == " ":
|
|
self.board[i] = self.player_symbol
|
|
if self.check_winner() == self.player_symbol:
|
|
self.board[i] = self.computer_symbol
|
|
return i
|
|
self.board[i] = " "
|
|
|
|
move_order = [4, 0, 2, 6, 8, 1, 3, 5, 7]
|
|
for move in move_order:
|
|
if self.board[move] == " ":
|
|
return move
|
|
|
|
return -1
|
|
|
|
def make_move(self, position: int) -> bool:
|
|
"""玩家移动"""
|
|
if 0 <= position <= 8 and self.board[position] == " ":
|
|
self.board[position] = self.current_player
|
|
return True
|
|
return False
|
|
|
|
def switch_player(self):
|
|
"""切换当前玩家"""
|
|
self.current_player = "O" if self.current_player == "X" else "X" |