我正在尝试实现一个简单的纸牌游戏,其目标是移动不同颜色的行和列,直到它们形成特定的图案。我试图使用二维列表来表示我的游戏板的配置:
board = [['W', 'W', 'W', 'W'],
['W', 'W', 'W', 'W'],
['B', 'B', 'B', 'B'],
['B', 'B', 'B', 'B']]
假设我们有以下目标板:
goal = [['W', 'B', 'B', 'W'],
['W', 'W', 'W', 'W'],
['W', 'W', 'B', 'B'],
['B', 'B', 'B', 'B']]
对于给定的移动,您只能向上或向下移动一列的元素,或者向右或向左移动一行的元素。从板端掉落的元素会循环回到正在移动的列或行的另一侧。我如何实现函数来实现此功能?对我来说,沿行移动元素的实现似乎相当简单,例如:
def shift_left(board, row_num, num_tiles):
for i in range(0, num_tiles):
elem = board.pop(0)
board.append(elem)
我走在正确的道路上吗?我如何实现沿列移动元素的功能?
最佳答案
这里有一个方法可以解决这个问题
from copy import deepcopy
def shift(board, ix, direction):
if direction is 'up':
return shift_col(board, ix, direction)
if direction is 'down':
return shift_col(board, ix, direction)
if direction is 'left':
return shift_row(board, ix, direction)
if direction is 'right':
return shift_row(board, ix, direction)
def shift_col(board, col_ix, direction):
temp = [row[col_ix] for row in board]
if direction is 'up':
temp = temp[1:len(temp)] + [temp[0]]
if direction is 'down':
temp = [temp[-1]] + temp[0:-1]
for ix, i in enumerate(board):
i[col_ix] = temp[ix]
return board
def shift_row(board, row_ix, direction):
if direction is 'right':
temp = [board[row_ix][-1]] + board[row_ix][0:-1]
if direction is 'left':
temp = board[row_ix][1:len(board[row_ix])] + [board[row_ix][0]]
board[row_ix] = temp
return board
然后我们可以通过以下方式使用它
board = [['W', 'W', 'W', 'W'],
['W', 'W', 'W', 'W'],
['B', 'B', 'B', 'B'],
['B', 'B', 'B', 'B']]
# Shifts the board for a row or column index
# in the specified direction.
# up/down: ix is for columns
# left/right: ix is for rows
board = shift(deepcopy(board), 2, 'down')
for i in board:
print(i)
关于python - 在 2D 列表中滑动列和行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49185800/