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

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

问题描述

我目前正在尝试编写一个名为《巴姆图姆》的游戏.游戏涉及一个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:

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天全站免登陆