在 Python 中为 7x7 板制作撤消功能 [英] Making an undo function for a 7x7 board in Python

查看:23
本文介绍了在 Python 中为 7x7 板制作撤消功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试编写一款名为 Pah Tum 的游戏.该游戏涉及一个 7x7 的棋盘.对于板子,我刚刚创建了一个包含 7 个列表的列表,每个列表包含 7 个元素,基本上我只是将每一行变成一个列表并将它们合并到一个大列表中:

I am currently trying to program a game called Pah Tum. The game involves a board that is 7x7. For the board I just created a list with 7 lists containing 7 elements each, basically I just made each row into a list and merged them into a big list:

board = [[0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0]]

游戏应该有撤销功能,可以让玩家后退一步.我想我可以将整个电路板附加到一个单独的列表中,然后用它来回退一步.

The game should have an undo function, which enables the player to go back one step. I thought I could just append the whole board into a seperate list and use that to go back a step.

        if input == 'u' or input == 'U':
            board = board_list[-1]
            del board_list[-1]

直到这里它工作,但由于某种原因,board_list(我将当前板附加到的列表)总是作为一个整体更新,这意味着每个元素都会发生变化并成为新板.

until here it works, but for some reason the board_list (the list I'm appending the current board to) always updates as a whole, meaning each element changes and becomes the new board.

例如.如果我有

#board = [[0, 'B'], [0, 0]]
board_list.append(board)
.
.
.
#board = [[0, 'B'], [0, 'B']]
board_list.append(board)

在第一个附加之后我会得到

after the first append I'd get

board_list = [[[0, 'B'], [0, 0]]]

第二个留给我

board_list = [[[0, 'B'], [0, 'B']], [[0, 'B'], [0, 'B']]]

我不知道为什么会发生这种情况.我搜索了类似的问题,但我只看到画布的撤消功能,我不确定我是否可以在这种情况下使用它们.

I have no idea why this happens. I searched for similar questions but I only see undo functions for canvases and I'm not sure if I can use them for this scenario.

推荐答案

当您将 board 附加到 board_list 时,您正在添加一个引用原始 board.也许更好的选择是在您移动时为更改的单元格添加先前的状态:

When you append board to board_list you're adding a reference to the original board. Perhaps a better option would be to add the previous state for the changed cell when you make a move:

moves.append([x, y, board[x][y]])

然后当您撤消时,您会重新应用该状态:

And then when you undo you reapply that state:

undo_move = moves[-1]
board[undo_move[0]][undo_move[1]] = undo_move[2]
del moves[-1]

或者更像python:

Or more pythonically:

x, y, board[x][y] = moves.pop()

或者,您可以复制整个图板并将其存储在列表中.

Alternatively, you could make a copy of the entire board and store that in the list instead.

这篇关于在 Python 中为 7x7 板制作撤消功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆