python - Connect4 w/ AI Bots:最佳对角移动(python)
问题描述
我目前正在尝试编写一个函数,该函数将选择最好的列来丢弃该部分,因此对角线有一个连接 4。所以从给定的game_board,函数应该返回winning_col = 4。但我确定要做什么,这就是我开始的。
game_board =
[['_','_','_','-','-'],
['-','-','-','-','-'],
['_','_','_','o','o'],
['-','-','o','x','x'],
['-','o','o','x','o']]
num_row= 5
num_col= 5
num_piece = 3
game_piece = 'o'
for rows in range(num_row - num_piece + 1):
for cols in range(num_piece - 1, num_col):
index = 0
for counts in range(num_piece):
if game_board[rows + index][cols - index] == game_piece and game_board[rows + index][cols] == game_piece:
index += 1
winning_col = cols
else:
break
if index == num_piece:
print (winning_col)
解决方案
处理在棋盘游戏中找到获胜棋步的一般问题的典型方法是首先编写一个函数,该函数将告诉您给定的棋盘设置是否获胜。看看这个答案,了解如何做到这一点的一些想法:
所以,do_we_have_a_winner
从那个问题的函数开始(它适用于任何“N in a row”类型的游戏,例如tic tac toe 或connect 4),我将添加另一个帮助程序,这是一个专门用于连接的函数- 4 将一块落入棋盘:
def drop_piece(
board: List[List[str]],
piece: str,
col: int
) -> List[List[str]]:
"""Drops the piece into the board, returning the modified board."""
new_board = [[p for p in row] for row in board]
for row in reversed(new_board):
if row[col] is None:
row[col] = piece
return new_board
raise ValueError(f"Column {col} is full!")
现在我要设置我的电路板并定义一种打印它的好方法:
def print_board(board: List[List[str]]):
for row in board:
print("".join(p if p else '-' for p in row))
game_board = [
[p if p not in {'_', '-'} else None for p in row]
for row in [
['_', '_', '_', '-', '-'],
['-', '-', '-', '-', '-'],
['_', '_', '_', 'o', 'o'],
['-', '-', 'o', 'x', 'x'],
['-', 'o', 'o', 'x', 'o']
]
]
game_piece = 'o'
现在我已经完成了这个设置,问题就很简单了:对于每一列,看看如果我们在那里丢了一块棋盘会是什么样子,然后看看这是否会让我们成为赢家!
print_board(game_board)
print(f"Looking for a winning move for {game_piece}...")
for col in range(len(game_board[0])):
test_board = drop_piece(game_board, game_piece, col)
if do_we_have_a_winner(test_board, 4) == game_piece:
print(f"Winning move is column {col}!")
print_board(test_board)
break
-----
-----
---oo
--oxx
-ooxo
Looking for a winning move for o...
Winning move is column 4!
-----
----o
---oo
--oxx
-ooxo
推荐阅读
- c# - UWP 使用 FolderPicker 添加刚刚定义的文件类型
- git - 我不小心使用了 revert 而不是重置未提交的文件
- php - 是否可以将自定义数据传递给条带结帐?
- android - does android.permission.CAMERA can activate camera even when app is not open?
- react-native - 在使用 VSCode 在 React Native 中进行调试时,有什么方法可以特别设置 iPhone 6s?
- node.js - 如何从日志消息中调试 node.js 程序
- c++ - 如何不忽略构造函数参数之前的空格?
- tensorflow - Keras - 添加的图层必须是图层类的实例。找到:张量
- java - 如何在 Jenkins 中使用构建参数编辑 app.properties 文件
- c - c中位移和加法后的变量值不正确