## universal function for pawns.

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

the mishanator
Posts: 209
Joined: Mon May 31, 2010 6:49 pm UTC

### universal function for pawns.

I am, for a project in my class making a server/client chess game. I have some code that looks like thig:

Code: Select all

`int Board::MoveWhitePawn1(bool first, bool kill, int x, int y){   if(!(first || kill))   {      if(whitePawn1[0] == x && (whitePawn1[1] + 1) == y)      {         whitePawn1[0] = x;         whitePawn2[1] = y;      }      else      {         return 0;      }   }   else if(first && !kill)   {      if(whitePawn1[0] == x && (whitePawn1[1] + 2) == y)      {         whitePawn1[0] = x;         whitePawn2[1] = y;      }      else      {         return 0;      }   }   else if(kill)   {      if(((whitePawn1[0] + 1) || (whitePawn1[0] - 1)) == x && (whitePawn1[1] + 1) == y)      {         whitePawn1[0] = x;         whitePawn2[1] = y;      }      else      {         return 0;      }   }   return 1;}`

the thing is, there are 16 pawns and so i have 16 of these functions (one for each pawn). is there a way to condense this? because this is like 600 lines of code
BTW: i know some of the code isn't exactly functional, also i know that there is no case for a pawn landing on another, i just started this and that remains to be worked out.

Sagekilla
Posts: 382
Joined: Fri Aug 21, 2009 1:02 am UTC
Location: Long Island, NY

### Re: universal function for pawns.

Why don't you do it the obvious way?

Make a pawn class (Even if it's a struct containing the coordinates), and pass that into a MoveWhitePawn() function.

You're doing too much work for yourself.
http://en.wikipedia.org/wiki/DSV_Alvin#Sinking wrote:Researchers found a cheese sandwich which exhibited no visible signs of decomposition, and was in fact eaten.

scarecrovv
It's pronounced 'double u'
Posts: 674
Joined: Wed Jul 30, 2008 4:09 pm UTC
Location: California

### Re: universal function for pawns.

Or you could even just have an array of pawns, and pass your function the index of the pawn you want to move.

the mishanator
Posts: 209
Joined: Mon May 31, 2010 6:49 pm UTC

### Re: universal function for pawns.

Make a pawn class

thats a good idea... though not that obvious (to me).
So then i would have a class for each type of piece, and another class for a "Board" object, where they would all interact?

Sagekilla
Posts: 382
Joined: Fri Aug 21, 2009 1:02 am UTC
Location: Long Island, NY

### Re: universal function for pawns.

the mishanator wrote:
Make a pawn class

thats a good idea... though not that obvious (to me).
So then i would have a class for each type of piece, and another class for a "Board" object, where they would all interact?

Essentially yes. This is a bit more involved but you could also create a class hierarchy.

You could create a "Board Piece" abstract base class and have the different pieces inherit from it as being a type of the above.

Then you could provide a universal "Move" method for the Board Piece class, and have your Board utilize that. Then just implement the details of your move method inside of the various subclasses.
http://en.wikipedia.org/wiki/DSV_Alvin#Sinking wrote:Researchers found a cheese sandwich which exhibited no visible signs of decomposition, and was in fact eaten.

the mishanator
Posts: 209
Joined: Mon May 31, 2010 6:49 pm UTC

### Re: universal function for pawns.

We haven't actually covered class hierarchies in class... i don't suppose it's to big a topic to figure out, is it?

Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

### Re: universal function for pawns.

Using class hierarchies in a proper, efficient way actually boils down pretty much to coding in an object-oriented way. That is a rather big topic to get into. Mostly because it takes a lot of studying to grasp the general idea (for most people), but in the case of C++ also because there are many subtleties in the syntax. If you only just started learning programming and the assigned workload for the class is not that big (say, 100 hours), then you should consider whether this project is really worth the effort to study OO design principles.

What is the focus of the class? Is it about program design, or is it just to give you a firmer grasp of procedural programming? In the former case, maybe you should put some effort in studying OO design, but do keep an eye on your time. In the latter case, leave the class hierarchies for what they are for a while and obtain the efficiency from using arrays of structs and such, like scarecrovv suggested.

A very good indicator is the way your teacher is talking about it. When I had my introductory course in C++, the teacher used the term "object orientation" as a synonym for storing data in classes that have member functions. Although it is true that classes with member functions are a prerequisite for OO design, there is much more to OO design than just that. In particular, using classes (with or without member functions) in your code just because they are classes will probably not make your code any better.
If you have the impression that your teacher is totally unaware of the distinction between OO design and "programming with classes", then stay away from the class hierarchies. It would be casting pearls before swine, and therefore a waste of your effort.
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

the mishanator
Posts: 209
Joined: Mon May 31, 2010 6:49 pm UTC

### Re: universal function for pawns.

From what I understand the class is intended to be entirely on OOP, not quite as indepth as the next one (Data Structures) but I looked at the syllabus and we are going to be getting to that pretty soon. My book has several chapters on it.

Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

### Re: universal function for pawns.

Ah, then I said nothing. Carry on.

(You would probably have come up with the idea to use classes by yourself after reading the syllabus and the book.)
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

the mishanator
Posts: 209
Joined: Mon May 31, 2010 6:49 pm UTC

### Re: universal function for pawns.

i already was using classes, i just had one big one that contained methods to move all pieces, etc.

Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

### Re: universal function for pawns.

the mishanator wrote:i already was using classes, i just had one big one that contained methods to move all pieces, etc.

So that's a good example of how not to use classes.
You'll learn better ways to use them along the way.
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

The Black Hand
Posts: 1037
Joined: Tue Feb 12, 2008 11:40 am UTC
Location: Behind you

### Re: universal function for pawns.

The key to basic OOP is the "has-a" and "is-a" relationships. The board "has a" (number of) chess pieces on it, therefore, the odds are a chess piece should be a separate class. A Pawn "is a" type of chess piece, so should probably be a subclass of the Chess Piece class. There are exceptions to these rules, but in my (limited) experience they are few and far between.

Then, you need to consider what a board actually does. The board doesn't move the pieces, it just provides places for the pieces to sit. The player moves the pieces, this suggests that the move() function/method should be a member of the piece class.

The whole thing (in an ideal OOP world) would be controlled by a Game class, which has a Rules class, and a Board class.

This brings the other massive benefit of OOP: reusability. If you wanted to make a checkers program, you would only need to write new Rules and Piece classes: the game is essentially the same: one player moves a piece, then the other; and you can use exactly the same Board for both games.

On the other hand, you could make four-player chess using new Rules, Game* and Board classes, reusing the ChessPiece classes from your first game.

This post is now probably going to be picked apart by those more skilled in Object Design than I, but I don't really mind.

*You could write the Game class in such away that it would support two or four players, but that's an exercise for the reader.
73, de KE8BSL loc EN26.

Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

### Re: universal function for pawns.

Don't bother too much with trying to make things object-oriented. These things come with experience, and learning them other than just writing lots of code is almost impossible. Just group related data together, and put the methods that use that data in the same class to begin with. Try to keep the number of data members in each class as small as possible, and don't be afraid of making small ad-hoc classes. Pondering things like "has-a" and "is-a" relationships (which are entirely useless) and class hierarchies is just wasting your time; do that after the code is written (if you have time), because it's impossible to get it right before then.

And if you disagree with some advice, no matter how smart or well-respected the source is, throw it away, or at least exlore it. Don't be afraid of experimenting.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

the mishanator
Posts: 209
Joined: Mon May 31, 2010 6:49 pm UTC

### Re: universal function for pawns.

that sounds like pretty reasonable advice =) thanks. it's coming along quite nicely actually.

the mishanator
Posts: 209
Joined: Mon May 31, 2010 6:49 pm UTC

### Re: universal function for pawns.

I have a question now. So I have a class for each piece, how can I manage the positions of the pieces in such a way that the "move" method would not permit a piece to be on the same tile as another? Could there be some sort of manager specifically for this that each piece's class is a part of? so like i could call a single function that stores the most current positions of everything to check against...

Sizik
Posts: 1260
Joined: Wed Aug 27, 2008 3:48 am UTC

### Re: universal function for pawns.

You could have the pieces tell the board where they move, and if the square they are moving to is occupied, it would capture the piece/return an "invalid move" message.
she/they
gmalivuk wrote:
King Author wrote:If space (rather, distance) is an illusion, it'd be possible for one meta-me to experience both body's sensory inputs.
Yes. And if wishes were horses, wishing wells would fill up very quickly with drowned horses.

_Axle_
Posts: 253
Joined: Fri Sep 24, 2010 7:33 pm UTC

### Re: universal function for pawns.

I would suggest some kind of gameboard, where after a piece is picked and moved, it will first decide if it is a legal move of that type of piece. Then check if some other piece is already on that spot, then its either a capture if its opposite yours, or a failure of a move if its yours.

The gameboard should keep the state of the board ( likely 2d array ) at all times, and if it is networked, you should make sure they are synched ( not that hard for turn based, but its a good practice to expect the worst of games ).
Yakk wrote:Computer Science is to Programming as Materials Physics is to Structural Engineering.

the mishanator
Posts: 209
Joined: Mon May 31, 2010 6:49 pm UTC

### Re: universal function for pawns.

well i was thinking the same sort of thing. for example, here is the move method for the rook (which can go up/down as much as one wants)

Code: Select all

`void Rook::move(int x, int y){   if((x >= 1 && x <= 8) && (y >= 1 && y <= 8))   {      if((position[0] == x && position[1] > y) || (position[1] == y && position[0] > x))      {         position[0] = x;         position[1] = y;      }   }}`

to move it, a new position is passed as an argument. this method doesnt work because it merely checks the new position to make sure it is valid. a more effective way would be to loop through the entire path to see if any object occupies any of the tiles in between. however, i do not have anything to check against...

_Axle_
Posts: 253
Joined: Fri Sep 24, 2010 7:33 pm UTC

### Re: universal function for pawns.

oh yeah, I am rusty at chess.

Though, Only pieces that collision matters are the Queen, Rook and Bishop ( if I remember right ) and there would have to be a loop. Though the loop is simple.
Yakk wrote:Computer Science is to Programming as Materials Physics is to Structural Engineering.

the mishanator
Posts: 209
Joined: Mon May 31, 2010 6:49 pm UTC

### Re: universal function for pawns.

Yes, but the final position of EVERY piece must be checked after the move method is called. Again though, how would I check in the loops? The final positions would be easy to check when then move is actually called (in the Board class). BTW, the relationship between the piece's classes and the board class, is that sort of inheritance?

_Axle_
Posts: 253
Joined: Fri Sep 24, 2010 7:33 pm UTC

### Re: universal function for pawns.

Code: Select all

`class GameBoard{public:bool ValidMove(GamePiece gp, int x, int y);private:int board[x][y]; // 0 if empty, 1 if player 1, 2 if player 2GamePieces AllPieces[32];         // I think its 32?};`

The pieces are data members in your board class. That is at least how I would approach this problem.
Yakk wrote:Computer Science is to Programming as Materials Physics is to Structural Engineering.

bieber
Posts: 223
Joined: Thu Mar 13, 2008 12:13 am UTC

### Re: universal function for pawns.

the mishanator wrote:Yes, but the final position of EVERY piece must be checked after the move method is called. Again though, how would I check in the loops? The final positions would be easy to check when then move is actually called (in the Board class). BTW, the relationship between the piece's classes and the board class, is that sort of inheritance?

Nope, aggregation. A rook, for instance, "is-a" chess piece, but the relationship between the board and pieces is that the board "has-many" pieces.

_Axle_
Posts: 253
Joined: Fri Sep 24, 2010 7:33 pm UTC

### Re: universal function for pawns.

hate to spam post . . .

Only major inheritance would try for chess is :

Code: Select all

`class GamePiece{public:GamePiece(Type);virtual void Move(int x, int y) = 0;GetType();private:[code][/code]int Type; // Enum of what type it is};Class Pawn : GamePiece{public:void Move(int x,int y);private:};`

I am not checking for compiling, just quickly typing this up
It is mostly pseudo code
Also, for checking your game piece moves

Code: Select all

`bool ValidMove(GamePiece* gp, int x, int y){  int type = gp->GetType();  vec2 pos = gp->GetPosition();  int player = gp->Owner();  if(type == ROOK || type == QUEEN || type == BISHOP) // check to see if you need loop through   {// Setup x,y increments depending on type and direction        while(!(end-1) )        {           if(board[x][y])              return false; // Something was in that spot for moving, invalid move           inc x,y;        } // end while   } // end if   // Check final position for all types   // Handle empty case -> Valid move, update board and piece   //            Your piece -> Invalid move   //            Enemy piece -> Valid move, update board, and both pieces}`
Yakk wrote:Computer Science is to Programming as Materials Physics is to Structural Engineering.

the mishanator
Posts: 209
Joined: Mon May 31, 2010 6:49 pm UTC

### Re: universal function for pawns.

Hate to sound dumb, but what does "->" do?

_Axle_
Posts: 253
Joined: Fri Sep 24, 2010 7:33 pm UTC

### Re: universal function for pawns.

the mishanator wrote:Hate to sound dumb, but what does "->" do?

o.O
Its dereferencing from a pointer.

Code: Select all

`struct/class Foo{  int data;};Foo a;a.data;   // ValidFoo* b = &a;b->data; // Validb.data // Invalid`

Just curious, is this for a class, and what language are you planning on using ( to make sure I don't confuse you with C/C++ stuff ).
Yakk wrote:Computer Science is to Programming as Materials Physics is to Structural Engineering.

the mishanator
Posts: 209
Joined: Mon May 31, 2010 6:49 pm UTC

### Re: universal function for pawns.

Well, so far it's for my entertainment... eventually maybe i'll use it as a final project for my class. The language is C++.

i thought "*" was the magical wand of dereferencing... what is the difference?

_Axle_
Posts: 253
Joined: Fri Sep 24, 2010 7:33 pm UTC

### Re: universal function for pawns.

* does dereference. Though to access structure/class data/methods, you need to follow with a .
(*b).data is the same as b->data , it just dereferences to methods/data
Yakk wrote:Computer Science is to Programming as Materials Physics is to Structural Engineering.

the mishanator
Posts: 209
Joined: Mon May 31, 2010 6:49 pm UTC

### Re: universal function for pawns.

ahhh... i get it. what about when i see it in c code? c isnt object oriented...

_Axle_
Posts: 253
Joined: Fri Sep 24, 2010 7:33 pm UTC

### Re: universal function for pawns.

structs aren't part of any OO design, but they exist in basic C. So, if given a pointer to a struct, you have to use (*). or -> to get the data from it.
Yakk wrote:Computer Science is to Programming as Materials Physics is to Structural Engineering.

the mishanator
Posts: 209
Joined: Mon May 31, 2010 6:49 pm UTC

### Re: universal function for pawns.

oh okay. i thought structs were just classes where everything was public though

Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

### Re: universal function for pawns.

RoadieRich wrote:The key to basic OOP is the "has-a" and "is-a" relationships. The board "has a" (number of) chess pieces on it, therefore, the odds are a chess piece should be a separate class. A Pawn "is a" type of chess piece, so should probably be a subclass of the Chess Piece class. There are exceptions to these rules, but in my (limited) experience they are few and far between.

That's a simple and elegant way to look at it. I have never been aware of these rules of thumb, although I think I applied them intuitively. Thanks for the new insight.

Still, it doesn't fully capture all essential features of OO, like information hiding, encapsulation, dynamic binding and inheritance. Also, it doesn't logically entail the special kind of outsourcing that appears in many OO design patterns. Like in the case of moving the game piece: the piece evaluates whether the move is legal, and after that the board checks whether the move is possible and whether it would be a capture.
If you state encapsulation explicitly, the outsourcing will follow more directly: the piece is the right entity to determine whether a move (of itself) is legal, while the board is the right entity (has the right knowledge) to determine whether the move is possible and what would be its result.

the mishanator wrote:oh okay. i thought structs were just classes where everything was public though

In modern C++, this is true. Traditionally however, structs are just custom container types for heterogenous data. That's the reason why their members are public by default: usually you want to access the data directly. Classes, on the other hand, were invented specifically for OOP, and their members are private by default to promote information hiding. Therefore, it is recommended to use a class whenever the type will have its own behaviour or provide any form of data abstraction. Using structs as classes should be considered poor style.
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

Posts: 3072
Joined: Mon Oct 22, 2007 5:28 pm UTC
Location: Beaming you up

### Re: universal function for pawns.

This isn't entirely on the topic, but your code doesn't handle En Passant.
<quintopia> You're not crazy. you're the goddamn headprogrammingspock!
<Weeks> You're the goddamn headprogrammingspock!
<Cheese> I love you

the mishanator
Posts: 209
Joined: Mon May 31, 2010 6:49 pm UTC

### Re: universal function for pawns.

That wouldnt be a hard feature to add ( i dont think)

on a side note (well still related), this is my class for a rook

Code: Select all

`class Rook {private:   int position[2]; // x and y coordinates of where it is (i decided to not use the alphabet).   bool side; // is it white or black?   bool state; // has it been captured?public:   Rook(bool Side, int x, int y); // when object is created, it's given a position and a side.   void move(int x, int y); // move to new position.   int getPositionX(); // get new x.   int getPositionY(); // get new y.   void kill(); // if it's captured, mark it as killed.   bool isAlive(); // is it active?};`

The classes for each piece are the same, and most of the functions are the same too. Really only the move methods are different. If i were to make them inherit getPositionX(), getPositionY(), kill(), and isAlive() from a GamePiece class, would that be more effective (i read up on class inheritance) furthermore the GamePiece class could contain an array of all the positions of all the pieces for my other problem. is this a good idea? or should i keep doing what i'm doing?

bieber
Posts: 223
Joined: Thu Mar 13, 2008 12:13 am UTC

### Re: universal function for pawns.

If you're going to create a GamePiece class to derive the others from, it should never actually be instantiated, but rather serve as a common base that holds data and methods common to all game pieces. For instance, it should contain the coordinates of the piece, whether it's still in play, and probably a pure virtual method to move the piece. Then you inherit that class in your individual piece's classes and they automatically inherit those data members and methods.

Also, I would really encourage you to use separate x/y or row/col coordinates, or something like

Code: Select all

`struct{    int x;    int y;} coords;`

Using a simple array like that, all you have to do is mix up which index corresponds to which coordinate once and you'll find yourself with a bug that will be almost impossible to hunt down.

the mishanator
Posts: 209
Joined: Mon May 31, 2010 6:49 pm UTC

### Re: universal function for pawns.

I would really encourage you to use separate x/y or row/col coordinates

Will do!

This is what it looks like so far though:

Code: Select all

`class Piece {private:   int x;   int y;   bool side;   bool state;public:   Piece(bool Side, int X, int Y);   int getPositionX();   int getPositionY();   void kill();   bool isAlive();};class Pawn: public Piece {private:   int x;   int y;   bool side;   bool state;public:   void move(bool first, bool kill, int X, int Y);};...`

I was wondering, is there a way to access private members of the Piece class in the Pawn class (for example)? because i have this twice:

Code: Select all

`...private:   int position[2];   bool side;   bool state;...`

Axidos
Posts: 167
Joined: Tue Jan 20, 2009 12:02 pm UTC
Location: trapped in a profile factory please send help

### Re: universal function for pawns.

the mishanator wrote:I was wondering, is there a way to access private members of the Piece class in the Pawn class (for example)? because i have this twice:

Code: Select all

`...private:   int position[2];   bool side;   bool state;...`

Use protected instead of private.

Public: accessible by anything and inheritable.
Private: accessible only by the same class, not inheritable.
Protected: accessible only by the same class and its children, and therefore inheritable.

the mishanator
Posts: 209
Joined: Mon May 31, 2010 6:49 pm UTC

### Re: universal function for pawns.

<impressed>That's really cool...</impressed>

the mishanator
Posts: 209
Joined: Mon May 31, 2010 6:49 pm UTC

### Re: universal function for pawns.

well i have a class thats basically like this:

Code: Select all

`class Piece {protected:      int position[2];      bool side;      bool state;      bool occupied[8][8];public:      Piece(bool Side, int x, int y);      int getPositionX();      int getPositionY();      void kill();      bool isAlive();      int getOccupied(int x, int y);};class Pawn: public Piece {public:      void move(bool first, bool kill, int x, int y);};`

then from main, to test this code i did this:

Code: Select all

`int main() {      Pawn::Piece one(1, 2, 3);      one.move(0,0,3,1);      for (int i = 0; i <= 7; i++) {            for (int j = 0; j <= 7; j++) {                  cout << one.getOccupied(i, j);            }            cout << endl;      }      return 0;}`

and i get this compile error: error: ‘class Piece’ has no member named ‘move’

so i try this:

Code: Select all

`int main() {      Pawn::Piece one(1, 2, 3);      one.Pawn::move(0,0,3,1);      for (int i = 0; i <= 7; i++) {            for (int j = 0; j <= 7; j++) {                  cout << one.getOccupied(i, j);            }            cout << endl;      }      return 0;}`

and it tells me: error: ‘Pawn’ is not a base of ‘Piece’

what is the proper way to do this?

Also: don't derived classes inherit constructors? why then would i even have Pawn::Piece one(1, 2, 3); instead of Pawn one(1, 2, 3);?

bieber
Posts: 223
Joined: Thu Mar 13, 2008 12:13 am UTC

### Re: universal function for pawns.

the mishanator wrote:well i have a class thats basically like this:
Also: don't derived classes inherit constructors? why then would i even have Pawn::Piece one(1, 2, 3); instead of Pawn one(1, 2, 3);?

You shouldn't, and that's probably what's causing your problems. The correct form is

Code: Select all

`Pawn one(1,2,3);one.move(...);...`

However, that probably won't work either because your Pawn class needs a constructor, which in turn needs to call the base class constructor in its initialization list, like this

Code: Select all

`void Pawn::Pawn(bool side, int x, int y): Piece(side, x, y){...}`

Jplus
Posts: 1721
Joined: Wed Apr 21, 2010 12:29 pm UTC
Location: Netherlands

### Re: universal function for pawns.

A few remarks.

1. In reaction to bieber: constructors don't have a return type, so the "void" shouldn't be there. The rest of the story however is correct.

2. You can make working with board positions even more efficient by defining a global type:

Code: Select all

`struct position {    char x;    char y;};`

So you can just pass around position objects instead of separate x and y values. Like this:

Code: Select all

`class Piece {protected:      position pos;      bool side;      bool state;      bool occupied[8][8];public:      Piece(bool Side, position p);      position getPosition();      void kill();      bool isAlive();      int getOccupied(position p);};class Pawn: public Piece {public:      void move(bool first, bool kill, position p);};`

3. Actually, in a truly OO design it would be even better to give Pieces no knowledge at all about their position... because, afterall, the board is already keeping track of their positions. Same story for whether positions are occupied or not (if you do it like this, every piece will be keeping a private registry of which positions are occupied; not efficient and also error-prone!).
However, you can't do everything completely right at the very first time... so you may ignore this point for now.
"There are only two hard problems in computer science: cache coherence, naming things, and off-by-one errors." (Phil Karlton and Leon Bambrick)

coding and xkcd combined

(Julian/Julian's)

### Who is online

Users browsing this forum: No registered users and 11 guests