有Python写五子棋
时间: 2024-02-16 20:31:30 浏览: 139
以下是一个简单的Python五子棋游戏实现:
```python
import numpy as np
ROW = 15 # 棋盘行数
COL = 15 # 棋盘列数
PLAYER1 = 1 # 玩家1用1表示
PLAYER2 = -1 # 玩家2用-1表示
WIN = 5 # 获胜需要连续的棋子数
class Game:
def __init__(self):
self.board = np.zeros((ROW, COL)) # 初始化棋盘
self.player = PLAYER1 # 玩家1先手
self.over = False # 游戏是否结束
def play(self, r, c):
if self.over or self.board[r][c] != 0:
return False # 游戏结束或该位置已经有棋子
self.board[r][c] = self.player # 下棋
self.player = -self.player # 切换玩家
self.over = self.check_win() # 检查是否获胜
return True
def check_win(self):
for r in range(ROW):
for c in range(COL):
if self.check(r, c):
return True
return False
def check(self, r, c):
if self.board[r][c] == 0:
return False
for dr, dc in [(0, 1), (1, 0), (1, 1), (1, -1)]:
if self.check_direction(r, c, dr, dc):
return True
return False
def check_direction(self, r, c, dr, dc):
count = 1
for i in range(1, WIN):
nr, nc = r + i * dr, c + i * dc
if nr < 0 or nr >= ROW or nc < 0 or nc >= COL or self.board[nr][nc] != self.board[r][c]:
break
count += 1
for i in range(1, WIN):
nr, nc = r - i * dr, c - i * dc
if nr < 0 or nr >= ROW or nc < 0 or nc >= COL or self.board[nr][nc] != self.board[r][c]:
break
count += 1
return count >= WIN
def print_board(self):
print(" ", end="")
for c in range(COL):
print(chr(ord('a') + c), end=" ")
print()
for r in range(ROW):
print("{:2d}".format(r + 1), end=" ")
for c in range(COL):
if self.board[r][c] == PLAYER1:
print("o", end=" ")
elif self.board[r][c] == PLAYER2:
print("x", end=" ")
else:
print(".", end=" ")
print()
def get_board(self):
return self.board
def get_player(self):
return self.player
def is_over(self):
return self.over
```
该游戏使用numpy库实现了一个二维数组作为棋盘,其中0代表空位置,1代表玩家1的棋子,-1代表玩家2的棋子。该游戏实现了下棋、切换玩家、检查获胜等功能,并且可以输出当前棋盘状态。可以使用以下代码测试该游戏:
```python
game = Game()
while not game.is_over():
game.print_board()
player = "o" if game.get_player() == PLAYER1 else "x"
print("现在是{}玩家的回合".format(player))
pos = input("请输入你要下棋的位置,如a1:")
c = ord(pos[0]) - ord('a')
r = int(pos[1:]) - 1
if game.play(r, c):
print("玩家{}在{}下了一颗棋".format(player, pos))
else:
print("请重新输入")
game.print_board()
winner = "o" if game.get_player() == PLAYER2 else "x"
print("游戏结束,玩家{}获胜".format(winner))
```
阅读全文