python井字棋小游戏代码不要pygame
时间: 2024-06-15 22:01:35 浏览: 210
当然,我可以帮你概述一个简单的Python井字棋(Tic Tac Toe)游戏代码的基本结构,不使用pygame库。我们将用基本的控制台界面和内置函数来实现。首先,我们需要定义一个`Board`类,用于存储棋盘状态和进行操作。这里是一个简化版的实现:
```python
class Board:
def __init__(self):
self.board = [' ' for _ in range(9)]
self.current_player = 'X'
def print_board(self):
for i in range(3):
print(self.board[i*3:i*3+3])
def make_move(self, row, col):
if self.board[row*3 + col] == ' ':
self.board[row*3 + col] = self.current_player
self.current_player = 'O' if self.current_player == 'X' else 'X'
else:
print("Position is already taken.")
def check_win(self):
# 检查行、列和两个对角线是否有一方获胜
for i in range(9):
if self.board[i:i+3] == ['X'] * 3 or self.board[i::3] == ['X'] * 3:
return True
if self.board[0:3] == ['X'] * 3 or self.board[3:6] == ['X'] * 3 or self.board[6:9] == ['X'] * 3:
return True
if self.board == 'X' and self.board == 'X' and self.board == 'X':
return True
if self.board == 'X' and self.board == 'X' and self.board == 'X':
return True
return False
# 游戏主循环
def play_tictactoe():
board = Board()
while not board.check_win():
board.print_board()
row = int(input("Player X, enter row (1-3): "))
col = int(input("Player X, enter column (1-3): "))
board.make_move(row - 1, col - 1)
if board.check_win():
break
if board.check_win():
print(f"Player {board.current_player} wins!")
else:
print("It's a tie!")
play_tictactoe()
```
阅读全文