python字符型五子棋人机对战
时间: 2023-10-01 07:03:52 浏览: 44
下面是一个使用 Python 实现的五子棋人机对战的示例代码:
```python
import random
def draw_board(board):
"""绘制棋盘"""
for i in range(len(board)):
print(' '.join(board[i]))
def get_computer_move(board, computer_letter):
"""获取电脑下棋的位置"""
# 查找是否存在获胜的位置
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == ' ':
board[i][j] = computer_letter
if is_winner(board, computer_letter):
return (i, j)
board[i][j] = ' '
# 防守玩家获胜的位置
player_letter = 'X' if computer_letter == 'O' else 'O'
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == ' ':
board[i][j] = player_letter
if is_winner(board, player_letter):
return (i, j)
board[i][j] = ' '
# 随机下棋
while True:
i = random.randint(0, len(board) - 1)
j = random.randint(0, len(board[i]) - 1)
if board[i][j] == ' ':
return (i, j)
def is_winner(board, letter):
"""判断是否存在获胜的位置"""
# 检查行
for i in range(len(board)):
if board[i][0] == letter and board[i][1] == letter and board[i][2] == letter and board[i][3] == letter and board[i][4] == letter:
return True
# 检查列
for j in range(len(board[0])):
if board[0][j] == letter and board[1][j] == letter and board[2][j] == letter and board[3][j] == letter and board[4][j] == letter:
return True
# 检查正对角线
if board[0][0] == letter and board[1][1] == letter and board[2][2] == letter and board[3][3] == letter and board[4][4] == letter:
return True
# 检查反对角线
if board[0][4] == letter and board[1][3] == letter and board[2][2] == letter and board[3][1] == letter and board[4][0] == letter:
return True
return False
def is_board_full(board):
"""判断棋盘是否已满"""
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == ' ':
return False
return True
def main():
# 初始化棋盘
board = [[' ' for j in range(5)] for i in range(5)]
draw_board(board)
# 玩家执X,电脑执O
player_letter = 'X'
computer_letter = 'O'
while True:
# 玩家下棋
row = int(input('请输入行号(0-4):'))
col = int(input('请输入列号(0-4):'))
if board[row][col] == ' ':
board[row][col] = player_letter
else:
print('该位置已经下过了,请重新输入!')
continue
draw_board(board)
# 判断是否获胜
if is_winner(board, player_letter):
print('恭喜,你获胜了!')
break
# 判断是否棋盘已满
if is_board_full(board):
print('平局!')
break
# 电脑下棋
row, col = get_computer_move(board, computer_letter)
board[row][col] = computer_letter
draw_board(board)
# 判断是否获胜
if is_winner(board, computer_letter):
print('很遗憾,电脑获胜了!')
break
# 判断是否棋盘已满
if is_board_full(board):
print('平局!')
break
if __name__ == '__main__':
main()
```
这个程序中,使用一个二维数组 `board` 来表示棋盘,`'X'` 表示玩家棋子,`'O'` 表示电脑棋子,`' '` 表示空位。
在 `get_computer_move` 函数中,首先查找是否存在获胜的位置,如果存在则返回该位置;如果不存在,则防守玩家获胜的位置;最后,如果都没有找到,则随机下棋。
在 `is_winner` 函数中,检查是否存在获胜的位置,如果存在则返回 `True`,否则返回 `False`。
在主函数 `main` 中,先让玩家下棋,再让电脑下棋,直到某一方获胜或者棋盘已满。
阅读全文