编写五子棋的完整python代码_python实现五子棋程序
时间: 2023-07-23 12:12:10 浏览: 89
好的,下面是五子棋的完整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
# 切换玩家
def switch_player(self):
self.current_player = WHITE if self.current_player == BLACK else BLACK
# 落子
def move(self, x, y):
if self.board[x][y] == EMPTY:
self.board[x][y] = self.current_player
return True
else:
return False
# 检查是否五子连珠
def check_win(self, x, y):
current = self.board[x][y]
count = 0
# 横向检查
for i in range(max(0, y - 4), min(BOARD_SIZE, y + 5)):
if self.board[x][i] == current:
count += 1
if count == 5:
return True
else:
count = 0
# 竖向检查
count = 0
for i in range(max(0, x - 4), min(BOARD_SIZE, x + 5)):
if self.board[i][y] == current:
count += 1
if count == 5:
return True
else:
count = 0
# 左上到右下检查
count = 0
for i, j in zip(range(max(0, x - 4), min(BOARD_SIZE, x + 5)),
range(max(0, y - 4), min(BOARD_SIZE, y + 5))):
if self.board[i][j] == current:
count += 1
if count == 5:
return True
else:
count = 0
# 左下到右上检查
count = 0
for i, j in zip(range(max(0, x - 4), min(BOARD_SIZE, x + 5)),
range(min(BOARD_SIZE - 1, y + 4), max(-1, y - 5), -1)):
if self.board[i][j] == current:
count += 1
if count == 5:
return True
else:
count = 0
return False
# 判断是否结束
def is_game_over(self):
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if self.board[i][j] != EMPTY:
if self.check_win(i, j):
return True
return False
# 打印棋盘
def show_board(self):
print(' ' + ''.join([str(i) for i in range(BOARD_SIZE)]))
for i in range(BOARD_SIZE):
print(str(i) + ''.join(['.' if self.board[i][j] == EMPTY else 'B' if self.board[i][j] == BLACK else 'W' for j in range(BOARD_SIZE)]))
```
以上就是五子棋的完整Python代码实现,你可以在此基础上进行修改和优化。