Search code examples
xnadecoupling

How best to decouple objects in, for example, a 'snake' game


I am creating a snake game in C#/XNA for fun but it's a good opportunity to practice some good object design.

Snake Object

There's a snake object which is essentially a linked list, each node being a vector with X & Y co-ordinates which relate to the map.

Also a few properties such as whether the snake has just eaten (in which case, the last body node is not removed for this update), direction that the snake is moving in etc.

Map Object

The map (game area) holds its contents inside 2D array of integers - using an array of primitives to store the map should keep down memory consumption and be quicker (and easier) to iterate over than an array of vectors.

Contents are defined inside an enum {Empty, Wall, Snake, Food} which are then stored inside the array at the relevant co-ordinates.

A reference is also kept to the snake object within the map so that every call to render, loops through the nodes that make up the snake and render it into the correct position on the map.

Question!!

My question is... is this coupling too tight, in which case are there any suggestions (i.e. observer pattern) or is it okay for this situation...

I've tried to think of a way to decouple the snake from needing to know the co-ordinate system being used by the map, but can't think of a way to make it work and keep the positions each nodes relative to each-other.

Any answers appreciated, cheers!


Solution

  • "is this coupling too tight?" No, it isn't.

    In this case, the code required to decouple it is bigger, more complicated, and harder to maintain than the code required to simply implement it with the coupling.

    Furthermore, there is always going to be some level of coupling required. Coupling to "a coordinate system" is usually one of them in game development. You could, in fact, rigorously decouple your map and snake objects (again, not worth the effort), but they still need to share a common coordinate system in order to communicate.