OOP for chess game? [closed] - oop

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I came across such a OOP design on web(a brief version):
public abstract class ChessPieceBase {
abstract boolean canBeChecked();
abstract boolean isSupportCastle();
}
public class King extends ChessPieceBase { ... }
public class Queen extends ChessPieceBase { ... }
public class Position { // represents chess positions in compact form
ArrayList<ChessPieceBase> black;
ArrayList<ChessPieceBase> white;
}
public class ChessPieceTurn { };
public abstract class PlayerBase {
public abstract ChessPieceTurn getTurn(Position p);
}
class ComputerPlayer extends PlayerBase {
public ChessPieceTurn getTurn(Position p) { return null; }
}
public class HumanPlayer extends PlayerBase {
public ChessPieceTurn getTurn(Position p) { return null; }
}
public class GameManager {
void processTurn(PlayerBase player) { };
boolean acceptTurn(ChessPieceTurn turn) { return true; };
Position currentPosition;
}
I have some difficulty understanding the design, not knowing if i did not understand OOP or understanding chess :(. From top to bottom:
ChessPieceBase is the abstract base class for all pieces, king, queen, rook, bishop, knight, and pawn, right? so i see King and Queen extend ChessPieceBase.
Position, according to comments, should record a global current positions of pieces for black and white. It is implemented as an arraylist of ChessPieceBase, but ChessPieceBase does not contain any position info member, so where is position info stored?
what's ChessPieceTurn? if it's a 'my turn, your turn' concept, why getTurn() func in player class need 'Position p' parameter and return null?
GameManager class. 'currentPosition' record a global state of the game, 'acceptTurn()' does not seem to do anything, 'processTurn()' get turn from player and handle like referee. Hope i understand this last one correct.
And if possible, can someone write a little main() function to show how it works? At this time i am just confused.
Any idea from you on how you see what classes should look like for chess game are welcome,
Thanks,

Related

Open/Close principle and polymorphism

The Open/Closed Principle states that software entities (classes, modules, etc.) should be open for extension, but closed for modification. I learned about this today and my teacher said that this concept is intrinsically connected to the concept of polymorphism. I canĀ“t really see how both concepts are connected, can anyone explain please?
Here's my exaplanation.
Look at the following example:
public interface IShape
{
void Draw();
}
public class Square : IShape
{
public void Draw()
{
// DRAW SQUARE
}
}
public class Circle : IShape
{
public void Draw()
{
// DRAW CIRCLE
}
}
public class Renderer
{
public void DrawShapes(ICollection<IShape> shapes)
{
foreach (var shape in shapes)
{
shape.Draw();
}
}
}
This code is open to extensions and closed to modifications therefore it follows the OCP principle. Why? In case you need to make the application able to draw a new shape (e.g. Triangle), you don't need to modify the DrawShapes method of the Render class.
You only need to create a new class "Triangle" that implements the interface IShape and pass it to the DrawShapes method.
This code is also polymorphic because the "DrawShapes" method does not need to know the types of the shapes that it is rendering.
Pay attention to one thing: the closure of the O.C.P. principle is always strategic. What does it mean? It means that you cannot have code that is 100% closed to modifications. Example: what happens if you need to draw all the squares before the circles? In that case you have to modify the DrawShapes method; maybe with a Strategy pattern you can inject the policy to sort the drawing of the shapes.

Understanding Abstract Factory Design pattern [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
in Abstract Factory design pattern , a class delegates the responsibility of object instantiation to another object via composition.
can some one explain it with some example.
I'll tell you a traditional example about that. Imagine you have a UI library. It have implementation of different UI components like buttons, sliders, radio buttons, etc. You also want to have different look-and-feel of these components, for example silver, dark, light, windows-like, gtk-like etc. You can use an abstract class which makes the common things for each component's creation and child classes which inherit from the abstract and specifies only the differences:
class AbstractComponentFactory {
public abstract Button createButton() {
//implementation
}
public abstract Slider createSlider() {
//implementation
}
}
class SilverComponentFactory extends AbstractFactory {
public Button createButton() {
Button b = base.createButton();
//customize the button
}
public Slider createSlider() {
Slider b = base.createSlider();
//customize the slider
}
}
class WindowsComponentFactory extends AbstractFactory {
public Button createButton() {
Button b = base.createButton();
//customize the button with windows look-and-feel
}
public Slider createSlider() {
Slider b = base.createSlider();
//customize the slider with windows look-and-feel
}
}
Now if you need to create components you can change dynamically the implementation of the Abstract factory:
public void createUI(AbstractComponentFactory f) {
Button b = f.createButton();
Slider s = f.createSlider();
}
//..
createUI(new SilverComponentFactory());
Here is a sample class diagram, I hope it's not so complex.

How to identify an object and make a relationship among them [c#] [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
What is the best way to identify the objects and their Relationship between them ?
As i am new to Programming[c# windows application],I am finding difficult in making relationship between objects .
Can anyone suggest me the best way to start with?
Thanks,
Karthik
You should probably read up on object oriented programming and design. Then read up on C# programming.
Here are a few book suggestions:
Head First Object Oriented Analysis and Design
Beginning C# 3.0: An Introduction to Object Oriented Programming
Then when you're ready, you can move on to Jon Skeet's book =)
If you're not looking to purchase a book, maybe take a look at this site. It covers key object oriented design principles.
I'll try and point you in the right direction with a contrived example:
Suppose we want to make a simple management application for supermarket staff. We are required to store some personal information and work-related information, so we'll need name, address, date started, department, and position.
So now we can try and summarise this specification and think about how to model each bit of data.
StaffMember
Name
Address
Date Started
Department
Department
Name
Position
Position
Title
Roles
Now we can map these ideas to c# classes and use properties to hold the bits of data we need:
class StaffMember
{
public string Name { get; set; }
public string Address { get; set; }
public DateTime DateStarted { get; set; }
public Department Department { get; set; } // class Department
}
class Department
{
public string Name { get; set; }
public Position Position { get; set; } // class Position
}
class Position
{
public string Title { get; set; }
public string PrimaryRole { get; set; }
}
Sample usage:
static void Main()
{
StaffMember employee = new StaffMember();
employee.Name = "Ali Gray";
employee.Address = "123 Abc Street";
employee.DateStarted = DateTime.Now;
// Now add the employees department
employee.Department = new Department();
employee.Department.Name = "Checkout";
// Now add the employees position
employee.Department.Position = new Position();
employee.Department.Position.Title = "Bag Packer";
employee.Department.Position.PrimaryRole = "Pack bags";
}
Obviously this is an extremely simplified example, but hopefully it'll help you on your way to understanding oo design.

Object Oriented Design for a Chess game [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I am trying to get a feel of how to design and think in an Object Oriented manner and want to get some feedback from the community on this topic. The following is an example of a chess game that I wish to design in an OO manner. This is a very broad design and my focus at this stage is just to identify who is responsible for what messages and how the objects interact each other to simulate the game. Please point out if there are elements of bad design (high coupling, bad cohesion etc.) and how to improve on them.
The Chess game has the following classes
Board
Player
Piece
Square
ChessGame
The Board is made up of squares and so Board can be made responsible for creating and managing Square objects. Each piece also is on a square so each piece also has a reference to the square it is on. (Does this make sense?). Each piece then is responsible to move itself from one square to another.
Player class holds references to all pieces he owns and is also responsible for their creation (Should player create Pieces?) . Player has a method takeTurn which in turn calls a method movePiece which belongs to the piece Class which changes the location of the piece from its current location to another location. Now I am confused on what exactly the Board class must be responsible for. I assumed it was needed to determine the current state of the game and know when the game is over. But when a piece changes it's location how should the board get updated? should it maintain a seperate array of squares on which pieces exist and that gets updates as pieces move?
Also, ChessGame intially creates the Board and player objects who in turn create squares and pieces respectively and start the simulation. Briefly, this might be what the code in ChessGame may look like
Player p1 =new Player();
Player p2 = new Player();
Board b = new Board();
while(b.isGameOver())
{
p1.takeTurn(); // calls movePiece on the Piece object
p2.takeTurn();
}
I am unclear on how the state of the board will get updated. Should piece have a reference to board? Where should be the responsibility lie? Who holds what references? Please help me with your inputs and point out problems in this design. I am deliberately not focusing on any algorithms or further details of game play as I am only interested in the design aspect. I hope this community can provide valuable insights.
I actually just wrote a full C# implementation of a chess board, pieces, rules, etc. Here's roughly how I modeled it (actual implementation removed since I don't want to take all the fun out of your coding):
public enum PieceType {
None, Pawn, Knight, Bishop, Rook, Queen, King
}
public enum PieceColor {
White, Black
}
public struct Piece {
public PieceType Type { get; set; }
public PieceColor Color { get; set; }
}
public struct Square {
public int X { get; set; }
public int Y { get; set; }
public static implicit operator Square(string str) {
// Parses strings like "a1" so you can write "a1" in code instead
// of new Square(0, 0)
}
}
public class Board {
private Piece[,] board;
public Piece this[Square square] { get; set; }
public Board Clone() { ... }
}
public class Move {
public Square From { get; }
public Square To { get; }
public Piece PieceMoved { get; }
public Piece PieceCaptured { get; }
public PieceType Promotion { get; }
public string AlgebraicNotation { get; }
}
public class Game {
public Board Board { get; }
public IList<Move> Movelist { get; }
public PieceType Turn { get; set; }
public Square? DoublePawnPush { get; set; } // Used for tracking valid en passant captures
public int Halfmoves { get; set; }
public bool CanWhiteCastleA { get; set; }
public bool CanWhiteCastleH { get; set; }
public bool CanBlackCastleA { get; set; }
public bool CanBlackCastleH { get; set; }
}
public interface IGameRules {
// ....
}
The basic idea is that Game/Board/etc simply store the state of the game. You can manipulate them to e.g. set up a position, if that's what you want. I have a class that implements my IGameRules interface that is responsible for:
Determining what moves are valid, including castling and en passant.
Determining if a specific move is valid.
Determining when players are in check/checkmate/stalemate.
Executing moves.
Separating the rules from the game/board classes also means you can implement variants relatively easily. All methods of the rules interface take a Game object which they can inspect to determine which moves are valid.
Note that I do not store player information on Game. I have a separate class Table that is responsible for storing game metadata such as who was playing, when the game took place, etc.
EDIT: Note that the purpose of this answer isn't really to give you template code you can fill out -- my code actually has a bit more information stored on each item, more methods, etc. The purpose is to guide you towards the goal you're trying to achieve.
Here is my idea, for a fairly basic chess game :
class GameBoard {
IPiece config[8][8];
init {
createAndPlacePieces("Black");
createAndPlacePieces("White");
setTurn("Black");
}
createAndPlacePieces(color) {
//generate pieces using a factory method
//for e.g. config[1][0] = PieceFactory("Pawn",color);
}
setTurn(color) {
turn = color;
}
move(fromPt,toPt) {
if(getPcAt(fromPt).color == turn) {
toPtHasOppositeColorPiece = getPcAt(toPt) != null && getPcAt(toPt).color != turn;
possiblePath = getPcAt(fromPt).generatePossiblePath(fromPt,toPt,toPtHasOppositeColorPiece);
if(possiblePath != NULL) {
traversePath();
changeTurn();
}
}
}
}
Interface IPiece {
function generatePossiblePath(fromPt,toPt,toPtHasEnemy);
}
class PawnPiece implements IPiece{
function generatePossiblePath(fromPt,toPt,toPtHasEnemy) {
return an array of points if such a path is possible
else return null;
}
}
class ElephantPiece implements IPiece {....}
I recently created a chess program in PHP (website click here, source click here) and I made it object oriented. Here are the classes I used.
ChessRulebook (static) - I put all my generate_legal_moves() code in here. That method is given a board, whose turn it is, and some variables to set the level of detail of the output, and it generates all the legal moves for that position. It returns a list of ChessMoves.
ChessMove - Stores everything needed to create algebraic notation, including starting square, ending square, color, piece type, capture, check, checkmate, promotion piece type, and en passant. Optional additional variables include disambiguation (for moves like Rae4), castling, and board.
ChessBoard - Stores the same information as a Chess FEN, including an 8x8 array representing the squares and storing the ChessPieces, whose turn it is, en passant target square, castling rights, halfmove clock, and fullmove clock.
ChessPiece - Stores piece type, color, square, and piece value (for example, pawn = 1, knight = 3, rook = 5, etc.)
ChessSquare - Stores the rank and file, as ints.
I am currently trying to turn this code into a chess A.I., so it needs to be FAST. I've optimized the generate_legal_moves() function from 1500ms to 8ms, and am still working on it. Lessons I learned from that are...
Do not store an entire ChessBoard in every ChessMove by default. Only store the board in the move when needed.
Use primitive types such as int when possible. That is why ChessSquare stores rank and file as int, rather than also storing an alphanumeric string with human readable chess square notation such as "a4".
The program creates tens of thousands of ChessSquares when searching the move tree. I will probably refactor the program to not use ChessSquares, which should give a speed boost.
Do not calculate any unnecessary variables in your classes. Originally, calculating the FEN in each of my ChessBoards was really killing the program's speed. I had to find this out with a profiler.
I know this is old, but hopefully it helps somebody. Good luck!

Managing inter-object relationships

How do you code special cases for objects?
For example, let's say I'm coding an rpg - there are N = 5 classes. There are N^2 relationships in a matrix that would determine if character A could attack (or use ability M on) character B (ignoring other factors for now).
How would I code this up in OOP without putting special cases all over the place?
Another way to put it is, I have something maybe
ClassA CharacterA;
ClassB CharacterB;
if ( CharacterA can do things to CharacterB )
I'm not sure what goes inside that if statement, rather it be
if ( CharacterA.CanDo( CharacterB ) )
or a metaclass
if ( Board.CanDo( CharacterA, CharacterB ) )
when the CanDo function should depend on ClassA and ClassB, or attributes/modifiers with ClassA/ClassB?
i would start with a canSee(Monster monster) or canBeSeenBy(Monster monster) method and see what happens. you may end up with a Visibilility class or end up using the http://en.wikipedia.org/wiki/Visitor_pattern. an extreme example is uncle bobs triple dispatch:
// visitor with triple dispatch. from a post to comp.object by robert martin http://www.oma.com
/*
In this case, we are actually using a triple dispatch, because we have two
types to resolve. The first dispatch is the virtual Collides function which
resolves the type of the object upon which Collides is called. The second
dispatch is the virtual Accept function which resolves the type of the
object passed into Collides. Now that we know the type of both objects, we
can call the appropriate global function to calculate the collision. This
is done by the third and final dispatch to the Visit function.
*/
interface AbstractShape
{
boolean Collides(final AbstractShape shape);
void Accept(ShapeVisitor visitor);
}
interface ShapeVisitor
{
abstract public void Visit(Rectangle rectangle);
abstract public void Visit(Triangle triangle);
}
class Rectangle implements AbstractShape
{
public boolean Collides(final AbstractShape shape)
{
RectangleVisitor visitor=new RectangleVisitor(this);
shape.Accept(visitor);
return visitor.result();
}
public void Accept(ShapeVisitor visitor)
{ visitor.Visit(this); } // visit Rectangle
}
class Triangle implements AbstractShape
{
public boolean Collides(final AbstractShape shape)
{
TriangleVisitor visitor=new TriangleVisitor(this);
shape.Accept(visitor);
return visitor.result();
}
public void Accept(ShapeVisitor visitor)
{ visitor.Visit(this); } // visit Triangle
}
class collision
{ // first dispatch
static boolean Collides(final Triangle t,final Triangle t2) { return true; }
static boolean Collides(final Rectangle r,final Triangle t) { return true; }
static boolean Collides(final Rectangle r,final Rectangle r2) { return true; }
}
// visitors.
class TriangleVisitor implements ShapeVisitor
{
TriangleVisitor(final Triangle triangle)
{ this.triangle=triangle; }
public void Visit(Rectangle rectangle)
{ result=collision.Collides(rectangle,triangle); }
public void Visit(Triangle triangle)
{ result=collision.Collides(triangle,this.triangle); }
boolean result() {return result; }
private boolean result=false;
private final Triangle triangle;
}
class RectangleVisitor implements ShapeVisitor
{
RectangleVisitor(final Rectangle rectangle)
{ this.rectangle=rectangle; }
public void Visit(Rectangle rectangle)
{ result=collision.Collides(rectangle,this.rectangle); }
public void Visit(Triangle triangle)
{ result=collision.Collides(rectangle,triangle); }
boolean result() {return result; }
private boolean result=false;
private final Rectangle rectangle;
}
public class MartinsVisitor
{
public static void main (String[] args)
{
Rectangle rectangle=new Rectangle();
ShapeVisitor visitor=new RectangleVisitor(rectangle);
AbstractShape shape=new Triangle();
shape.Accept(visitor);
}
}
Steve Yegge has an awesome blog post about the Properties pattern that you could use handle this. In fact, he wrote an RPG using it!
http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html
You might say player1 is a type1 and type1s can attack type2s and player2 is a type2, so unless there is some "override" on the specific player1, player1 can attack player2.
This enables very robust and extensible behavior.
What is the definition of "see"? If they occupy the same square? If so, this will be answered in how you implement collision detection (or whatever in this case) rather then OOP relationships between characters. Without knowing more information, I would approach the problem in this manner (in C++/pseudo code for illustration):
class Character {
private:
matrixSquare placement;
public:
Character() {};
~Character {};
matrixSquare getLocation() { return placement;};
};
class GameBoard {
private:
//your 5 x 5 matrix here
public:
GameBoard() {};
~GameBoard() {};
boolean isOccupied(matrixSquare)
{
if (occupied)
{
//do something
return true;
}
else
{
return false;
}
}
};
The trick here is to define the relationship between your character pieces and your implementation of the playing field. After that is established you could then clarify how you determine if two characters are in the same square, adjoining squares, etc... Hope that helps.
I would say use design patterns, generally I think Observer, Mediator and Visitor patterns are quite good for managing complex inter-object relationships.
I would (assuming C++) give each class a std::string identifier, returned by a getter method on the class's instance, and use a std::map< std::pair<std::string, std::string>, ... > to encode the special cases of relationship between classes, all nice and ordered in one place. I'd also access that map exclusively through a getter function so that changing the strategy for encoding some or all of the special cases is made easy as pie. E.g.: if only a few pairs of classes out of the 25 have the "invisibility" property, the map in that case might contain only the few exceptions that do have that property (for a boolean property like this a std::set might actually be a preferable implementation, in C+_).
Some OO languages have multi-dispatch (Common Lisp and Dylan are the two that come to mind at the moment), but for all the (vast majority) of languages that lack it, this is a good approach (in some cases you'll find that a centralized map / dict is restrictive and refactor to a Dynamic Visitor design pattern or the like, but thanks to the "getter function" such refactorings will be pretty transparent to all the rest of your code).
In response to your edit of your question, you'll want to look into polymorphism. I personally would have the cando() function be a part of the Board, then, depending on the two classes passed in, the Board would call the appropriate function and return the result (of battle, of seeing, so on and so forth).
If you're doing this in java an enum/interface to go along with your Game Board would be a very clean way of approaching this problem.
I suggest you look at double dispatch pattern.
http://c2.com/cgi/wiki?DoubleDispatchExample
The above example explains how a group of printers can print a group of shapes.
http://en.wikipedia.org/wiki/Double_dispatch
The wikipedia example specifically mentions solving adaptive collision problems with this pattern.