用python代码实现五子棋
时间: 2023-11-19 09:10:39 浏览: 82
python实现五子棋人机对战游戏
好的,以下是Python实现五子棋的代码:
```
import numpy as np
# 定义棋盘大小
BOARD_SIZE = 15
class Board:
def __init__(self):
self.board = np.zeros([BOARD_SIZE, BOARD_SIZE], dtype=np.int8)
self.current_player = 1
def play(self, x, y):
# 判断当前位置是否为空
if self.board[x, y] != 0:
return False
# 落子
self.board[x, y] = self.current_player
# 检查胜利情况
if self.check_win(x, y):
return True
# 切换玩家
self.current_player = 3 - self.current_player
return False
def check_win(self, x, y):
# 检查行
for i in range(max(0, x - 4), min(BOARD_SIZE, x + 5)):
if np.all(self.board[i:i+5, y] == self.current_player):
return True
# 检查列
for i in range(max(0, y - 4), min(BOARD_SIZE, y + 5)):
if np.all(self.board[x, i:i+5] == self.current_player):
return True
# 检查正斜线
for i in range(max(x - 4, 0), min(BOARD_SIZE - 4, x + 1)):
j = y - x + i
if np.all(self.board[i:i+5, j:j+5].diagonal() == self.current_player):
return True
# 检查反斜线
for i in range(max(x - 4, 0), min(BOARD_SIZE - 4, x + 1)):
j = y + x - i
if np.all(np.fliplr(self.board[i:i+5, j-4:j+1]).diagonal() == self.current_player):
return True
return False
def __str__(self):
pieces = {1: '●', 2: '○', 0: ' '}
lines = [' '.join(pieces[x] for x in row) for row in self.board]
row_numbers = ['%2d' % i for i in range(1, BOARD_SIZE + 1)]
return '\n'.join([''] + row_numbers + [''] + lines + [''])
if __name__ == '__main__':
board = Board()
print(board)
while True:
# 玩家落子
x, y = input('请落子,格式为 x,y:').split(',')
x, y = int(x) - 1, int(y) - 1
if board.play(x, y):
print('玩家胜利!')
break
print(board)
# AI落子
empty_x, empty_y = np.where(board.board == 0)
scores = np.zeros([BOARD_SIZE, BOARD_SIZE], dtype=np.int32)
for i, j in zip(empty_x, empty_y):
for k in range(2):
board.board[i, j] = k + 1
if board.check_win(i, j):
scores[i, j] += 1000 if board.current_player == k + 1 else -1000
else:
scores[i, j] += np.sum(scores[max(0, i-2):min(i+3, BOARD_SIZE), max(0, j-2):min(j+3, BOARD_SIZE)])
board.board[i, j] = 0
best_move = np.unravel_index(np.argmax(scores), [BOARD_SIZE, BOARD_SIZE])
print('AI 落子:', best_move)
if board.play(*best_move):
print('AI胜利!')
break
print(board)
```
阅读全文