五子棋程序代码python
时间: 2023-08-21 08:16:24 浏览: 137
当然!以下是一个简单的五子棋程序的 Python 代码示例:
```python
import numpy as np
# 定义棋盘大小
BOARD_SIZE = 15
# 定义棋盘状态
EMPTY = 0
BLACK = 1
WHITE = 2
# 创建一个空棋盘
board = np.zeros((BOARD_SIZE, BOARD_SIZE))
# 判断是否在棋盘内
def is_valid_move(x, y):
return x >= 0 and x < BOARD_SIZE and y >= 0 and y < BOARD_SIZE
# 判断是否胜利
def is_win(move):
x, y = move
# 水平方向
count = 1
for i in range(1, 5):
if is_valid_move(x+i, y) and board[x+i, y] == board[x, y]:
count += 1
else:
break
for i in range(1, 5):
if is_valid_move(x-i, y) and board[x-i, y] == board[x, y]:
count += 1
else:
break
if count >= 5:
return True
# 垂直方向
count = 1
for i in range(1, 5):
if is_valid_move(x, y+i) and board[x, y+i] == board[x, y]:
count += 1
else:
break
for i in range(1, 5):
if is_valid_move(x, y-i) and board[x, y-i] == board[x, y]:
count += 1
else:
break
if count >= 5:
return True
# 正斜方向
count = 1
for i in range(1, 5):
if is_valid_move(x+i, y+i) and board[x+i, y+i] == board[x, y]:
count += 1
else:
break
for i in range(1, 5):
if is_valid_move(x-i, y-i) and board[x-i, y-i] == board[x, y]:
count += 1
else:
break
if count >= 5:
return True
# 反斜方向
count = 1
for i in range(1, 5):
if is_valid_move(x-i, y+i) and board[x-i, y+i] == board[x, y]:
count += 1
else:
break
for i in range(1, 5):
if is_valid_move(x+i, y-i) and board[x+i, y-i] == board[x, y]:
count += 1
else:
break
if count >= 5:
return True
return False
# 主循环
def main():
player = BLACK
while True:
# 打印棋盘
print(board)
# 玩家下棋
if player == BLACK:
move = input("请输入您的落子位置,格式为x,y:")
x, y = map(int, move.split(','))
if is_valid_move(x, y) and board[x, y] == EMPTY:
board[x, y] = BLACK
if is_win((x, y)):
print("黑棋获胜!")
break
player = WHITE
else:
print("无效的落子位置,请重新输入!")
continue
# AI 下棋
else:
# 这里可以添加 AI 算法来选择最佳的落子位置
valid_moves = np.argwhere(board == EMPTY)
move = valid_moves[np.random.choice(len(valid_moves))]
x, y = move
board[x, y] = WHITE
if is_win((x, y)):
print("白棋获胜!")
break
player = BLACK
if __name__ == "__main__":
main()
```
这段代码实现了一个简单的五子棋游戏,其中包括棋盘状态的定义、判断是否胜利的函数、玩家和 AI 的落子逻辑等。你可以直接运行这段代码来体验游戏。注意,AI 目前只是随机选择一个空位置进行落子,你可以根据需要修改 AI 算法来提升智能程度。
阅读全文