aspose file tools*
The moose likes Game Development and the fly likes Turn Based Strategy Games Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Game Development
Bookmark "Turn Based Strategy Games" Watch "Turn Based Strategy Games" New topic
Author

Turn Based Strategy Games

Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
One purpose of this thread is to help someone with tic tac toe and connect4. My approach will be to show a general strategy for turn based games, that can be used for any turn based game strategy board game.

OK Gurudas. I'm gonna write my own version of tic tac toe at the same time. And you can follow along, or just take what you need. I'll wait till you reply in the thread before I proceed.

My overall plan is gonna be to develop game components that as much as possible will be re-usable in various games. So I will save a copy of these classes untouched.

for me, the GUI comes first. The following three classes will form the starting point for any board game. You are free to use this, or use your own. Keep in mind this is just a starting point, there may be changes to the GUI later on. It's not being presented as the best possible way, it's just a way that works for me. These classes are compileable and runnable

GameFrame.java
This is just a shell. Its sole purpose is to be a container for the GUI. Instead of a JFrame class I could just as easily use a JApplet. I will try to leave this class as is. Maybe I will add some code only if it specific to a Desktop version of the game.

GameTable.java
This is my main GUI class, it extends JPanel so it can easily be loaded in a JFrame or a JApplet. The GUI will have three main sections, although the actual layout may be changed.

1. The game board
2. A control panel for any buttons or checkboxes that might be required
3. A text Area for output of text information neede during development or after the game is finished.

For now, this class will act as the listener for any event handlers that are required. Notice that the board has a mouse listener attached. This is what will let you drawn x's and o's by clicking the mouse.

GameBoard.java
This is the actual playing surface. The paintComponent() method may be quite sophisticated, depending on the game and the complexity of the piece design. For tic tac toe it will be quite simple.


ok my next step, and this applies to any board game, is to think about an internal representation of the position. Some kind of an array. When I click on a section of the board, the event handler will use some kind of formula to transform the x,y co-ordinates of the board, which is currently 400x400, into array co-rdinates, which is 3x3 in the case of tictactoe. When the array is updated, there will be a call for the board to b repainted, and the paintComponent method will get its information from the internal array, not from the mouse event handler.

After I have my internal board representation, I'll start thinking about game logic, such as negamax and alphabeta, so there will be more classes to come.
Kabir Shah
Ranch Hand

Joined: Aug 04, 2009
Posts: 125
@Fred, thank you for starting a new thread.

I understood your codes( written those in very simple manner).
Coming to internal representation, We can have array of 3x3 as 1d array of 9 elements.
and number them serially from 0-8.(or 1-9).
am I making any sense.. please correct me if I am not. more over what about the main class..
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
Gurudas Bhandarkar wrote:@Fred, thank you for starting a new thread.

I understood your codes( written those in very simple manner).
Coming to internal representation, We can have array of 3x3 as 1d array of 9 elements.
and number them serially from 0-8.(or 1-9).
am I making any sense.. please correct me if I am not. more over what about the main class..


Yes, you make sense. It can be done either way.

if you use a single dimension array with length 9 then the transformation to a two dimensional array would be

row = index/3;
column = index%3;

Do you know how to transform from x,y co-ordinates of mouseClick on the board, to array co-ordinates?

right now I'm working on the alphaBeta code for this, it should be ready for tomorrow, touch wood.

p.s. the main class is the JFrame shell, it has the main method. We will not be touching the main method. Such is the true nature of event driven programming, in my opinion.
Kabir Shah
Ranch Hand

Joined: Aug 04, 2009
Posts: 125
no i dont know how to make that conversion. I would surely like to learn it.
More over after executing the the GameFrame.java, its giving me an applet with green background. and a test button which has label test. clicking on it, applet outputs test 123.
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
Yes, testing 123 is exactly what the application us supposed to do at this point. You can experiment with the mousePressed or mouseClicked event handler to see what results you get. You can also use the text area to display information such as mouse click co-ordinates, array co-ordinates etc.

OK I'll give you a hint about calculating the array co-ordinates from the mouseclick.

Working entirely within the GameTable class...

First you need the x,y co-ordinates (in pixels) of the mouseClick. Look to the methods of the MouseEvent class for that. e is the MouseEvent object.

You need to figure out the square size in pixels (width/3)

Since the x,y co-ordinates of the mouseClick are expressed in pixels relative to the top left corner of the board, and since the square size and board width is also expressed in pixels, you should be able to make a formula to determine which square you clicked in, then it is easy to relate this to the actual array co-ordinate of the square.

Also, since all this will be triggered by a mouseClick, it makes sense that these calculations can be dome in the mouseClicked or mousePressed methods. Then you can diplay your results in the text area.

Once you get that down pat, you figure out how to update the position array, and from there you think about how to write your paintComponent method in the GameBoard class to draw an x or o on the board based on the contents of the array.

Any questions, ask away.

By the time you get all that figured out, I should be ready with the negamax stuff for the computer to make moves.

As a starting point. Pot some code in the mouseClicked or mousePressed method which will display the xy co-ordinates of the mouseclick in the text area.
Kabir Shah
Ranch Hand

Joined: Aug 04, 2009
Posts: 125
Suppose we initialize the mouse co-ordinates as mouseX for x-axis and mouseY for Y axis with 0.
now as e is declared as the object of mouseListener, we can use e.getX() and e.getY() to get the co-ordinates.
Am I correct? or at least going in right direction?

Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
That sounds pretty good to me. I'll be a little more precise, and say that mouseX and mouseY are variables of type int to which e.getX() and e.getY() are assigned.

Anyways, I've pretty much got my gui the way I want it. The link is below. Give some thought as to what must be going on behind the scenes, or what I must have added to the GameTable and GameBoard classes.

In particular, the evaluate button does two things. One is kind of obvious, the other is not so obvious.

http://fchess.uuuq.com/test1/tictactoe.htm
Kabir Shah
Ranch Hand

Joined: Aug 04, 2009
Posts: 125
Ya the gui is good but then, I guess the code is yet to be completed.
about two buttons, I found that rest is normally a newGame and repaint and evaluate is to evaluate the position(game over or not). In text field, if x won then it displays the message and similarly for o. but the game doesnot point out for a draw. and also the game continues even if its won by either of the players.
-Please also do you mind to share the code with me abt the updated gui?
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
You are correct the code is not complete. But notice this. When you complete a row yes you can continue to make plays. But, if you click evaluate button after the row is complete, then the method that is called does determine if the game is over, and it prevents you from making any more moves. When all the different parts are working properly, then I will write the code to make it happen automatically.

There is a reason for doing things this way. I write separate methods for each aspect of the game. I have written an evaluate() method. When the button is clicked, the position string is passed to the evaluate() method and the method returns a variable. The value of that variable tells me what is the state of the game. You are correct, I forget to add a draw test, but that is easy to fix. Once the evaluate() is working properly, I do another button, and another method, to tell me what are the possible moves in the position. Then there will be one more button and method, a recursive negamax/alphabeta method, which will use the other two methods to determine the best move based on a position. Once all three methods have been tested separately. I'll put it all together to work automatically, and then I can get rid of some of the buttons.

Sure, I'll make the code available soon, no problem, I just thought you'd like the chance to work some of it out yourself first.
Kabir Shah
Ranch Hand

Joined: Aug 04, 2009
Posts: 125
I am new to the swing components.(not that i dont know it but some how, never tried to solve algorithms or create games using swings. just console oriented application, then my friend told me that the gui thing is more impressive than the console applications,I told her that the logic is same, she very well pointed out that looks are what that matter. So I thought to create this game using gui of course with your help.) So it will be better for me to study the code you have written first and then try to write some other.

also one more thing, the test button is not visible if the window is maximized.
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
Gurudas Bhandarkar wrote:I am new to the swing components.(not that i dont know it but some how, never tried to solve algorithms or create games using swings. just console oriented application, then my friend told me that the gui thing is more impressive than the console applications,I told her that the logic is same, she very well pointed out that looks are what that matter. So I thought to create this game using gui of course with your help.) So it will be better for me to study the code you have written first and then try to write some other.

also one more thing, the test button is not visible if the window is maximized.


OK, well don't maximize the window then.

Anyways, there's not much more I can show you. I have already shown you most of what you need for a GUI. I gave you the basic code for creating the framework. I showed you how to create a JButton and add it to a JPanel. I showed you how to add the JPanel to a JFrame. I showed you how to create an action handler for the Jbutton. I showed you how to put some code in the action handler for the JButton, that prints testing 123. I showed you how to write text to a text area. And on your own you came up with a plan for getting the xy co-rdinayes of a mouse click, and we talked about how that code would go into the mousePresses method.

Anyways, I'll post some code later. There also plenty on the net already In the mean time, we can deal with specific questions.

So you have a lot already. There's not much more GUI stuff to show you. Why don't you work with that for a while, try some simple stuff. Try changing the code in the event handler for the textB button. and if you have specific questions I'll help you.

ok here it is.

http://fchess.pastebin.com/f3606d6bd
http://fchess.pastebin.com/f642d0c5
http://fchess.pastebin.com/f70822fae
Kabir Shah
Ranch Hand

Joined: Aug 04, 2009
Posts: 125
You have done a fantastic job. I hope I am not asking too much from your side.
The question was why the Test button didnt appear when window was maximized,what is the reason. Now even if I maximize it all three buttons are visible.
Moreover, I would like to suggest a thing in this program, that if we are able to put icons for 'X' and 'O'. I have tried to put the icons as
Now I don't know where to put this code or exactly how to make that icon appear. Similarly I am planing for O and grid lines as well. Also if I want to put the image, where should I save this images in order that the program can access them. Later on I want to convert this game to gomoku. Its generally played on 13x13 board. and to connect 5 like tictactoe, hence tried to find some common logic to evaluate the game. to check win in columns, something like

Similarly for rows.
but when it comes to check for diagonals, I am stuck again.
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
Gurudas Bhandarkar wrote:You have done a fantastic job. I hope I am not asking too much from your side.
The question was why the Test button didnt appear when window was maximized,what is the reason. Now even if I maximize it all three buttons are visible.
Moreover, I would like to suggest a thing in this program, that if we are able to put icons for 'X' and 'O'. I have tried to put the icons as
Now I don't know where to put this code or exactly how to make that icon appear. Similarly I am planing for O and grid lines as well. Also if I want to put the image, where should I save this images in order that the program can access them. Later on I want to convert this game to gomoku. Its generally played on 13x13 board. and to connect 5 like tictactoe, hence tried to find some common logic to evaluate the game. to check win in columns, something like

Similarly for rows.
but when it comes to check for diagonals, I am stuck again.


No, you're not asking too much, I'm learning stuff from this too.

Well, if you want to use external images, then you use instances of the BufferedImage class. Then there are methods to create a BufferedImage object from an external file. Then you would use a drawImage method instead of drawOval or drawLine as I have used. See the following page for more information...

http://java.sun.com/docs/books/tutorial/2d/images/loadimage.html

as for evaluation, you will notice that first I build a string that is based on a row, column, or diagonal of the position, then I use a Regular Expression to see what kind of pieces occupy that string.
Kabir Shah
Ranch Hand

Joined: Aug 04, 2009
Posts: 125
Here is what I tried.

Still the image didn't appear so I tried to specify the entire path
like


So I got an exception of illegal escape character.

so how can I do it? Once I get this, I would like to change the grid as well to make it appear better, what say?
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
Gurudas Bhandarkar wrote:Here is what I tried.

Still the image didn't appear so I tried to specify the entire path
like


So I got an exception of illegal escape character.

so how can I do it? Once I get this, I would like to change the grid as well to make it appear better, what say?


well, You are on the right track, but there is a problem with the way you specify your path to the file. I suggest for now just put the image file in the same directory as the program, and just specify the file name. I think you can also use double slashes and keep the path, e.g. E:\\Java Programs\\gomuko\\dist\\X.gif. You should read up on escape characters in java strings. But it is better to keep the images in the directory or subdierectory of the program and specify a relative path, so you can then teh whole folder zipped up to someone else, and they might not have an E drive.

Also, you do not want to the load the file from disk every time you draw the piece. You should have two class variables, iimgX and imgO, and load the files only once at the beginning of the board class. then refer to those class variables in your drawPiece method. See what i mean?
Kabir Shah
Ranch Hand

Joined: Aug 04, 2009
Posts: 125
I did that when i used jus "X.gif", the file was in same folder as of the program.
I use netbeans for java programs, is there a different way to do it?
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
Gurudas Bhandarkar wrote:I did that when i used jus "X.gif", the file was in same folder as of the program.
I use netbeans for java programs, is there a different way to do it?


I don't follow you. You still have the problem? If the file is in the same folder as the program, then you don't need to specify the full path. Just use ImageIO.read(new File("X.gif")); Do you get the same error? a different error? does it work? I don't use netbeans, but it shouldn't make a difference. I don't think.

Kabir Shah
Ranch Hand

Joined: Aug 04, 2009
Posts: 125
Ya it happens the same thing.
As I run the program, I click on the playing area, no lines are drawn but there is 'X' on that grid.. I may not be able to explain but in short, there is X but not visible.
I ll post the code once again take a look at it.
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
Gurudas Bhandarkar wrote:Ya it happens the same thing.
As I run the program, I click on the playing area, no lines are drawn but there is 'X' on that grid.. I may not be able to explain but in short, there is X but not visible.
I ll post the code once again take a look at it.


try g.drawImage(img, x, y, null);
Kabir Shah
Ranch Hand

Joined: Aug 04, 2009
Posts: 125
no difference.
Am I missing anything very basic?
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
Gurudas Bhandarkar wrote:no difference.
Am I missing anything very basic?


please post your entire GameBoard class. thanks
Kabir Shah
Ranch Hand

Joined: Aug 04, 2009
Posts: 125
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41520
    
  53
I haven't read the whole thread, but this is a bad idea:

try {
img = ImageIO.read(new File("X.gif"));
} catch (IOException e) {
}

In I/O code you simply must handle exceptions; at least print out a warning message that something went wrong, like "System.out.println(e.getMessage())".


Ping & DNS - my free Android networking tools app
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
Ulf Dittmer wrote:I haven't read the whole thread, but this is a bad idea:

try {
img = ImageIO.read(new File("X.gif"));
} catch (IOException e) {
}

In I/O code you simply must handle exceptions; at least print out a warning message that something went wrong, like "System.out.println(e.getMessage())".


agreed, with some kind of a message we at least know where the problem is
Kabir Shah
Ranch Hand

Joined: Aug 04, 2009
Posts: 125
@Ulf&Fred
Thanks for pointing that one.
The error is "Cant read input file"

Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
Gurudas Bhandarkar wrote:@Ulf&Fred
Thanks for pointing that one.
The error is "Cant read input file"




I'm not sure what the problem is.

Make sure the file is there, in the same directory as the class files
There may be an issue with case. Make sure the case of the filename and extension match.
Make sure you have saved and recompiled the class.

Kabir Shah
Ranch Hand

Joined: Aug 04, 2009
Posts: 125
In net beans there is a folder called E:\Java Programs\gomuko\build\classes\gomuko which has all classes stored for this program. I pasted the image after downloading and recompiled the code.
As soon as I recompiled the code, The image was deleted from the folder!
Does this happen because I am using netbeans?

Which IDE do you use for Java Programs?
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41520
    
  53
"X.gif" is a relative path that depends on the current working directory. In an IDE, there's generally no telling what the working directory is, but it may very well not be what you think it is.

Run the application outside of the IDE and see what happens, or use absolute paths.
Kabir Shah
Ranch Hand

Joined: Aug 04, 2009
Posts: 125
But as Fred said, absolute path is not a good idea as when zipped and sent to some one else, he might not have that folder.
More over Netbeans creates a .jar file rather than .class file
while executing.
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
Gurudas Bhandarkar wrote:But as Fred said, absolute path is not a good idea as when zipped and sent to some one else, he might not have that folder.
More over Netbeans creates a .jar file rather than .class file
while executing.


I am 99% sure the problem is that the particular version of ImageIO.read() doesn't work with jar files, so as Ulf said you can run the program outside of netbeans without a jar file, or try this...

ImageIO.read( getClass().getResourceAsStream("X.gif") );

I use this with my chess program. But I am not sure it will work in you GameBoard class. You may to create static BufferedImage variables in your GameFrame class, and reference these variables from your drawPiece method.
Kabir Shah
Ranch Hand

Joined: Aug 04, 2009
Posts: 125
no even this is not working.

Here is the entire code
It generates exception like:Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1322)
at gomuko.GameBoard.drawPiece(GameBoard.java:62)
at gomuko.GameBoard.paintComponent(GameBoard.java:51)
at javax.swing.JComponent.paint(JComponent.java:1027)
at javax.swing.JComponent.paintToOffscreen(JComponent.java:5122)
at javax.swing.BufferStrategyPaintManager.paint(BufferStrategyPaintManager.java:285)
at javax.swing.RepaintManager.paint(RepaintManager.java:1128)
at javax.swing.JComponent._paintImmediately(JComponent.java:5070)
at javax.swing.JComponent.paintImmediately(JComponent.java:4880)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:723)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:679)
at javax.swing.RepaintManager.seqPaintDirtyRegions(RepaintManager.java:659)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:128)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)


Now when I look in the first exception I found this, if (input == null) {
throw new IllegalArgumentException("input == null!");
}


I don't know if I am making any sense or not neither do I know that I am going on right track or not, please help.
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41520
    
  53
Where does the file reside now? If you use the class/resource mechanism for loading images, then the file must be in the classpath, and that, too, might not be what you think it is when using an IDE.
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
Fred Hamilton wrote:
Gurudas Bhandarkar wrote:But as Fred said, absolute path is not a good idea as when zipped and sent to some one else, he might not have that folder.
More over Netbeans creates a .jar file rather than .class file
while executing.


I am 99% sure the problem is that the particular version of ImageIO.read() doesn't work with jar files, so as Ulf said you can run the program outside of netbeans without a jar file, or try this...

ImageIO.read( getClass().getResourceAsStream("X.gif") );

I use this with my chess program. But I am not sure it will work in you GameBoard class. You may to create static BufferedImage variables in your GameFrame class, and reference these variables from your drawPiece method.


This may not solve all of your problems, but it should be done. In your GameFrame class declare and initialize two variables, imgX & imgO in the same way you have done here, except declare them as static.

then your drawPiece method contains g.drawImage(GameFrame.imgX, x, y, null);

I can't comment on the classpath issue, I don't use netBeans and I compile from the command line, and I always group my class files together, so I don't need a classpath.
Kabir Shah
Ranch Hand

Joined: Aug 04, 2009
Posts: 125
I don't know how to compile more than 1 class in command line.
There are 4 different class made for
1.GameFrame.java
2.GameTable.java
3.GameBoard.java
4.Engine.java
when I try to compile the GameFrame.java it says cannot find symbol, GameTable.
Its like we were taught only to compile one class and then onwards we started to use IDEs.
Kabir Shah
Ranch Hand

Joined: Aug 04, 2009
Posts: 125
So I guess we can temporarily leave the image thing.
What about the alpha-beta pruning. I am excited to see it.
Also want your suggestions so as to what modifications has to be done while transforming this game to gomoku?
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41520
    
  53
You can compile multiple files using "javac *.java". If you compile single files, then any classes referenced by that class need to be on the classpath. That's accomplished through "javac -classpath /path/to/my/class/directory Engine.java". The Sun Java Tutorial covers all this in detail.
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
Gurudas Bhandarkar wrote:I don't know how to compile more than 1 class in command line.
There are 4 different class made for
1.GameFrame.java
2.GameTable.java
3.GameBoard.java
4.Engine.java
when I try to compile the GameFrame.java it says cannot find symbol, GameTable.
Its like we were taught only to compile one class and then onwards we started to use IDEs.


sigh. spend a little time learning how to work from the command line then. Turn netbeans off, and use a text editor.

http://java.sun.com/docs/books/tutorial/getStarted/cupojava/win32.html

forget classpath for now. just make sure all your tictactoe files are in the same directory.

http://chortle.ccsu.edu/CS151/cs151java.html
Kabir Shah
Ranch Hand

Joined: Aug 04, 2009
Posts: 125
kk I will do it in some free time before programing next game.
I guess I am so much dependent on netbeans that I can hardly work without that. (I know that is bad)
I will see to it later.
Is there any book which can help in programing in swing and also some with algorithms (like minimax, abp, negascout.. and much more)
Would like to develop the recursion skills and also make more intelligent games and also hope that I won't trouble you as much I did.
More over I would like to create a sort of database in which computer it self feeds the best possible moves for the current position I got no idea whatsoever it is, please help me to find the technical term for the same.
Also would like to see the alpha beta code that you created for this game if its over.
I sincerly hope that I am not taking much of your time.
Thank you for helping me and hope to learn from you and some day would like to help you back.
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
ok fair enough.

anyways, the recursion part is proving trickier than I thought it would be. Maybe today, maybe tomorrow.

As for the command line stuff. It shouldn't take more than 15 minutes to work that part out. It's the easiest part of programming in java, so I don't see why youhave to wait, considering the time we've both put into getting BufferedImages to work.

Anyways. It's your call, you can do what you want. While you are waiting for the recursion methods, you may wish to look into the the two links I provided in my previous post. The first one explains how to do command line stuff, the second one is an introduxtory java course that uses no IDE, and includes some basic chapters on GUIs and recursion.

Kabir Shah
Ranch Hand

Joined: Aug 04, 2009
Posts: 125
@Fred

I took a look.
I will work it out as you said, alpha-beta should work the same in any game no matter its chess, connect4 or any other.
So just a query, why can't we just copy paste your code that you used for chess(of course if you permit).
Also please provide me with the suggestions so as to how can I transform this into a gomoku, or I can modify the grid and the shape into gomoku variant so that even I would learn.
and then you can correct me if I go wrong, would this be alright?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Turn Based Strategy Games