We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello, I'm pretty new to programming, and am working on a pretty basic drawing program. See I am trying to add undo and redo buttons. I want them to be able to affect the things I draw in the PGraphics, if that makes sense. Is there a way to fix this? Sorry if the code is excessive...
PGraphics pg;
boolean controlDown = false;
boolean shiftDown = false;
int bgColor = 255;
int pColor = 0;
int pAlpha = 255;
int selector = 0;
int pSize = 5;
int eSize = 5;
boolean drawing = false;
boolean doOnce = false;
Undo undo;
void setup() {
size(900, 600);
smooth();
pg = createGraphics(width, height);
undo = new Undo(10);
}
void draw() {
background(bgColor);
if(mouseX > 142) {
noCursor();
} else {
cursor();
}
noFill();
stroke(0);
if(selector == 0) {
ellipse(mouseX, mouseY, pSize + 2, pSize + 2);
} else {
ellipse(mouseX, mouseY, eSize + 2, eSize + 2);
}
}
void pencil() {
if (mousePressed) {
if (mouseX > 142) {
pg.beginDraw();
pg.stroke(pColor, pAlpha);
pg.strokeWeight(pSize);
pg.strokeJoin(ROUND);
pg.line(mouseX, mouseY, pmouseX, pmouseY);
pg.endDraw();
image(pg, 0, 0);
}
}
}
void mousePressed() {
if (mouseX > 142) {
drawing = true;
} else {
drawing = false;
}
}
void mouseReleased() {
drawing = false;
doOnce = false;
if(mouseX > 142 || mouseX > 18 && mouseX < 67 && mouseY > 534 && mouseY < 586) {
undo.takeSnapshot();
}
}
void mouseClicked() {
println(mouseX, mouseY);
}
void keyPressed() {
if (key == CODED) {
if (keyCode == CONTROL) {
controlDown = true;
}
if (keyCode == SHIFT) {
shiftDown = true;
}
return;
}
if (controlDown) {
if (keyCode == 'Z') {
if (shiftDown) {
undo.redo();
} else {
undo.undo();
}
}
return;
}
}
void keyReleased() {
if (key == CODED) {
if (keyCode == CONTROL) {
controlDown = false;
}
if (keyCode == SHIFT) {
shiftDown = false;
}
}
}
class Undo {
int undoSteps = 0, redoSteps = 0;
CircImgCollection images;
Undo(int levels) {
images = new CircImgCollection(levels);
}
public void takeSnapshot(){
undoSteps = min(undoSteps+1, images.amount-1);
redoSteps = 0;
images.next();
images.capture();
}
public void undo() {
if (undoSteps > 0) {
undoSteps--;
redoSteps++;
images.prev();
images.show();
}
}
public void redo() {
if (redoSteps > 0) {
undoSteps++;
redoSteps--;
images.next();
images.show();
}
}
}
class CircImgCollection {
int amount, current;
PImage[] img;
CircImgCollection(int amountOfImages) {
amount = amountOfImages;
img = new PImage[amount];
for (int i=0; i < amount; i++) {
img[i] = createImage(width, height, RGB);
img[i] = get();
}
}
void next() {
current = (current + 1) % amount;
}
void prev() {
current = (current - 1 + amount) % amount;
}
void capture() {
img[current] = get();
}
void show() {
image(img[current], 0, 0);
}
}
Answers
edit post, highlight code, press ctrl-o