用python写一个五子棋
时间: 2023-07-18 13:45:28 浏览: 50
好的,以下是一个简单的 Python 五子棋代码示例:
```python
import numpy as np
# 棋盘大小
BOARD_SIZE = 15
# 棋盘数组
board = np.zeros((BOARD_SIZE, BOARD_SIZE), dtype=int)
# 玩家
BLACK = 1
WHITE = -1
# 当前玩家
current_player = BLACK
# 判断是否能落子
def is_valid_move(row, col):
if row < 0 or row >= BOARD_SIZE or col < 0 or col >= BOARD_SIZE:
return False
if board[row][col] != 0:
return False
return True
# 落子
def play_move(row, col):
global current_player
if is_valid_move(row, col):
board[row][col] = current_player
current_player = -current_player
return True
else:
return False
# 判断胜负
def check_win():
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if board[i][j] == 0:
continue
if j + 4 < BOARD_SIZE and board[i][j] == board[i][j+1] == board[i][j+2] == board[i][j+3] == board[i][j+4]:
return board[i][j]
if i + 4 < BOARD_SIZE and board[i][j] == board[i+1][j] == board[i+2][j] == board[i+3][j] == board[i+4][j]:
return board[i][j]
if i + 4 < BOARD_SIZE and j + 4 < BOARD_SIZE and board[i][j] == board[i+1][j+1] == board[i+2][j+2] == board[i+3][j+3] == board[i+4][j+4]:
return board[i][j]
if i + 4 < BOARD_SIZE and j - 4 >= 0 and board[i][j] == board[i+1][j-1] == board[i+2][j-2] == board[i+3][j-3] == board[i+4][j-4]:
return board[i][j]
return 0
# 打印棋盘
def print_board():
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if board[i][j] == BLACK:
print('●', end=' ')
elif board[i][j] == WHITE:
print('○', end=' ')
else:
print('+', end=' ')
print()
# 游戏循环
while True:
print_board()
row = int(input("请输入行数:"))
col = int(input("请输入列数:"))
if play_move(row, col):
result = check_win()
if result == BLACK:
print("黑方胜利!")
break
elif result == WHITE:
print("白方胜利!")
break
else:
print("输入有误,请重新输入!")
```
以上代码使用 numpy 数组实现了五子棋的落子、判断胜负等功能,游戏循环中通过输入行数和列数来进行落子。你可以根据自己的需要进行修改和扩展。
阅读全文