I am currently working on creating a paint program using python and pygame. I am currently having trouble with creating the undo/redo function in the program. The way I was thinking of doing so would be to save the canvas image after each time the user releases the mouse, but I am not sure if the individual images would have to be saved in a temporary folder that is deleted after the program is closed. I have also read that this method can affect performance of the program so I am wondering if there are any other methods that will work more efficiently. Thank you.
Paint Program in Python - Undo and Redo
1k views Asked by user2950875 At
2
There are 2 answers
0
On
writing a copy to file does sound a bit heavy handed, does it need to be unlimited undo? I would suggest using something like pythons collections.deque as a circular buffer to save the last N modifications, this would save you having to worry about cleanup and disk storage. If taking full snapshots each time turns out to be to much performance wise you may need to look into limiting eached saved region to a specific bounding box based on whatever that last action was that the user performed.
My suggestion is to have a buffer of the last operations that have been done. Each operation will consist of a sprite, and a position of where it is placed.
You will be drawing the canvas, as well as all sprites from that buffer. When you have to many sprites in the buffer, you can blit the oldest onto the canvas, thus saving memory.
The undo itself would be rather easy. Just remove the last sprite that was added.
A redo would be slightly more difficult. Since instead of removing, I would have a pointer, that points to the last sprite that I will draw. If a new action will be added, only then I remove all the sprites that have been "invisible".