Multiple Objects question

So I am trying to make chess with my limited knowledge and got stuck at a part. I have two objects (two white pawns) on the board but if I move them, they leave behind themselves as they are dragged across the screen. This would normally be solved by using “setup()” in their code by when that is done, it erases the other piece. Is there a way to fix that or does go into stuff like arrays or something?
Here is my code for reference

wPawn wp1;
wPawn wp2;

//start positions {{

float wp01x = 60;
float wp01y = 610;

float wp02x = 160;
float wp02y = 610;

//start positions }}

void setup() {
  size(950,850);
  background(164,249,238);
  
  //checkerboard {{
  int xsize = 100;
  int ysize = 100;
  int xpos = 50;
  int ypos = 0;
  int r = 255;
  int g = 255;
  int b = 255;
   
  while (ypos < 800) {
    while (xpos < 800) {
      fill(r,g,b);
      rect(xpos,ypos,xsize,ysize);
      xpos = xpos + 100;
      if (r == 255) {
        r = 0;
        g = 0;
        b = 0;
      } else {
        r = 255;
        g = 255;
        b = 255;
       
      }
    }
    ypos = ypos + 100;
    xpos = 50;
    if (r == 255) {
        r = 0;
        g = 0;
        b = 0;
      } else {
        r = 255;
        g = 255;
        b = 255;
      }
  }
  //Checkerboard }}
  
  //Position establishment {{
  textSize(30);
  fill(0,0,0);
  text("A",90,835);
  text("B",190,835);
  text("C",290,835);
  text("D",390,835);
  text("E",490,835);
  text("F",590,835);
  text("G",690,835);
  text("H",790,835);
  text("8",10,60);
  text("7",10,160);
  text("6",10,260);
  text("5",10,360);
  text("4",10,460);
  text("3",10,560);
  text("2",10,660);
  text("1",10,760);
  //position establishement }}
  
  wp1 = new wPawn(wp01x,wp01y);
  wp2 = new wPawn(wp02x,wp02y);
  
}

void draw() {
  wp1.display();
  wp1.move();
  
  wp2.display();
  wp2.move();
}

Class “wPawn”

PImage wPawn;

class wPawn {
  float wPx;
  float wPy;
  
  
  wPawn(float tempXpos, float tempYpos) {
    wPx = tempXpos;
    wPy = tempYpos;
  }
  
  void display() {
   
    wPawn = loadImage("wPawn.png");
    image(wPawn,wPx,wPy,80,80);

  }
  void move() {
    if (mousePressed) {
      if (wPx <= mouseX && mouseX <= (wPx + 80) && wPy <= mouseY && mouseY <= (wPy + 80)) {
        wPx = mouseX - 40;
        wPy = mouseY - 40;
    }
  }
 }
}
1 Like

The code that you have in setup to draw the board needs to be placed in a different function. Let’s call it drawBoard(). Now call this function in the first line of your draw() function. This ensures every time draw() is executed, your board is updated and your pieces will be always drawn on top of a fresh new board.

Yes, it is great you are using classes. Consider using interfaces to be able to define multiple type of pieces: horse, queen, pawn, etc…

Kf

2 Likes

Thank you very much! Though I have not learned about what interfaces are, I will definitely attempt to once I do. My previous idea was just making a bunch of classes for each piece.