Каждый раз, когда нажимается кнопка мыши, вам нужно создать новый DrawEntity
объект:
if event.type == pg.MOUSEBUTTONDOWN and event.button == 1:
DrawEnt.append(DrawEntity())
В draw
вы должны добавить Rect к последнему DrawEntity
в deque
(DrawEnt
):
def draw(window):
if len(DrawEnt) > 0:
d_Ent = DrawEnt[-1]
mouseX, mouseY = pg.mouse.get_pos()
click = pg.mouse.get_pressed()
if click[0]:
rect = pg.draw.rect(window, (0, 0, 0), pg.Rect(mouseX, mouseY, 3, 3), 3)
d_Ent.add(rect)
Вкл. ctrl - z удалить последний элемент из DrawEnt
(pop
), очистить и снова нарисуйте все оставшиеся элементы:
if event.type == pg.KEYDOWN:
if event.key == pg.K_z and pg.key.get_mods() & pg.KMOD_LCTRL:
if len(DrawEnt) > 0:
DrawEnt.pop()
window.fill((255, 255, 255))
for entity in DrawEnt:
for r in entity.entity:
pg.draw.rect(window, (0, 0, 0), r, 3)
См. пример:
class DrawEntity:
def __init__(self):
self.entity = []
def add(self, toAdd):
self.entity.append(toAdd)
def remove(self):
self.entity = []
def __str__(self):
return ' '.join(map(str, self.entity))
DrawEnt = deque()
def draw(window):
if len(DrawEnt) > 0:
d_Ent = DrawEnt[-1]
mouseX, mouseY = pg.mouse.get_pos()
click = pg.mouse.get_pressed()
if click[0]:
rect = pg.draw.rect(window, (0, 0, 0), pg.Rect(mouseX, mouseY, 3, 3), 3)
d_Ent.add(rect)
def main():
running = True
window = pg.display.set_mode((640, 480))
window.fill((255, 255, 255))
while running:
clock.tick(3200)
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
if event.type == pg.MOUSEBUTTONDOWN and event.button == 1:
d_Ent = DrawEntity()
DrawEnt.append(DrawEntity())
if event.type == pg.KEYDOWN:
if event.key == pg.K_z and pg.key.get_mods() & pg.KMOD_LCTRL:
if len(DrawEnt) > 0:
DrawEnt.pop()
window.fill((255, 255, 255))
for entity in DrawEnt:
for r in entity.entity:
pg.draw.rect(window, (0, 0, 0), r, 3)
draw(window)
pg.display.flip()
#end main loop
pg.quit()
if __name__ == '__main__':
pg.init()
clock = pg.time.Clock()
main()