【发布时间】:2012-06-02 04:26:00
【问题描述】:
我正在尝试使用 lambda 在 pygame 应用程序中实现撤消和重做,但与引用有关,或者我对 list.remove() 实现的理解导致我的程序崩溃。创建可撤消操作的代码如下
elif MOUSEBUTTONUP == event.type:
x, y = pygame.mouse.get_pos()
if leftClick:
if len( objects ) > 0 and objects[ -1 ].is_open():
actions.do( \
[ lambda: objects[ -1 ].add( Point( x, y, 0 ) ) ], \
[ lambda: objects[ -1 ].remove( Point( x, y, 0 ) ) ] \
)
else:
actions.do( \
[ lambda: objects.append( Polygon( ( 255, 255, 255 ) ).add( Point( x, y, 0 ) ) ) ],
[ lambda: objects.pop() ] \
)
其中objects是Polygons的列表,定义为
class Polygon:
def __init__( self, colour, width = 0 ):
self._points = []
self._colour = colour
self._isopen = True
self._width = width
def get_colour( self ):
return self._colour
def add( self, point ):
self._points.append( point )
return self
def remove( self, point ):
print "List contains " + str( self._points )
print "Trying to remove " + str( point )
self._points.remove( point )
return self
def num_points( self ):
return len( self._points )
def get_points( self ):
""" Returns a copy of the points in this vector as a list. """
return self._points[:]
def open( self ):
self._isopen = True
return self
def close( self ):
self._isopen = False
return self
def is_open( self ):
return self._isopen
def set_width( self, width ):
self._width = width
return self
def get_width( self ):
return self._width
def is_filled( self ):
return self._filled
添加的点定义为
class Point:
def __init__( self, x, y, z ):
self.x = x
self.y = y
self.z = z
def rel_to( self, point ):
x = self.move( point.z, point.x, self.z, self.x )
y = self.move( point.z, point.y, self.z, self.y )
return ( x, y )
def move( self, viewer_d, displacement, object_d, object_h ):
over = object_h * viewer_d + object_d * displacement
under = object_d + viewer_d + 1
return over / under
def __str__( self ):
return "(%d, %d, %d)" % ( self.x, self.y, self.z )
def __eq__( self, other ):
return self.x == other.x and self.y == other.y and self.z == other.z
def __ne__( self, other ):
return not ( self == other )
actions,在第一个sn-p中,是Action的一个实例,其定义如下
class Actions:
#TODO implement immutability where possible
def __init__( self ):
self.undos = []
self.redos = []
def do( self, do_steps, undo_steps ):
for do_step in do_steps:
do_step()
self.undos.append( ( do_steps, undo_steps ) )
self.redos = []
def can_undo( self ):
return len( self.undos ) > 0
def undo( self ):
if self.can_undo():
action = self.undos.pop()
_, undo_steps = action
for undo_step in undo_steps:
undo_step()
self.redos.append( action )
def can_redo( self ):
return len( self.redos ) > 0
def redo( self ):
if self.can_redo():
action = self.redos.pop()
redo_steps, _ = action
for redo_step in redo_steps:
redo_step()
self.undos.append( action )
所以问题是,当我点击两次以上并尝试调用actions.undo() 时,我得到list.remove(x) 的异常,它说x 不在列表中,我认为是因为它试图删除同一点两次。在前两次单击之前不会发生这种情况的原因是第一次撤消尝试删除最近的点,而第二次撤消只是将多边形从对象堆栈中弹出。我的问题是为什么actions.undo() 的Point 会尝试两次删除同一个点,即使第一个点应该从self.undos 堆栈中弹出并推到self.redos 堆栈上?非常感谢您的任何反馈。
【问题讨论】:
标签: python lambda pygame undo redo