五子棋python简单代码
时间: 2024-04-02 09:30:31 浏览: 31
当然可以!以下是一个简单的五子棋Python代码示例:
```python
# 创建一个15x15的棋盘
board = [[' ' for _ in range(15)] for _ in range(15)]
# 定义棋盘打印函数
def print_board(board):
for row in board:
print('|'.join(row))
print('-' * 29)
# 定义判断胜利函数
def check_win(board, row, col, player):
# 检查水平方向
count = 0
for i in range(col-4, col+5):
if i < 0 or i >= 15:
continue
if board[row][i] == player:
count += 1
if count == 5:
return True
else:
count = 0
# 检查垂直方向
count = 0
for i in range(row-4, row+5):
if i < 0 or i >= 15:
continue
if board[i][col] == player:
count += 1
if count == 5:
return True
else:
count = 0
# 检查左上到右下方向
count = 0
for i in range(-4, 5):
if row+i < 0 or row+i >= 15 or col+i < 0 or col+i >= 15:
continue
if board[row+i][col+i] == player:
count += 1
if count == 5:
return True
else:
count = 0
# 检查左下到右上方向
count = 0
for i in range(-4, 5):
if row-i < 0 or row-i >= 15 or col+i < 0 or col+i >= 15:
continue
if board[row-i][col+i] == player:
count += 1
if count == 5:
return True
else:
count = 0
return False
# 主循环
current_player = 'X'
while True:
print_board(board)
print("轮到玩家", current_player)
row = int(input("请输入行号(0-14):"))
col = int(input("请输入列号(0-14):"))
if board[row][col] != ' ':
print("该位置已经有棋子了,请重新输入!")
continue
board[row][col] = current_player
if check_win(board, row, col, current_player):
print_board(board)
print("玩家", current_player, "获胜!")
break
if current_player == 'X':
current_player = 'O'
else:
current_player = 'X'
```
这段代码实现了一个简单的五子棋游戏。玩家可以依次输入行号和列号来下棋,程序会判断是否有玩家获胜并打印棋盘。如果没有玩家获胜,游戏将继续进行。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)