python五子棋代码
时间: 2023-10-08 16:13:41 浏览: 24
以下是一个简单的 Python 五子棋代码示例:
```python
import numpy as np
# 定义棋盘大小
SIZE = 15
# 定义棋盘
board = np.zeros((SIZE, SIZE), dtype=np.int)
# 定义棋子颜色
BLACK = 1
WHITE = 2
# 定义落子函数
def put_chess(x, y, color):
if board[x][y] == 0:
board[x][y] = color
return True
return False
# 定义判断胜负函数
def check_win(x, y, color):
# 判断横向是否连成五子
count = 0
for i in range(max(0, x-4), min(SIZE, x+5)):
if board[i][y] == color:
count += 1
if count == 5:
return True
else:
count = 0
# 判断纵向是否连成五子
count = 0
for i in range(max(0, y-4), min(SIZE, y+5)):
if board[x][i] == color:
count += 1
if count == 5:
return True
else:
count = 0
# 判断斜向是否连成五子
count = 0
for i, j in zip(range(max(0, x-4), min(SIZE, x+5)),
range(max(0, y-4), min(SIZE, y+5))):
if board[i][j] == color:
count += 1
if count == 5:
return True
else:
count = 0
# 判断反斜向是否连成五子
count = 0
for i, j in zip(range(max(0, x-4), min(SIZE, x+5)),
range(min(SIZE-1, y+4), max(-1, y-5), -1)):
if board[i][j] == color:
count += 1
if count == 5:
return True
else:
count = 0
return False
# 开始游戏
player = BLACK
while True:
if player == BLACK:
print("黑方落子:")
else:
print("白方落子:")
x = int(input("请输入x坐标:"))
y = int(input("请输入y坐标:"))
if put_chess(x, y, player):
if check_win(x, y, player):
print("恭喜{}方获胜!".format("黑" if player == BLACK else "白"))
break
player = WHITE if player == BLACK else BLACK
else:
print("该位置已有棋子,请重新输入。")
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)