提供五子棋的代码
时间: 2023-07-03 19:14:17 浏览: 60
以下是 Python 实现的五子棋代码:
```python
import numpy as np
class Board:
def __init__(self, size):
self.size = size
self.board = np.zeros((size, size), dtype=int)
self.current_player = 1
def play(self, row, col):
if self.board[row][col] != 0:
return False
self.board[row][col] = self.current_player
self.current_player = -self.current_player
return True
def check_win(self):
for i in range(self.size):
for j in range(self.size):
if self.board[i][j] == 0:
continue
if j + 4 < self.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]:
return self.board[i][j]
if i + 4 < self.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]:
return self.board[i][j]
if i + 4 < self.size and j + 4 < self.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]:
return self.board[i][j]
if i + 4 < self.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]:
return self.board[i][j]
return 0
```
这里我们使用了 numpy 库来生成棋盘的数组,其中 `self.size` 表示棋盘大小,`self.board` 表示当前的棋盘状态,`self.current_player` 表示当前下棋玩家。在 `play` 方法中,我们判断当前位置是否为空,如果为空,则放置当前玩家的棋子,并切换下一个玩家。在 `check_win` 方法中,我们遍历整个棋盘,判断是否存在五子连珠的情况,如果存在,则返回胜利的玩家。如果棋盘已满且没有找到胜利的玩家,则返回 0 表示平局。
阅读全文