Question

I am designing Classic Snake game using OOPS.I will have the following classes at top level :

Game {
   Board board,
   Snake snake;
}
    
Board {
   Cell cells[];
}

Cell {
   int x,
   int y,
   Type type;
}

Type {
   SNAKE,
   FOOD,
   EMPTY
}

Snake {
   List<Cells> snakeParts;
}

I am a little confused on following point:

Can snake be part of Board class as follow?

Board {
   Cell cells[];
   Snake snake;
}

Like instead of Game class having Snake object, is it better for Board class to have snake object?Because it makes sense to say that BOARD 'has-a' snake instead of Game 'has-a' snake .

Was it helpful?

Solution

If you are trying to do Object-Orientation I would suggest a different approach.

Contrary to what structured design and entity relationship diagrams suggest, there is no inherent relationship between things in a oo system. All relationships are derived from requirements and ultimately the behavior objects must support. Without behavior it makes no sense to talk about relationships.

For example, are "food" and "snake" the same type, or implement the same interface? Depends what their behavior is. Both can be thought of as being able to be presented on the board. This is sort of similar, so they could be related types. But, I could also model that as the "snake" being something I can give directions to, and the "food" not. So in that case they would probably not be related.

So your question of "Can snake be part of Board class as follow?" is an implementation detail, not an objective fact that you can discuss just in itself. Whether it will be depends on how you choose to implement them (what "behavior" you assign to objects). Different trade-offs will lead to different designs and different relationships.

Relationships between objects is a consequence of your design, not the other way.

OTHER TIPS

If you just look at the board. I think it does not realy care if there is a snake positioned on it or an apple positioned on it. A board is a set of Cells as you pointed out and a certain sequence of Cells may form a Snake or an Apple.

I would lay the following abstraction.

  • Pattern has Cells
  • Snake is a Pattern
  • Apple is a Pattern of 1

Snake is Alive until Pattern has no double crossing (repeating cell)

Game has a Snake that is Alive. Dead Snake - Game Over.

Board is not that significant by the way as it is just an arrangment of Cells - if it is a square or Kvadrat board you can effectivly ignore it. The board abstraction may become nessessary if your board geography is non trivial.

From the perspective of the Board the only thing that matters(potentialy) is what is the geography of the Cells and if a Cell is lit or not lit.

Licensed under: CC-BY-SA with attribution
scroll top