首页 > 解决方案 > 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)

标签: python

解决方案


处理在棋盘游戏中找到获胜棋步的一般问题的典型方法是首先编写一个函数,该函数将告诉您给定的棋盘设置是否获胜。看看这个答案,了解如何做到这一点的一些想法:

在网格中查找具有相同值的相邻单元格。想法如何改进这个功能?

所以,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

推荐阅读