Design a Chess game (using OOPS and Java Design Pattern) - java

Can someone help me build a chess game from the scratch using Java OOPS and Design patterns concepts.
A rough model is enough.
Are there any links/blogs for this?

First of all, this is a very broad question.
Second, Object Oriented approaches are somewhat slow, which will decrease the engines play strength.
That said, here is roughly what you need:
- a piece class, or an enum, or something similar
a chessboard class, where you can place and move pieces
a move generator, this is a function that lists all legal moves of a chessboard
an evaluation function that "rates" chesspositions, wheter black or white has an advantage
a minimax function, (see google "minimax algorithm"), that returns the best move in a position
some kind of gui for the whole thing
For more info, see the chessprogramming wiki.

I would have a class for the games map, a class for a figure (and childclasses for tower, king aso.). Also probably a class for the player.

Related

Does an evaluation function for a chess game consider all pieces on the board?

I hope this is an easily answered question, but I am slightly confused about how an evaluation function for a chess game works. I am using a minimax algorithm that evaluates the board at the leaf nodes, taking into account material, piece-square tables, mobility, etc. Does an evaluation function for a minimax algorithm (not negamax) take into account every piece on the board, both black and white, to calculate a board value or does it just look at the pieces of the minimser(black) or maximiser(white).
For instance, do I sum the material of both black and white or just whichever side's turn it is when the evaluate_board() method is called?
I apologise if this is confusing, but I am new to this. Even a little bit of clarification would be much appreciated. Thankyou.
The evaluation of a position can take anything into account. If you use minimax, you might want negative scores to be good for white and postive for black -- or something like that. So if you only use material to evaluate, you could count each white piece as -N and each black piece as +N. And the starting position is 0.
Keep in mind that even with pruning, minimax can take a long time if you go even a few ply (depths). So the cheaper or faster the evaluation method is, the better. Simple material advantage IMHO is the only evaluation you'll need.
Of course the chess wiki has a thorough article on the evaluation part of a chess engine: https://chessprogramming.wikispaces.com/Evaluation

Chess game design and Singleton pattern

I am currently creating a chess game consisting of the following classes:
ChessPiece - For all the various chess pieces, composed with a MovementBehaviour instance variable
MovementBehaviour - Interface implemented by PawnMovementBehaviour,
KingMovementBehaviour etc classes to define
how each piece type moves
ChessBoard - Consisting of a ChessPiece[][] 2D array with functionality like addPiece()/removePiece()/replacePiece() etc
Player - Small class helps associate which pieces belong to which human player
Game - The main class essentially which will begin by asking players for their names and desired piece colors and then running the
game by instantiating a ChessBoard and letting players move turn by
turn until checkmate is reached.
I was wondering if I should be using a Singleton pattern (With regards to the ChessBoard class) ? Currently I am not and I am passing the instance of the ChessBoard into the chess pieces movement functionality so that the piece can understand its surroundings. This is because of course moves are deemed legal depending on what spaces are occupied/empty on the board at any time.
Singletons are very rarely a good idea. I happen to have started a similar project recently so I will answer this from my current experience.
The way I've implemented it is by considering a chessboard a collection of Location objects, where a location holds an X-value, Y-value and a Piece object. Only relevant places are filled in where empty ones aren't even tracked.
You seem to be wondering if you should use a singleton for the single purpose of validation. There are many, many things you have to validate when a move is done: Can you move that way? Are you check? Is it en-passant? Is it a rochade? etc.
What you could do is create a bunch of validate methods that take as arguments a chessboard and the start- and endlocation. This way you have all information required to check if the move is valid. This does require the pieces to know their own properties: how can I move? What's my color?
When you have all this, you can implement the different validation logic to make a move.
Using a singleton will be rather nasty when you could just extract the validation and pass the chessboard around. It would also be much harder to test (and good testing is definitely something you want in a chessgame).
My setup looks like this:
Chessboard.CanMoveToLocation(int startX, int startY, int endX, int endY) {
// Call validators with local field chessboard and given location objects
}
Each validator will return a custom enum ValidationResult to indicate if it's allowed or forbidden for this particular validator.
You'll have to make sure the validators are called in the correct order (returning false after checking if it's a valid move is not a good idea: he might have been rochading or slaying en-passant). Or you could ofcourse combine related validators.
Should you wish to take a look: my current (far from finished) implementation.
In my experience, I'd rather use Observer Pattern in this case.
The ChessBoard class plays the role of Observer and the ChessPiece which should be an abstract class is the Subject class. You might want to make a look on Observer Pattern and it usage
When you take one Piece and make a movement, that means the location of that Piece has been changed and the Piece will notify to the board to check the movement whether it is valid or not.

designing a project in java

I don't know exactly how to design a project. It's my first year at my computer science department. I'm still learning a lot of information about Java, such as inheritance, polymorphism, abstract classes, interfaces, and so on. I am really curious about these lectures and I'm willing to learn them well. Actually I've not missed any point in these lectures and I got those very well. But nobody teach me how to desing a project and we are supposed to design a decent Java project at the very end of school.
I and my 3 classmates have decided to make a new game. It is played with only one ball and the ball has changeable two colours. Also two players have the same colour with this ball's colours. When the ball is at one player's colour, this player will be able to move the ball and try to score to another player's goal. These are our idea's basic logic and we can add some new facilities and options for this game. We are so willing to achieve this project. But... although we listen and learn from our lectures, we are really confused about to design this project step-by-step. I've just tried to demonstrate our project's logic. Meanwhile, we are still learning about GUI but we are at the very beginning of GUI. So I want to understand about what kind of ways we have to follow in order to design and make this kind of project. I just want to know about tricks and shortcuts and make the most of our knowledge about class hierachies, abstract classes, superclasses, overriding, etc.(We know everything about this terms but just don't know how to use them to design a project). If you can indicate even a little info about these, I would be so so so happy and able to change my point of view. And it would facilitate our progress. Thank you!
You might want to have a look at this Java Pong Game - it's pretty simple and includes some source code that you can study.
More general advice:
You need some way to display what is happening in the game. Probably the easiest way to display the screen in a very simple game is to use a JPanel and override it's paintComponent() method to draw the game screen correctly (e.g. draw players at the right x,y locations)
You will also need a game loop that should do the following things:
Reads any input from players
Update the positions of the objects in the game
call repaint() on the JPanel so that the screen gets redrawn
Waits a short amount of time using e.g. Thread.sleep(30) to sleep for 30 milliseconds
Loops back to the start of the game loop
I would recommend separating the classes that define the user interface (frames, panels etc.) from classes that define the game logic (players, balls etc.). Ideally the game logic classes shouldn't contain any code that relates to how they are displayed or interacted with.
For a game this simple, you don't actually need many classes. I'd recommend something like:
App - contains the main(...) function which launches the game. At a minimum it should create a JFrame and add a single GamePanel inside it, but you can create other UI elements if you like. You may choose to implement your game loop also in this class - in which case the main method should call this once all the setup has been done.
GamePanel (which extends JPanel) - contains the screen drawing logic, also perhaps detects mouse movement
Game - class that represents the entire state of the game, including the locations of both players and the ball
Player - small class to represent the player, with x,y co-ordinates
Ball - small class to represent the ball, with x,y co-ordinates and dx,dy velocity
GUI isn't really suitable for making a game.
a GUI (Graphical User Intreface, Swing in java) is a set of buttons and other text/image content, as opposed to something you can make a game with: a 3D rendering engine, such as OpenGL (most commonly used on java, be it in a framework or through low level libraries).
You here have a choice:
you can either decide to do a simpler project, for example a console program, but that will run on a GUI, for example a GUI program to move files.
or you can get to learning OpenGL or similar (JOGL for java) and make that game!
(JavaFX also might work, but I don't know much about it)
Now about design.
Generally you want to have a main "looping" class that will output every frame etc.
The main "looping" class should inherit from an interface that allows all other components to get the rendering particle, the time counter etc.
Then you want several components, one for the ball, one for any other physics object (don't forget to make them implement a "physics" interface and add them as "physical object references" in your main class, so that the physics for them are calculated each frame!), one for the background, and one for user input.
You can also add multiple others that will each do a specific action.

Collision Detection in Java for a game

Im making a game in Java with a few other people but we are stuck on one part of it, making the collision detection. The game is an RPG and I know how to do the collision detection with the characters using Rectangles, but what I dont know how to do is the collision detection for the maps. What I mean by that is like so the character cant walk over trees or water and that stuff but using rectangles doesnt seem like the best option here.
Well to explain what the game maps are gonna look like, here is an example http://i980.photobucket.com/albums/ae287/gordsmash/7-8.jpg
Now I could use rectangles to get bounds and stop the player from walking over the trees and water but that would take a lot of them.
But is there another easier way to prevent the player from walking over the trees and obstacles besides using Rectangles?
Here's a simple way but it uses more memory and you do the work up front... just create a background collision mask that denotes the permissible areas for characters to walk on in a binary form. You can store that in some sort of compressed bitmap form. The lookup then is very simple and very quick.
Rectangle collision detection seems to make sense; However, alternatively you may also try sphere-sphere collision detection, which can detect collision much quicker. You don't even need a square root for distance computations since you can compare the squared distances to see if the spheres overlap. This is a very fast method, and given the nature of your game could work very well.
ALSO! Assuming you have numerous tiles which you are colliding against, consider some method of spacial partitioning. Let me give you an easy example - subdivide your map into several rectangles (http://www.staff.ncl.ac.uk/qiuhua.liang/Research/Pic_research/mine_grid.jpg) and then depending on which rectangular area your player is currently residing in - check collision only against the tiles which are located within that area.
You may take it a step further - if you have more tiles in any given area than the threshold that you set - subdivide that area further to make more smaller areas within it.
The idea behind such subdivision is called Quadtree, and there is a huge quantity of papers and tutorials on the subject, you'll catch on very quickly.
Please let me know if you have any questions.
There are many solutions to this type of problem, but for what you're doing I believe the best course of action would be to use a tile engine. This would have been commonly used in similar games in the past (think any RPG on the SNES) and it provides you with a quick and easy means of both level/map design and collision detection.
The basic concept of a tile engine is that objects are stored in a 2D array and when your player (or any other moving game entity) attempts to move into a new tile you perform a simple check to see if the object in that tile is passable or not (for instance, if it's grass, the player may move; if it's a treasure chest, the player cannot move). This will greatly simplify checking for collisions (as a naive check of a list of entities will have O(n^2) performance). This picture might give you an idea of what I'm talking about. The lines have been added to illustrate a point, but of course when you're playing the game you don't actively think of everything as being composed of individual 32x32 pixel tiles.
While I don't personally have any experience with tile engines in Java, it looks like Mappy supports Java, and I've heard good things about PulpCore. You're more than welcome to create your own engine, of course, but you have to decide if your effort is better spent reinventing the wheel (but, of course, it will be your wheel then, and that is rather satisfying) or spend your time making a better game.

Java swing small 2D game: how to modelize the view?

In a small java swing 2D game, what is the best solution for creating the board view?
Use a component for the board and custom paint it and each square of the checker at once?
Use a component for the board and create another component modelizing the square with its own paint component doing the job for the square only. Use a layout to place each Square instance in the board?
I know this is subjective and I don't want a fight about it. I just need some clues to figure myself which way I should go. I've begun a side project and I've using 1), with the feeling that there is something wrong.
Just go with one drawing panel/container for everything.
Consider a tile based game. Using your second solution each tile would be an object, memory would skyrocket and the game would slow to a crawl.
Using the first option you are flexiable. You draw what you want, you have the panel coordinates so everything is relative to this. Using the tile based example you'd know the height and width of the panel, draw your square and increment in the X and Y coordinates as appropriate.
GUI frameworks such as Swing or .NET's Winforms are expensive as they have a whole lot of other stuff that a game won't need. So to answer your question, go with option one, rather than say using a panel for every checker on your board.
One nice solution to using the second method, in combination with the first method is the Flyweight Design Pattern. You still get to use OO objects, but you'll have a fraction of the amount you normally would. Check it out.
Like Finglas, I lean toward your first approach. This tile-based game is a concrete example. In contrast, this component-based game uses a GridLayout of JToggleButton. The former is somewhat more complex but plays well even on large screens; the latter is simpler yet sufficient for reasonable games. You may have to experiment with your game's geometry and logic to decide which to prefer.

Categories