以python语言编写一个五子棋人机对战程序
时间: 2023-06-16 22:02:58 浏览: 122
Python五子棋人机对战程序
好的,下面是一个简单的五子棋人机对战程序,基于Python 3编写:
```python
import random
# 初始化棋盘
def init_board():
board = []
for i in range(15):
row = ["+" for j in range(15)]
board.append(row)
return board
# 显示棋盘
def display_board(board):
for row in board:
print(" ".join(row))
# 判断是否胜利
def is_win(board, player):
# 判断行
for i in range(15):
for j in range(11):
if board[i][j] == player and board[i][j+1] == player and board[i][j+2] == player and board[i][j+3] == player and board[i][j+4] == player:
return True
# 判断列
for i in range(11):
for j in range(15):
if board[i][j] == player and board[i+1][j] == player and board[i+2][j] == player and board[i+3][j] == player and board[i+4][j] == player:
return True
# 判断对角线
for i in range(11):
for j in range(11):
if board[i][j] == player and board[i+1][j+1] == player and board[i+2][j+2] == player and board[i+3][j+3] == player and board[i+4][j+4] == player:
return True
for i in range(11):
for j in range(4, 15):
if board[i][j] == player and board[i+1][j-1] == player and board[i+2][j-2] == player and board[i+3][j-3] == player and board[i+4][j-4] == player:
return True
return False
# 人下棋
def human_move(board):
while True:
move = input("请输入您下棋的坐标,以逗号分隔(如:7,8):")
x, y = move.split(",")
x = int(x)
y = int(y)
if x < 1 or x > 15 or y < 1 or y > 15:
print("坐标输入有误,请重新输入!")
elif board[x-1][y-1] != "+":
print("此处已经有棋子,请重新输入!")
else:
board[x-1][y-1] = "O"
break
# AI下棋
def ai_move(board):
while True:
x = random.randint(1, 15)
y = random.randint(1, 15)
if board[x-1][y-1] == "+":
board[x-1][y-1] = "X"
break
# 主函数
def main():
board = init_board()
display_board(board)
while True:
human_move(board)
display_board(board)
if is_win(board, "O"):
print("恭喜你,你赢了!")
break
ai_move(board)
display_board(board)
if is_win(board, "X"):
print("很遗憾,你输了!")
break
if __name__ == "__main__":
main()
```
这个程序实现了人机对战,人执黑先手,机器执白后手。在人下棋的时候,程序会通过输入坐标来确定落子的位置,在AI下棋的时候,程序会随机选择一个空位来落子。如果任意一方获得了五子连珠,游戏结束。
阅读全文