python五子棋人机对战
时间: 2023-09-02 16:14:07 浏览: 124
以下是一个简单的 Python 代码实现,实现了人机对战五子棋游戏:
```python
import random
# 初始化棋盘
def init_board(n):
board = []
for i in range(n):
row = ['-'] * n
board.append(row)
return board
# 打印棋盘
def print_board(board):
n = len(board)
for i in range(n):
row_str = ' '.join(board[i])
print(row_str)
# 判断是否胜利
def check_win(board, player):
n = len(board)
# 检查行
for i in range(n):
if board[i].count(player) == n:
return True
# 检查列
for i in range(n):
col = [board[j][i] for j in range(n)]
if col.count(player) == n:
return True
# 检查对角线
diag1 = [board[i][i] for i in range(n)]
diag2 = [board[i][n-i-1] for i in range(n)]
if diag1.count(player) == n or diag2.count(player) == n:
return True
return False
# 人类玩家下棋
def human_player(board, player):
n = len(board)
while True:
try:
row = int(input("请输入行号(1-%d):" % n)) - 1
col = int(input("请输入列号(1-%d):" % n)) - 1
if board[row][col] == '-':
board[row][col] = player
break
else:
print("该位置已经有棋子,请重新输入!")
except:
print("输入不合法,请重新输入!")
# AI玩家下棋
def ai_player(board, player):
n = len(board)
# 随机生成下棋位置
while True:
row = random.randint(0, n-1)
col = random.randint(0, n-1)
if board[row][col] == '-':
board[row][col] = player
break
# 游戏主循环
def main():
n = 10 # 棋盘大小
human = 'X'
ai = 'O'
board = init_board(n)
print_board(board)
while True:
# 人类下棋
human_player(board, human)
print_board(board)
if check_win(board, human):
print("你赢了!")
break
# AI下棋
ai_player(board, ai)
print_board(board)
if check_win(board, ai):
print("你输了!")
break
if __name__ == '__main__':
main()
```
这个代码实现了一个简单的五子棋游戏,玩家扮演 X 方,AI 扮演 O 方。玩家每次输入行号和列号下棋,AI 则随机选择一个空位置下棋。当有一方获胜时,游戏结束。
阅读全文