I am currently working on creating a chess game in android studio - in Java. I have a board class which contains a 2D array of tiles. Each of these tiles has the possibility (optional variable) to contain a piece. The piece class has sub classes for the different type of pieces.
I am now working on populating the board with the pieces and was wondering if there is some sort of effective way of doing this? I can run through the array with a massive switch case but that just seems dumb.
Also, later on I plan to develop an AI to play against and it would be useful to be able to easily input random board positions to test its capabilities.
Any advice?
Concider I have an incomplete 2d array, with some of it's cells blocked, like this:
I want to fill that array with given tetris like shapes (perfect solution not guaranteed), those are the rules:
Path always connected, no "holes"
Pieces are pre-known and are enough to cover exactly 100% of path (if fitting)
Pieces can be rotated and flipped, makes it 8 different ways to place each piece
My question is, how can I brute-force it and ensure I actually checked all the variations?
My plan was to start from left top corner and seek for the next empty cell in a loop.
But then I don't know what to do when i get stuck. Maybe store placed pieces in a stack and try different ways but the fact I can both rotate pieces and change their places was too much for me. Working with java in case that's matter. thanks!
First of all, I am not sure whether it is allowed to ask this kind of question. So I am trying to create a board game and I was stuck at the implementation of generating valid moves for Piece. Here is the extract of the class diagram.
You can think this board game like chess, so we need to know the location of other pieces while generating valid moves. The problem is I have no idea how to check it. Is my class diagram wrong? Or should I check at the board every time I check a square? And how do I do that in Java? Thanks for helping.
The piece should not decide what its valid moves are, it should only be aware of where it is and how it's capable of moving. It is not responsible for that sort of logic.
The board should manage whether or not that's allowed or not (that is, it takes a piece which returns its possible moves to it, and in turn returns the valid moves).
The Piece class exposes a getPossibleMoves method that returns the list of positions it can reach:
public List<Square> getPossibleMoves(){ // might want to differentiate types of moves
Then, the board class has a getValidMoves method that takes a piece and returns its valid moves.
public List<Square> getValidMoves(Piece piece) {
return piece.getPossibleMoves().
stream(). // and filter by
filter(move -> isOnValidBoardCoordinate(move)). // can shorten
filter(move -> doesNotIntersectOtherPiece(move)).
filter(move -> otherValidation(move)).
collect(Collectors.toList());
}
Over the past few days, I've coded a (horribly patched together) text RPG game in Java. The positioning in the world is pretty much controlled by a simple 100x100 2D array of Strings. I then convert the Strings into actual objects when the player actually comes upon the grid.
What I have in mind is to have a graphic display showing this 100x100 grid with an image in each section of the grid that corresponds with what is in the array.
For example, if the String at block[10][15] is "rock", the graphic display section of the grid at row 10, column 15 would show a picture of a rock.
Ideally, this graphic would refresh every time I loop in my do-while loop. Oddly, what I have in mind is something that looks remarkably similar to the early pokemon games.
I apologize if my description is badly worded or my question too ambiguous. I have only learned java for half a semester in my computer science course, so my knowledge is limited to the basics we learned in the one semester. I do like to pursue various projects outside of class, like the text chess game that I (proudly) coded. I prefer to create everything from scratch so that I can learn the basics before using various libraries.
Could somebody please point me in the right direction for what I am looking for or offer a better way to go after this display?
Thank you very much in advance. Please let me know if a reference to my code would better help answer my question.
Firstly,you can use enums instead of strings as mentioned by Jack above. Eg
private enum Objects{
Rock(1),Coin(8),Med(45)...and so on
}
In your array, you may store these objects as numbers rather than strings.
eg:
boolean stopFlag=false;
do{
//check each element of your world array with the enum and draw it
for(int i=0;i<yourObjectsArray.length;i++)
{
for(int j=0;j<yourObjectsArray[i].length;j++){
switch(yourObjectsArray[i][j])
{
case Objects.Rock: drawRock(i,j);
break;
case Objects.Coin: drawCoin(i,j);
break;
//and so on....
}
}
}
//you can also put this into a separate function as drawWorld() and pass the objects.
//Key press checking logic here. If user presses exit key [esc] then you set the stopFlag as true
if(keypress==KEY_ESC){ stopFlag=true;}
}while(!stopFlag);
An example of Draw Rock:
private void drawRock(int i,int j){
//i and j are the cols and row values so you need to resolve them to coordinates.
//I am assuming u have a 800*600 screen and you mentioned that your world is 100x100 array. Then each of your object is 8*6 units in size so
xCoord=i*8;
yCoord=j*6;
//So if you have to draw a rock on [10][15] it will resolve as
//xCoord=10*8-> 80
//yCoord=15*6-> 90 so it will draw your rock in (80,90) on the screen
//Now you can either open the rock image from your disk now or u maintain one instance of rock at the beginning of the program so that you can use the same image later rather than opening it everytime you encounter a new Rock object in your array.For now I will open it here.
String path = "C:\\YourGameDirectory\\rock.jpg";
URL url = new File(path).toURI().toURL();
BufferedImage rockImg = ImageIO.read(url);
//draw it to the screen now if you have the graphics instance.
yourUIPanel.getGraphics().drawImage(rockImg,xCoord,yCoord,yourUIPanel);
// You may find many resources that teach you how to draw an image on the screen in Java. You may repeat the same for all the objects.
}
I hope the above codes helped you a-bit. If not,its my bad.
You can try this tutorial series to get started. Although its in C , it has concepts that will help u acheive what you have mentioned above.
Easiest thing to use for such tasks in my personal experience is Processing, which is a light framework which is able to provide a simple API to draw things.
There is a reference, and many tutorials so it shouldn't be that hard to get start with even if you are not expert.
As a side node: why do you use strings to store kinds of blocks? Could you use something better like an enum?
You might want to check out the source code of my old roguelike game Tyrant:
https://github.com/mikera/tyrant
Key ideas:
There is a Map class that is responsible for storing the data that represents the map. In Tyrant, the Map encapsulates storage of both the terrain and the objects places on the map.
There is a MapPanel class that shows the Map in the GUI. This is kept separate from the Map itself - it's generally a good idea to separate the GUI from your core engine data.
There is a Thing class that represents objects on the map. This includes everything from monsters, items, trees and clouds of smoke to the player character itself. Basically anything that isn't terrain.
As for refresh, the way this works is that the MapPanel repaints itself on demand, looking at the contents of the map. Check out MapPanel.paint(Graphics g) and the various methods that it calls.
I have written an Android app. It is a simple version of the old board game Connect 4. Currently my "Board" object holds the counters which have been places on the board. There are 2 players to this game.
The Board class comprises of 7 ArrayList objects, each one represents a column on the board.(the board is 7 across x 6 upwards). So for example when the red player clicks on the third column on the screen I call
boardObj.addCounter("red", column);
and inside the board object in the addCounter() function it does something like
column3.add(playerColor);
so the ArrayList column3 gets another item added and so forth.
My question is - is there a better data structure I can use as opposed to using 7 ArrayLists? I noticed that the function which checks whether there is a win, which is called after a counter is added to the board, is becoming quite an expensive function in terms of CPU. What structure would allow me to get and set the data and run my checkwin() algorithm with the best performance?
You have a 7x6 board, and you need to test for elements on the same row, column or diagonal.
A 2-dimensional array is the most obvious choice. I would use that.