0

我创建了一个海龟绘图程序,可以在用户在键盘上按下的海龟画布上绘制任何字母。我已经实现了一个撤消功能来撤消用户调用的最后一个绘图(如下所示),但现在我正在研究如何实现重做功能。任何人都可以根据我当前的撤消功能给我任何关于最pythonic方式的提示或技巧吗?我对此进行了很多搜索,但无济于事,因此非常感谢有关此问题的任何帮助。

我的撤消功能:

def Clear():
    clear()
    speed(0)
    tracer(0,0)



def undoHandler():
    if len(function) > 0:
        undoHandler.handling = True
        if not hasattr(undoHandler, "counter"):
            undoHandler.counter = 0
        undoHandler.counter += 1
        Clear()
        function.pop()
        penup()
        try:
            goto(o,p)
            print("Gone to")
        except:
            goto(-200, 100)
        pendown()

        # "function" is a deque I created with the letter functions appended to it        
        # Items created based on a Points class that also stores all the attributes including the width, height, color, etc. of each letter.     
        # Items from a queue I created for the letter functions. The following executes each item from the deque.
        try:
            for i in function:
            k = i.getXY()
            penup()
            goto(k)
            pendown()
            hk = i.getletterheight()
            global letter_height
            letter_height = hk
            rk = i.getletterwidth()
            global letter_width
            letter_width = rk
            hw = i.getwidth()
            width(hw)
            op = i.getcolor()
            try:
                color(op)
            except:
                for g in colors:
                cp = g.getcolor2()
                colormode(255)
                color(cp)
           j = i.getfunction()
           j()
        except:
            pass



   update()

编辑:为了避免混淆,我想要“重做”做的是清除画布,然后在每次按下调用“重做”的按钮时用一个函数重绘所有内容,超过未完成点。例如,如果用户在画布上绘制“HELLO”,并且用户撤消直到字母“H”,当按下一次重做时,乌龟应该重绘“H(用户选择的新字母)L”,如果重做是第二次调用,乌龟应该绘制“H(新字母用户选择)LL”,依此类推。它还应该能够将未完成的字母更改为用户替换它的字母(因此是“重做”)。例如,如果用户撤销到例如“HELLO”中的“H”,并且用户将“E”替换为“A”,那么当调用重做时,

4

1 回答 1

2

处理撤消/重做的一种简单方法是使用两个堆栈。

如果你把它想象成一个网络浏览器,一个堆栈用于 go backwards,另一个堆栈用于 go forwards

覆盖的新操作:每个新的用户操作都完成,然后压入backwards堆栈。最后,下一个重做动作被从forwards堆栈中弹出并丢弃的动作覆盖(如果它不为空)。

撤消:当用户想要后退时(undo),从backwards堆栈中弹出一个动作,撤消该动作,然后将该动作压入forwards堆栈。

全部重做:当用户想要前进时(redo),从forwards堆栈中弹出一个动作,该动作被重做,然后该动作被推入backwards堆栈。在这种情况下,redo实际上是redo all,所以redo应该重复直到forwards堆栈为空。

警告:确保定义每个操作以使其独立,否则当操作被覆盖时您可能会遇到问题。

于 2016-01-07T02:04:28.823 回答