• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 938
  • Last Modified:

Make a grid with selectable squares

Hi, i'm quite a newbie java programmer, and i got a quite simple question (with a long answer)... I got an idee to make a turn based strategie game (already made an rpg), but i need a grid with about 25x25 squares, and every square needs some properties. I tried some newbie stuff but i'm afraight i'll have to use some kind of difficult math line that i have never heard of.
So if you could just explain me how i have to tell my program over wich square my mouse is when i press it, i should be able to continue on my own. I Painted a grid and placed some buttons above it already, but that's all i have done so far...
It may take some of your time so that's why i filled in 150 points.

tnx,
Vincent Sels
0
Vincent_Sels
Asked:
Vincent_Sels
  • 5
  • 2
1 Solution
 
lawrieCommented:
The most flexible way would be to make a 'Cell' class, that takes care of each square. This could include drawing it (assuming later it will be more sophisticated than just a square) and knowing what size it is .. my suggestion is to have an java.awt.Rectangle class for each Cell that defines its location and size.

Then on your mouse click events, you will get the x & y coord of your mouse (event.getX() & event.getY()) and just test to see if you are in each Cell with Rectangle.contains(new Point(x, y))

This would be best if the board will not be just a big grid (eg some cells are different widths). If it will be (make sure this won't change later) perhaps just some maths to check which cell the x & y of the mouse click event occurred in.

If all cells the same, something like this would work
  clickedColumn = x / (boardWidth / numColumns);
  clickedRow = y / (boardHeight / numRows);


Hope this helps
0
 
Vincent_SelsAuthor Commented:
tnx i'll try some more and let you know if i was able to continue...
0
 
Vincent_SelsAuthor Commented:
OK this is how i'm gonna do it: subclass rectangle so i can add extra options, add all those 'rects' (in an array field) to the applet, and draw lines around them. Than i'll just use the contains method; that should do it...

but i encountered a problem... see for yourself:

extracts from class WorldMap:

     Rect[] field = new Rect[400];

     void addRects()
     {
          for (int y=0; y<20; y++)
          {
               for (int x=0; x<20; x++)
               {
                    field[(y*20)+x] = new Rect(3+ x*25, 30+ y*25, 25, 25); //here's the problem...
                    field[(y*20)+x].nr = y*20 + x;
               }
          }
     }

public class Rect extends java.awt.Rectangle
{
     stuff
}

when I try to create a new rect the compiler sais he cant find constructor Rect(int, int, int, int) in class Rect... but there certainly is one in class Rectangle. Do I do something wrong ? Do I have to make a new constructor ?
And btw, will it work that way or would you do it completely different ?
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
lawrieCommented:
If you have no constructors for Rect, will only get the default constructor, and hence the default Rectangle constructor. add the following to Rect, and it should fix things

public Rect(int x, int y, int width, int height)
{
    super(x, y, width, height);
}

What you propose would be the most generic way of doing things, offering flexibility to have different sizes or shapes later, so it would be the method I would go for personally. The only drawback would be having to search through all 400 cells to find a click, which will be a bit slower, but shouldn't have a great impact as long as you don't do many lookups unnecessarily (eg don't find it again if you have already found the required cell and could save which one it was instead of recalculating)
0
 
objectsCommented:
If you simply make each of your cells a component then you can add mouse motion listeners to each cell, removing the need for any calculations to work out which cell the mouse is over.
0
 
Vincent_SelsAuthor Commented:
Tnx for your replies...

Lawrie, I used that constructor and now both classes compile but unfortunately the whole thing won't work... When, for example, I try to display the string 'it worked' in field[200] (the rect in the middle), and draw a line from field[1].x, field[1].y to field[399].x, field[399].y nothing at all shows up ! I checked my formulas (field[(y*20)+x] = new Rect(3+ x*25, 30+ y*25, 25, 25);) to place the rectangles and I just can't find any mistakes :/
(the +3 or +30 i add to the place were the rectangle should be construted, is because it has to start at point (3,30) in stead of 0,0. With a canvas I would probably be able to avoid this but I just couldn't get the canvas in the right position so I decided to do it without...)

regards,
 BlackDeath
0
 
Vincent_SelsAuthor Commented:
Ok i'll just give the whole program... find out what's wrong because i really don't see the problem. I included some actions to trace the error but I don't see why it happens there.

import java.awt.*;
import java.lang.Math;

public class WorldMap extends java.applet.Applet
{

     /*////////////////////////////////////////*/
     /*/               Variables              /*/
     /*////////////////////////////////////////*/

     /******************\
     * LAYOUT VARIABLES *
     \******************/

     Panel buttons = new Panel();
     Button b_endTurn = new Button("END TURN");
     Button b_money = new Button("money");
     Button b_resources = new Button ("resources");
     Button b_production = new Button ("production");
     Button b_research = new Button ("research");
     Button b_bases = new Button ("bases");
     Button b_groups = new Button ("groups");

     /*********************\
     * SELECTION VARIABLES *
     \*********************/

     Rect[] field = new Rect[400];
     Point mousePos;
     boolean groupSelected;

     /*****************\
     * OTHER VARIABLES *
     \*****************/

     boolean fieldAdded;



     /*////////////////////////////////////////*/
     /*/                Functions             /*/
     /*////////////////////////////////////////*/

     void addRects()
     {
          for (int y=0; y<20; y++)
          {
               for (int x=0; x<20; x++)
               {
                    field[(y*20)+x] = new Rect(3+ x*25, 30+ y*25, 25, 25);
                    field[(y*20)+x].nr = y*20 + x;
               }
          }
          fieldAdded = true;
     }

     public void init()
     {
          /******************\
          * ARRANGING LAYOUT *
          \******************/

          buttons.setLayout(new GridLayout(1, 7, 0, 0));
          buttons.add(b_endTurn);
          buttons.add(b_money);
          buttons.add(b_resources);
          buttons.add(b_production);
          buttons.add(b_research);
          buttons.add(b_bases);
          buttons.add(b_groups);
          add(buttons);

          addRects();
     }

     public void paint(Graphics g)
     {
          /**************\
          * DRAWING GRID *
          \**************/

          ///////////////////////TEST///////////////////////
          if(fieldAdded)
               g.drawString("Field added", 100, 100);
          else
               g.drawString("Field not added", 100, 100);
          //////////////////////////////////////////////////

          g.setColor(Color.black);
          g.drawLine(3, 30, 503, 30);
          g.drawLine(3, 30, 3, 530);
          g.drawLine(503, 30, 503, 530);
          g.drawLine(3, 530, 503, 530);

          ///////////////////////TEST///////////////////////
          if (field[1].x != 0 && field[1].y != 0 && field[499].x != 0 && field[499].y != 0)
               g.drawString("field[1].x = " + field[1].x + ". field[1].y = " + field[1].y + ". field[499].x = " +
               field[499].x + ". field[499].y = " + field[499].y + ".", 50, 50);
          else
               g.drawString("1 or more values = 0...", 50, 50);
          //////////////////////////////////////////////////
     }

     public boolean mouseDown(Event evt, int x, int y)
     {

          return true;
     }
}


import java.awt.Rectangle;

public class Rect extends java.awt.Rectangle
{
     Rect(int x, int y, int widht, int height)
     {
          super();
     }

     int nr;

     boolean explored;

     boolean isSite;
     boolean isResource;
     boolean isMountain;
     boolean isForest;
     boolean groupPresent;

     int sitePlace;
     int resPerTurn;
     int resTurns;
     int numSite;
     int numResource;
     int numGroup;
}
0
 
Vincent_SelsAuthor Commented:
Ok I got a lot further now; I have the cells and they can contain new properties, they are selectable and easy editable... just what I wanted.

I'll accept on of your answers lawrie, because you first mentioned the rectangle system... thanks again !
If I encounter other problems I'll post them here to.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 5
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now