python - 在 2D 列表中滑动列和行

标签 python

我正在尝试实现一个简单的纸牌游戏,其目标是移动不同颜色的行和列,直到它们形成特定的图案。我试图使用二维列表来表示我的游戏板的配置:

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/

相关文章:

Python MySQL : Select with default value

python - 如何使用模型/ View / Controller 方法制作 GUI?

python - if 部分的变量范围

Python/ Pandas /日期时间 : transform entire lists in a column to datetime

python - Django 模板在无效的编辑个人资料表单上呈现更改的用户名

python - 这些(几乎相同)条件之间的效率差异是什么

python - 有没有办法在Windows 7中不使用QT编译wireshark解析器插件?

python - Django View 在模型更改后不更新

python - 如何将样本的 x 位置与 matplotlib.pyplot 中的表列对齐?

python - 如何对同一文本样本的不同主题/方面进行情感分析