[英]What is the most pythonic way to structure a multi-module python program?
[英]Most pythonic way to implement redoing in my Python turtle drawing program?
我創建了一個烏龜繪圖程序,該程序可以在用戶按下鍵盤上的烏龜畫布上繪制任何字母。 我已經實現了撤消功能來撤消用戶調用的最后一個圖形( 如下所示 ),但是現在我正在研究如何實現重做功能。 有人可以根據我目前的撤消功能,以最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”,則在調用重做時,應繪制“ HAL”。
處理撤消/重做的一種簡單方法是使用兩個堆棧。
如果您將其視為網絡瀏覽器,則一個堆棧用於backwards
,另一個堆棧用於forwards
。
帶有覆蓋的新操作:完成每個新的用戶操作,然后將其推入backwards
堆棧。 最后,通過彈出一個動作並將其從forwards
堆棧中丟棄(如果它不為空),下一個重做動作將被覆蓋。
撤消:當用戶想向后退( undo
)時,將從backwards
堆棧中彈出一個動作,撤消該動作,然后將該動作推入forwards
堆棧。
全部重做:當用戶要前進( redo
)時,將從forwards
堆棧中彈出一個動作,重做該動作,然后將該動作推入backwards
堆棧。 在這種情況下, redo
實際上是redo all
,所以redo
應重復,直到forwards
堆棧是空的。
警告:請確保每個動作的定義都是獨立的,否則覆蓋動作時可能會遇到問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.