我正在尝试实现一个简单的单人纸牌游戏,其目标是移动不同颜色的行和列,直到它们形成特定的模式。我试图使用2d列表来表示我的游戏板的配置:
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)
我是否在正确的轨道上?我如何实现沿列移动元素的功能?
答案 0 :(得分:1)
您可以转置您的电路板,然后重复使用先前定义的例程。以下是shift_down
。
def transpose(lst):
return list(map(list, zip(*lst)))
def shift_down(board, row_num, num_tiles):
board = transpose(board)
shift_left(board)
board = transpose(board)
shift_right
和shift_up
之后会有类似的过程。
答案 1 :(得分:1)
这是一种你可以解决这个问题的方法
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)