Tom Clabault
Tom Clabault

Reputation: 502

Not sure which class I should put my method in

I'm currently working on a simple 2D grid game. The grid of the game is composed of cells. A cell can contain (among other things) a landmine or a bomb. The classes that relate to my problem are: Player ; Board and Game

This is how my classes are used within each other:

The class Game represents a game in all its details:

public class Game
{
    private Board board;

    private Player player;

    //Currently using
    public void placeMine(Player owner, int x, int y);
}

The Board class is mainly a 2D array of Cell

public class Board
{
    private Cell[][] board;
}

The Cell class can contain a mine

public class Cell
{
    private boolean containsMine;
}

The Player class represents a player. A player should be capable of placing a landmine or a bomb on the board.

public class Player
{
    //placeMine() here ?
    public void placeMine(int x, int y);
}

Now the question is : Where should I put my placeMine() method?

My "real life logic" makes me want to put placeMine() in Player as it is logically a Player who places a mine on the ground. However, doing that means that the Player class has to have access to the instance of Board (as the mine is going to be placed on the board. On a cell of the board more precisely).

Giving the Player class an instance of Board sounds very bad as a Player doesn't "possess" a Board. The instance of Board could be given to the placeMine() method as an argument but I'm not too sure how I feel about doing this.

The other alternative, which I'm currently using, is having placeMine() in Game. It is much easier to make it work this way and simpler to comprehend I believe. It feels less of an instance passing festival than if I had to pass an entire Board each time. But it doesn't really suit the intuition I have about the whole thing (which is that a Player places a mine, not that a Game place a mine).

What would be the best way of doing this if the whole point is to have a clear, understandable, scalable architecture?

Upvotes: 2

Views: 82

Answers (1)

Ian Mc
Ian Mc

Reputation: 5829

The placeMine() method belongs in the Game class.

The architecture of your game is logically divided into (Model-View-Controller):

  • Model: Board / Cell
  • Controller: Game
  • Helper classes: Player (and Mine could be another if it had other properties)

The model contains the game's state. The controller is responsible for managing each turn of the game, and updating the state accordingly. The game's actions are dealt with by the controller. While a Player is the 'owner' of a turn, and perhaps the owner of a cell, etc, it is the Game which is placing a mine on any given turn on behalf of the player, and updating the state accordingly.

Upvotes: 2

Related Questions