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.
Related
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?
I am meant to create a game in Java that specifically uses looping Arraylists to create a 4x4 grid. I have a Grid class, made up of an ArrayList of 4 Rows, a Row Class made up of an ArrayList of Squares, and Squares Class. As well as other classes of objects, such as a hero and various enemies that will move to a random adjacent spot on the grid or "board" on each new turn.
I have methods in place to randomly assign starting positions, to find all possible adjacent positions and then select a random position out of those possible positions, etc.
The end product should look similar to this:
Is a GUI necessary or is there a much more primitive, simple way to model to the user the 'Grid' with the objects in their current containers?
You can use System.out.println("...") to print out the info to the terminal. You can just put everything in a String and print it out. You'll be able to see each time you make a move and see previous moves and add in more verbose info if you want. Assuming your grid is in an Arraylist grid, the following code should help you see how it can work.
for (Row row: grid){
String str = "";
for(Square square:row){
str += square;
}
System.out.println(str);
}
You can use the Java Scanner to grab input from the user instead of buttons.
I'm writing my first own chess game in Java.
My code already works for two players, manually playing from the keyboard, and I would like to expand it to a player against the computer game.
My problem is that I've never dealt with random actions.
The method which is moving a piece on the board, needs to receive 4 inputs:
two integers for the piece location, and two integers for the destination on the board.
Choosing the wrong inputs is OK since the movePiece method already checks if the integers are not out of the board's bounds, that they really reach a piece of the current player's color, that there's a piece in the coordination and its not empty, etc.
But how do I get these 4 integerss randomly? And how do I make them as closest as possible to "real" inputs (so I don't spend a lot of time disqualifying bad inputs)?
Java provides at least two options to generate random values:
http://docs.oracle.com/javase/6/docs/api/java/util/Random.html
http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#random()
E.g. to get random int values bounded by 4:
int x = new Random().nextInt(4);
int y = (int) (Math.random() * 4);
System.out.println(x + " " + y);
>> 2 3
If you really would like to create a computer player who just moves about randomly, I think it would be better to do it it like this:
Randomly select one of the existing chess pieces on the board
Compute all legal destinations to which that chess piece could move
If there are no legal destinations, choose a new piece amongst the previously not selected pieces
Randomly select one of the computed legal destinations
However, letting a computer player move about randomly is rather silly. A computer player would need to have some form of logic to compare which out of two moves is better. Implementing such logic is probably rather complex, and you're probably better off using a chess library as someone suggested in the comments.
You don't need 4 ints. You only need 1.
A way of doing this:
Iterate the pieces on the board.
For each piece, determine its available moves and stick all the available moves in a list.
Pick one move from the list at random (or at non-random, if you feel so-inclined).
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 am trying to code a Gomoku (five in a row) game in Java as an individual project. For the AI, I understand that the use of a Minimax function with Alpha-beta Pruning is a good way to approach this. However, I'm having a little trouble envisioning how this would work.
My question is this: what is a good representation for a node in a minimax tree?
I'm thinking my evaluation function will "weight" all the empty spaces on the board. It will then take the best value from that board as the node of the minmax decision tree. Am I on the right direction?
And any other tips are also welcome!
Thanks in advance!
The state space search is through the different states of the board. There are a lot of moves, since you can place a stone anywhere unoccupied. Each state can be represented as a e.g. 9x9 matrix, with 3 values -- white, black, or unoccupied. With a 9x9 board, there are therefore 3 ^ 81 possible board states.
From any board state, the number of moves is the number of unoccupied vertices. You can place a stone on any of these vertices. You can only play your own color. So, at most there are 81 possible moves .. 81 for the first move, 80 for the second, and so on. So you can search to depth 5 reasonably, and possibly more .. not too bad.
The proper representation is, as mentioned, a 2D matrix -- this can just be a 2D array of ints, with values e.g. 0 for unoccupied, 1 for white, 2 for black. ... int[9,9].
Your evaluation function doesn't sound very good. Instead, I would give points for the following:
-- get 5 in a row -- basically give it the max score for this one, since it's a win
-- 4 in a row with 2 open ends -- also max score, since opponent can't block you from getting 5.
-- 4 in a row with 1 open end -- still a very threatenning position, since opponent has to play
in one spot to block.
-- 3 in a row with 2 open ends -- very high score again
--- 4, 3, 2, 1 with both closed ends -- 0, since can't ever make 5 in a row.
and so on.
Then, you just apply the standard minimax algorithm -- i.e. alpha beta pruning -- it would be exactly the same as chess, but you have a different state space generator and evaluation function.
I'd consider an evaluation function of the following form: consider each set of, say, 6 positions in a line. (On a 19x19 board there are 14 along each line and varying numbers from 0 to 14 along each diagonal; I think that comes to 742 of these on the whole board. My arithmetic may be wrong.) For each set there are 729 possible arrangements of black, white and empty spaces. Or, er, 378 if you take end-to-end symmetry into account. Or, er, um, fewer than that but I can't be bothered to work out how many fewer if you take black/white symmetry into account too.
So now your evaluation function will consist of a table-lookup for each block of 6 stones, in a 378-or-however-many-element table (or perhaps two of them, one for horizontal and vertical lines, one for diagonal ones). Add up the results and that's your evaluation of the position.
It may turn out that actually a larger table (derived from a longer row of positions) works better.
But what goes in the table? Let your program work that out. Start with arbitrary values in the table (you might, e.g., take eval(line) = #black(line)-#white(line) or something). Let your program play itself, using alpha-beta search. Now update the table entries according to what happens. There are many different ways of doing this; here are a (sketchily-described) few.
During each game, keep track of how many times each pattern occurred in each player's positions. When the game's over, adjust each pattern's score so that patterns seen more often by the winning player look better.
Each time you do a search, adjust the scores for the patterns in the current position to bring the current static score nearer to the score obtained by search.
Each time a move is made, adjust the scores for each pattern in the "before" position to make the "before" score match the "after" score better.
Have lots of different tables (hence lots of different variants of the evaluation function). Let them play against one another. Apply some sort of evolution (e.g., play all against all, then throw out the worst performers and replace them with mutants derived from the better performers).
For a more sophisticated version of these ideas (applied to chess, but the same ideas would work fine for gomoku), take a look at http://cs.anu.edu.au/~Lex.Weaver/pub_sem/publications/knightcap.pdf .