Suppose I am building a chess game and creating board space objects. I am creating objects like so, precisely 64 for all spaces on the chess board:
BoardSpace a1 = new BoardSpace("black", 1, 1, true);
Here is the class I've created for the BoardSpace object:
public class BoardSpace {
String color;
int x_pos;
int y_pos;
boolean occupied;
//constructor
public BoardSpace (String color, int x_pos, int y_pos, boolean occupied) {
this.color = color;
this.x_pos = x_pos;
this.y_pos = y_pos;
this.occupied = occupied;
}
}
I create all my BoardSpace objects prior to moving chess pieces on the board. My chess piece objects each have an x position and y position. What I want to do is convert their coordinates into a BoardPiece name, and then retrieve a previously-created BoardPiece object from that name.
This is what I want to do:
static String get_BoardSpace_color(int x_pos, int y_pos){
int modified_x = x_pos + 96; //adjusting for ASCII
char c = (char)(modified_x);
String space_name = ""+c+y_pos;
BoardSpace piece = (BoardSpace)(space_name); //PROBLEM AREA
return piece.color;
}
How can I, using the correct string representation of the already existing object's name, actually RETRIEVE THAT OBJECT?
gridand simply get thegrid[x_pos][y_pos]object?enuminstead ofstringfor your color variableListor maybe an array. And access them there then, for examplelist.get(4)orarray[4].