用Python写五子棋的代码
时间: 2024-03-28 16:17:22 浏览: 66
好的,下面是一个简单的五子棋代码示例:
```python
import numpy as np
# 定义棋盘大小
BOARD_SIZE = 15
class Board:
"""五子棋棋盘类"""
def __init__(self):
self.board = np.zeros((BOARD_SIZE, BOARD_SIZE), dtype=int) # 初始化棋盘
self.player = 1 # 当前玩家,1为黑方,2为白方
def move(self, x, y):
"""在棋盘上落子"""
if self.board[x][y] != 0:
return False # 该位置已经有棋子
self.board[x][y] = self.player # 落子
return True
def switch_player(self):
"""切换玩家"""
if self.player == 1:
self.player = 2
else:
self.player = 1
def check_win(self, x, y):
"""检查是否获胜"""
def check_direction(dx, dy):
"""检查某个方向是否连成五子"""
count = 1 # 计数器
i, j = x, y
while i + dx >= 0 and i + dx < BOARD_SIZE and j + dy >= 0 and j + dy < BOARD_SIZE and self.board[i + dx][j + dy] == self.player:
count += 1
i += dx
j += dy
i, j = x, y
while i - dx >= 0 and i - dx < BOARD_SIZE and j - dy >= 0 and j - dy < BOARD_SIZE and self.board[i - dx][j - dy] == self.player:
count += 1
i -= dx
j -= dy
return count >= 5
# 检查四个方向是否连成五子
if check_direction(0, 1) or check_direction(1, 0) or check_direction(1, 1) or check_direction(1, -1):
return True
else:
return False
def show(self):
"""显示棋盘"""
print(" ", end="")
for i in range(BOARD_SIZE):
print(chr(ord('a') + i), end=" ")
print()
for i in range(BOARD_SIZE):
print(i + 1, end=" ")
for j in range(BOARD_SIZE):
if self.board[i][j] == 0:
print("+", end=" ")
elif self.board[i][j] == 1:
print("*", end=" ")
else:
print("O", end=" ")
print()
def main():
board = Board()
while True:
board.show()
x = input("请输入落子位置,如a1:")
y = int(x[1:]) - 1
x = ord(x[0]) - ord('a')
if not board.move(y, x):
print("该位置已有棋子,请重新输入!")
continue
if board.check_win(y, x):
board.show()
print("恭喜玩家{}获胜!".format(board.player))
break
board.switch_player()
if __name__ == '__main__':
main()
```
这个代码实现了一个简单的五子棋游戏,玩家通过输入坐标来在棋盘上落子,每落完一次子就切换玩家。当某个玩家在横、竖、斜方向上连成五子时,游戏结束,该玩家获胜。
阅读全文