python五子棋代码
时间: 2023-10-09 21:04:46 浏览: 37
以下是一个简单的 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
self.winner = None
def place(self, row, col):
if self.board[row][col] != 0:
return False
self.board[row][col] = self.current_player
self.check_win(row, col)
self.current_player = 3 - self.current_player
return True
def check_win(self, row, col):
directions = [(0, 1), (1, 0), (1, 1), (1, -1)]
for dx, dy in directions:
count = 1
r, c = row, col
while count < 5 and 0 <= r+dx < BOARD_SIZE and 0 <= c+dy < BOARD_SIZE and self.board[r+dx][c+dy] == self.current_player:
count += 1
r += dx
c += dy
r, c = row, col
while count < 5 and 0 <= r-dx < BOARD_SIZE and 0 <= c-dy < BOARD_SIZE and self.board[r-dx][c-dy] == self.current_player:
count += 1
r -= dx
c -= dy
if count >= 5:
self.winner = self.current_player
def __str__(self):
result = " "
for i in range(BOARD_SIZE):
result += chr(ord('a') + i) + " "
result += "\n"
for i in range(BOARD_SIZE):
result += "{:2d}".format(i+1)
for j in range(BOARD_SIZE):
if self.board[i][j] == 0:
result += " ."
elif self.board[i][j] == 1:
result += " x"
else:
result += " o"
result += "\n"
return result
board = Board()
while board.winner is None:
print(board)
move = input("Player {}'s turn. Enter move (e.g. b3): ".format(board.current_player))
col = ord(move[0]) - ord('a')
row = int(move[1:]) - 1
if not board.place(row, col):
print("Invalid move. Try again.")
print(board)
print("Player {} wins!".format(board.winner))
```
这段代码实现了一个简单的五子棋游戏。运行后,你可以使用命令行输入坐标来下棋。例如,输入 `b3` 表示在第二列第三行下一枚棋子。游戏会自动检查胜利条件并输出胜者。