五子棋游戏python人机对战
时间: 2023-08-28 19:07:58 浏览: 100
好的,以下是一个简单的五子棋游戏的 Python 代码,支持人机对战:
```python
import random
# 初始化棋盘
def init_board():
board = []
for i in range(15):
row = ["+" for j in range(15)]
board.append(row)
return board
# 打印棋盘
def print_board(board):
for row in board:
print(" ".join(row))
# 检查是否有五子连珠
def check_win(board, x, y, piece):
# 检查横向
count = 0
for i in range(15):
if board[x][i] == piece:
count += 1
else:
count = 0
if count >= 5:
return True
# 检查纵向
count = 0
for i in range(15):
if board[i][y] == piece:
count += 1
else:
count = 0
if count >= 5:
return True
# 检查左上到右下斜线
count = 0
for i in range(-4, 5):
if 0 <= x + i < 15 and 0 <= y + i < 15 and board[x + i][y + i] == piece:
count += 1
else:
count = 0
if count >= 5:
return True
# 检查右上到左下斜线
count = 0
for i in range(-4, 5):
if 0 <= x + i < 15 and 0 <= y - i < 15 and board[x + i][y - i] == piece:
count += 1
else:
count = 0
if count >= 5:
return True
return False
# 人机对战
def play():
board = init_board()
print_board(board)
piece = "X"
while True:
if piece == "X":
# 人下棋
x, y = map(int, input("请输入你要下的棋子坐标(x y):").split())
if board[x][y] != "+":
print("该位置已经有棋子,请重新下棋!")
continue
else:
# 机器下棋
x, y = get_ai_move(board, piece)
board[x][y] = piece
print_board(board)
if check_win(board, x, y, piece):
print(piece + "赢了!")
break
if piece == "X":
piece = "O"
else:
piece = "X"
# 获取机器下棋的位置
def get_ai_move(board, piece):
# 随机下棋
while True:
x = random.randint(0, 14)
y = random.randint(0, 14)
if board[x][y] == "+":
return x, y
if __name__ == "__main__":
play()
```
这个程序中,`init_board()` 函数用于初始化棋盘,`print_board()` 函数用于打印棋盘,`check_win()` 函数用于检查是否有五子连珠,`play()` 函数用于实现人机对战,`get_ai_move()` 函数用于获取机器下棋的位置。程序中使用了一个循环,交替让玩家和机器下棋,直到有一方获胜。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.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)