编写一个字符界面的五子棋人机对战程序,要求游戏难度中等
时间: 2024-05-01 11:20:25 浏览: 103
好的,我可以为您提供一个基于Python编写的字符界面五子棋人机对战程序,难度中等。以下是代码:
```python
import random
# 初始化棋盘
def init_board():
board = []
for i in range(15):
row = []
for j in range(15):
row.append('+')
board.append(row)
return board
# 打印棋盘
def print_board(board):
print(' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15')
for i in range(15):
row = chr(ord('A') + i) + ' '
for j in range(15):
row += board[i][j] + ' '
print(row)
# 判断输赢
def check_win(board, x, y):
# 横向
count = 0
for i in range(max(0, y - 4), min(15, y + 5)):
if board[x][i] == board[x][y]:
count += 1
if count == 5:
return True
else:
count = 0
# 竖向
count = 0
for i in range(max(0, x - 4), min(15, x + 5)):
if board[i][y] == board[x][y]:
count += 1
if count == 5:
return True
else:
count = 0
# 斜向
count = 0
for i in range(-4, 5):
if x + i < 0 or x + i >= 15 or y + i < 0 or y + i >= 15:
continue
if board[x + i][y + i] == board[x][y]:
count += 1
if count == 5:
return True
else:
count = 0
# 反斜向
count = 0
for i in range(-4, 5):
if x + i < 0 or x + i >= 15 or y - i < 0 or y - i >= 15:
continue
if board[x + i][y - i] == board[x][y]:
count += 1
if count == 5:
return True
else:
count = 0
return False
# 人下棋
def person_move(board):
while True:
move = input('请您输入您的落子坐标,例如 A1:')
if len(move) != 2:
print('输入有误,请重新输入!')
continue
x = ord(move[0]) - ord('A')
y = int(move[1:]) - 1
if x < 0 or x >= 15 or y < 0 or y >= 15 or board[x][y] != '+':
print('输入有误,请重新输入!')
continue
board[x][y] = 'O'
break
# 机器下棋
def computer_move(board):
score = [[0 for i in range(15)] for j in range(15)]
for i in range(15):
for j in range(15):
if board[i][j] == '+':
# 计算分数
for k in range(-2, 3):
if i + k < 0 or i + k >= 15:
continue
for l in range(-2, 3):
if j + l < 0 or j + l >= 15:
continue
if board[i + k][j + l] == 'O':
score[i][j] += 1
for k in range(-1, 2):
if i + k < 0 or i + k >= 15:
continue
for l in range(-1, 2):
if j + l < 0 or j + l >= 15:
continue
if board[i + k][j + l] == 'O':
score[i][j] += 1
score[i][j] += random.randint(-2, 2)
# 找到最高分数的位置
max_score = 0
points = []
for i in range(15):
for j in range(15):
if score[i][j] > max_score:
max_score = score[i][j]
points = [(i, j)]
elif score[i][j] == max_score:
points.append((i, j))
# 在最高分数的位置随机落子
x, y = random.choice(points)
board[x][y] = 'X'
# 主程序
def main():
board = init_board()
print_board(board)
while True:
person_move(board)
print_board(board)
if check_win(board, x, y):
print('您赢了!')
break
computer_move(board)
print_board(board)
if check_win(board, x, y):
print('机器赢了!')
break
if __name__ == '__main__':
main()
```
在该程序中,人执黑棋,机器执白棋。人和机器轮流下棋,直到有一方获胜或者和棋。机器的下棋策略是计算每个空位的得分,得分越高的位置越有可能落子,避免了随机落子的低效率。您可以尝试调整机器得分的权重,以改变难度水平。
阅读全文