Trying to create a 5x5 grid of squares with std draw but squares are at duplicate coordinates

323 Views Asked by At

I am trying to create a 5x5 board of rectangles(squares) with a 2d array but my code draws the 25 squares in only 5 places so it looks like there's only 5 squares diagonally on the "board". I'm assuming something is wrong with the logic in the nested loop but after tinkering around for a while I can't figure out what it is. Thanks for any help!!

Object class:

public class Card 
{
   private double x, y, wd, ht;
   private int cardNum;
   private boolean faceUp;
   private double space;
   private Color bsC, fsC;
   Random gen = new Random();

   public Card(double x, double y, double width, double height, int cN, double sP)
   {
      this.x = x;
      this.y = x;
      wd = width;
      ht = height;
      faceUp = false;
      this.cardNum = cN;
      space = 0.1;
      bsC = new Color(178, 178, 178);
      fsC = new Color(211, 172, 250);
   }

   public void drawMe()
   {
      StdDraw.setPenColor(bsC);
      StdDraw.filledRectangle(x, y, wd, ht);
   }
}

Tester class:

public class ClientCardJordanHubbard 
{
   public static void ClientCardJordanHubbard()
   {
       Random gen = new Random();
       Card[][] cards = new Card[5][5];
       int count = 0;
       StdDraw.setFont(new Font("Arial", Font.BOLD, 20));
       StdDraw.setPenColor(StdDraw.BLACK);
       StdDraw.text(0.5,0.5, "Press w a s d to move");
       StdDraw.pause(2000);
       StdDraw.clear();

    for(int i = 0; i < cards.length; i++)
    {
        double x = 0.25+0.14*i;
        for (int j = 0; j < cards[i].length; j++)
        {
            double y = 0.25+0.14*j;
            double w = 0.07;
            double h = 0.07;
            int cN = gen.nextInt(5)+1;
            cards[i][j] = new Card(x, y, w, h, cN, 0.1);
            cards[i][j].drawMe();
            System.out.println("The value of the card at index " +i+" " +j
            + " is: " +cards[i][j].getcN());
            System.out.println("The coordinates of the card at index " +i+" " +j
            + " is: " +cards[i][j].getX() +" "+cards[i][j].getY());
            
        }
    }
}
1

There are 1 best solutions below

0
On

Since your cards are displayed diagonally, the first thing you need to check whether your x will get an y value or vice-versa at some point. Knowing this, it is easy to find the error, which is the line of

this.y = x;

since your this.y gets an x value.