用python代码写五子棋游戏
时间: 2023-05-25 09:00:49 浏览: 85
python实现五子棋游戏
好的,以下是实现五子棋游戏的Python代码:
```python
import numpy as np
BOARD_SIZE = 15
EMPTY = 0
PLAYER_X = 1
PLAYER_O = 2
WIN_N = 5
class GameState:
def __init__(self):
self.board = np.zeros((BOARD_SIZE, BOARD_SIZE), dtype=int)
self.current_player = PLAYER_X
self.winner = None
self.is_ended = False
def get_valid_moves(self):
return np.transpose(np.where(self.board == EMPTY))
def move(self, point):
if self.is_ended:
raise ValueError("Game has already ended.")
if self.board[point[0], point[1]] != EMPTY:
raise ValueError(f"Invalid move: {point}")
self.board[point[0], point[1]] = self.current_player
self._check_win()
if self.winner is not None:
self.is_ended = True
else:
self.current_player = PLAYER_O if self.current_player == PLAYER_X else PLAYER_X
def _check_win(self):
for r in range(BOARD_SIZE):
for c in range(BOARD_SIZE):
if self.board[r, c] == EMPTY:
continue
if c + WIN_N <= BOARD_SIZE and np.all(self.board[r, c:c + WIN_N] == self.board[r, c]):
self.winner = self.current_player
if r + WIN_N <= BOARD_SIZE and np.all(self.board[r:r + WIN_N, c] == self.board[r, c]):
self.winner = self.current_player
if c + WIN_N <= BOARD_SIZE and r + WIN_N <= BOARD_SIZE and \
np.all(self.board[r:r + WIN_N, c:c + WIN_N].diagonal() == self.board[r, c]):
self.winner = self.current_player
if c >= WIN_N - 1 and r + WIN_N <= BOARD_SIZE and \
np.all(np.fliplr(self.board[r:r + WIN_N, c - WIN_N + 1:c + 1]).diagonal() == self.board[r, c]):
self.winner = self.current_player
if __name__ == '__main__':
game = GameState()
while not game.is_ended:
print(game.board)
valid_moves = game.get_valid_moves()
print(f"Valid moves: {valid_moves}")
player_input = input(f"Player {game.current_player}, enter move (row, col): ")
move = tuple(map(int, player_input.split(',')))
game.move(move)
print(f"Game is over. Winner: {game.winner}")
```
这个代码实现了一个基本的五子棋游戏,可以在命令行运行。首先创建一个 `GameState` 实例,用它来管理游戏状态。`board` 属性是一个二维数组,代表棋盘状态;`current_player` 属性记录当前轮到哪个玩家下棋;`winner` 属性记录赢家,如果游戏还没有结束则为 `None`;`is_ended` 属性记录游戏是否结束。`get_valid_moves` 方法返回一个二维数组,包含了当前能够下的合法位置。`move` 方法用于让当前玩家下棋,它会检查游戏状态是否合法,并且判断是否有任何一方已经获胜,如果有则将 `winner` 标记为赢家,将 `is_ended` 设为 `True`。最后在主循环中不断打印棋盘状态和合法位置,接收用户输入下棋位置,并更新游戏状态,直到游戏结束。
阅读全文