请用Python写个五子棋代码
时间: 2023-11-05 21:38:43 浏览: 65
当然可以!以下是一个简单的五子棋代码示:
```python
# 定义棋盘大小
_SIZE = 15
# 初始化棋盘
board = [[0] * BOARD_SIZE for _ in range(BOARD_SIZE)]
# 定义棋子类型
EMPTY = 0
BLACK = 1
WHITE = 2
# 定义当前下棋方
current_player = BLACK
# 判断是否胜利
def check_win(row, col):
directions = [(1, 0), (0, 1), (1, 1), (1, -1)]
for dx, dy in directions:
count = 1
i, j = row + dx, col + dy
while i >= 0 and i < BOARD_SIZE and j >= 0 and j < BOARD_SIZE and board[i][j] == board[row][col]:
count += 1
i += dx
j += dy
i, j = row - dx, col - dy
while i >= 0 and i < BOARD_SIZE and j >= 0 and j < BOARD_SIZE and board[i][j] == board[row][col]:
count += 1
i -= dx
j -= dy
if count >= 5:
return True
return False
# 下棋函数
def move(row, col):
if row < 0 or row >= BOARD_SIZE or col < 0 or col >= BOARD_SIZE or board[row][col] != EMPTY:
return False
board[row][col] = current_player
if check_win(row, col):
print("黑棋胜" if current_player == BLACK else "白棋胜")
return True
return False
# 游戏循环
while True:
# 打印棋盘
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if board[i][j] == EMPTY:
print("_", end=" ")
elif board[i][j] == BLACK:
print("X", end=" ")
else:
print("O", end=" ")
print()
# 获取玩家输入
row = int(input("请输入行号:"))
col = int(input("请输入列号:"))
# 下棋
if move(row, col):
break
# 切换下棋方
current_player = WHITE if current_player == BLACK else BLACK
```
这是一个简单的五子棋代码,可以在控制台中进行游戏。玩家需要依次输入行号和列号来下棋,程序会判断胜负并打印棋盘。注意,此代码只实现了基本功能,没有考虑规则限制、禁手等高级功能。
阅读全文