p ython五子棋游戏代码
时间: 2023-07-09 18:44:46 浏览: 87
以下是一个简单的 Python 五子棋游戏代码示例:
```python
import numpy as np
# 定义棋盘大小
BOARD_SIZE = 15
# 定义棋子类型
EMPTY = 0
BLACK = 1
WHITE = 2
class Board:
def __init__(self):
self.board = np.zeros((BOARD_SIZE, BOARD_SIZE), dtype=np.int8)
self.current_player = BLACK
self.game_over = False
def get_valid_moves(self):
valid_moves = []
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if self.board[i][j] == EMPTY:
valid_moves.append((i, j))
return valid_moves
def place(self, move):
if self.board[move[0]][move[1]] != EMPTY:
return False
self.board[move[0]][move[1]] = self.current_player
self.current_player = BLACK if self.current_player == WHITE else WHITE
return True
def is_game_over(self):
# 判断是否有一方连成五子
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if self.board[i][j] == EMPTY:
continue
if i + 4 < BOARD_SIZE and \
self.board[i][j] == self.board[i+1][j] == self.board[i+2][j] == self.board[i+3][j] == self.board[i+4][j]:
self.game_over = True
return True
if j + 4 < BOARD_SIZE and \
self.board[i][j] == self.board[i][j+1] == self.board[i][j+2] == self.board[i][j+3] == self.board[i][j+4]:
self.game_over = True
return True
if i + 4 < BOARD_SIZE and j + 4 < BOARD_SIZE and \
self.board[i][j] == self.board[i+1][j+1] == self.board[i+2][j+2] == self.board[i+3][j+3] == self.board[i+4][j+4]:
self.game_over = True
return True
if i + 4 < BOARD_SIZE and j - 4 >= 0 and \
self.board[i][j] == self.board[i+1][j-1] == self.board[i+2][j-2] == self.board[i+3][j-3] == self.board[i+4][j-4]:
self.game_over = True
return True
# 判断是否平局
if len(self.get_valid_moves()) == 0:
self.game_over = True
return True
return False
```
这个代码定义了一个 `Board` 类,表示五子棋棋盘。其中,`get_valid_moves` 方法返回当前可以下棋的位置列表,`place` 方法用于在棋盘上放置棋子,`is_game_over` 方法用于判断游戏是否结束。
你可以使用这个类来开发一个简单的五子棋游戏。
阅读全文