我目前正在尝试为一个函数编写代码,该函数将挑选最好的列来丢弃片段,因此有一个对角连接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)发布于 2020-05-19 10:14:56
处理在棋盘游戏中寻找获胜棋的一般问题的典型方法是首先编写一个函数,该函数将告诉您给定的棋盘设置是否为胜利。请看下面的答案,了解如何做到这一点:
Finding neighbor cells in a grid with the same value. Ideas how to improve this function?
因此,从问题中的do_we_have_a_winner函数开始(它适用于任何"N in a row“类型的游戏,例如tic tac toe或connect 4),我将添加另一个helper,这是一个专门用于connect-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
-ooxohttps://stackoverflow.com/questions/61881870
复制相似问题