编写五子棋的完整python代码_python实现五子棋程序
时间: 2023-07-23 22:18:51 浏览: 997
下面是一个简单的五子棋的Python实现代码:
```
# -*- coding: utf-8 -*-
import os
board = {} # 保存棋盘状态
player = 1 # 玩家
running = True # 游戏是否结束
# 初始化棋盘
for i in range(15):
for j in range(15):
board[(i, j)] = 0
# 判断是否有五个连续的棋子
def check_five(i, j, color):
count = 0
# 横向
for x in range(i - 4, i + 5):
if (x, j) in board and board[(x, j)] == color:
count += 1
else:
count = 0
if count == 5:
return True
# 竖向
for y in range(j - 4, j + 5):
if (i, y) in board and board[(i, y)] == color:
count += 1
else:
count = 0
if count == 5:
return True
# 斜向
k = j - i
for x in range(i - 4, i + 5):
y = x + k
if (x, y) in board and board[(x, y)] == color:
count += 1
else:
count = 0
if count == 5:
return True
k = j + i
for x in range(i - 4, i + 5):
y = -x + k
if (x, y) in board and board[(x, y)] == color:
count += 1
else:
count = 0
if count == 5:
return True
return False
# 打印棋盘
def print_board():
os.system('clear')
print(' 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14')
for i in range(15):
print(i, end=' ')
for j in range(15):
if board[(i, j)] == 0:
print('+', end=' ')
elif board[(i, j)] == 1:
print('○', end=' ')
else:
print('●', end=' ')
print()
# 主循环
while running:
print_board()
if player == 1:
print('轮到玩家1下棋')
else:
print('轮到玩家2下棋')
x = int(input('请输入 x 坐标:'))
y = int(input('请输入 y 坐标:'))
if (x, y) in board and board[(x, y)] == 0:
board[(x, y)] = player
if check_five(x, y, player):
running = False
print_board()
if player == 1:
print('玩家1获胜')
else:
print('玩家2获胜')
player = 3 - player
else:
print('非法坐标,请重新输入')
```
可以通过运行上面的代码,来体验五子棋的游戏过程。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)