python五子棋
时间: 2023-06-22 16:15:58 浏览: 49
好的,我可以为您提供一个简单的 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 move(self, x, y):
if self.board[x][y] != EMPTY:
return False
self.board[x][y] = self.current_player
self.current_player = WHITE if self.current_player == BLACK else BLACK
return True
def is_win(self):
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if self.board[i][j] == EMPTY:
continue
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]:
return True
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]:
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]:
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]:
return True
return False
def __str__(self):
res = ' '
for i in range(BOARD_SIZE):
res += chr(ord('a')+i) + ' '
res += '\n'
for i in range(BOARD_SIZE):
res += str(i+1) + ' '
for j in range(BOARD_SIZE):
if self.board[i][j] == EMPTY:
res += '· '
elif self.board[i][j] == BLACK:
res += '● '
else:
res += '○ '
res += str(i+1) + '\n'
res += ' '
for i in range(BOARD_SIZE):
res += chr(ord('a')+i) + ' '
return res
if __name__ == '__main__':
board = Board()
while True:
print(board)
if board.is_win():
print('游戏结束,%s方获胜!' % ('黑' if board.current_player == WHITE else '白'))
break
print('%s方落子:' % ('黑' if board.current_player == BLACK else '白'))
try:
x, y = input().strip().lower()
x = ord(x) - ord('a')
y = int(y) - 1
except:
print('请输入正确的坐标!')
continue
if x < 0 or x >= BOARD_SIZE or y < 0 or y >= BOARD_SIZE:
print('坐标超出范围!')
continue
if board.move(x, y):
print('落子成功!')
else:
print('此处已有棋子!')
```
这个 Python 五子棋游戏示例中,我们使用了 Python 的 numpy 库来表示棋盘,并定义了棋子的三种状态:空、黑、白。我们可以通过 `Board` 类来进行游戏的操作,包括落子、判断胜负等等。在 `__main__` 函数中,我们可以通过输入坐标来落子,游戏结束后会输出胜出方。