The right way to OOP. An example of a game. Player :: walk or Map :: playerWalk?

Suppose there is a game. There is a card class and a player class. The map stores fields and fields of shops. Which would be the right way to do in OOP. When is the method responsible for the player walking going to be Player :: walk or Map :: playerWalk?

As for the first example (Player :: walk), it seems that this is the right way to make it like in real life - its a player who walks, but he will need to access the destination field through a map instance, check if he can go there walk, remove it from the launch field and add it to the destination field, I got the impression that Player "knows too much."

+4
source share
3 answers

Ultimately, it is a design issue, both can fit well with the OOP paradigm.

I try to place methods in the class that are most intelligently understood semantically. In this case, this means Player::walkif the card does not do something to make the “players” move (that is, in the game with flippers, the game board makes the ball [aka 'player]] move), and then it can be more meaningful have this object, for example Board::movePlayer.

You must give a copy of the card to the player if you are going for design Player::walk. So you get Player::walk(Map &map /*more parameters here, maybe a direction or vector speed?*/).

Another thing is that you should try to tell more than you ask. This means that instead of:

//in Player::walk
if (map.cells[wantToWalkTo] == 0) {
    map.cells[wantToWalkTo] = this.playerId;
}
//TODO: handle failed moves

You should do something like:

bool moved = map.moveTo(position, this); //encapsulate the logic for moving a player to a position
//TODO: handle failed moves
+3
source

"" . Map . , (, , , ). , , .

Python-ish :

class Player:
    def __init__(self, Map, location):
        """Create a player, and tell them what Map they live on."""
        self.Map = Map
        self.location = location

    def walk(self, destination):
        """Try to walk to the destination."""
        path = self.Map.path_visible(location, destination)

        if path:
            self.location = destination

class Map:
    def path_visible(self, location, destination):
        """Can a player at location see how to get to the destination?"""
+1

, - , :

  • , - /
  • / .

The logic of the player's movement must be completely in the Player's class. Therefore, checking whether the target field is accessible by the player, whether it is empty, etc., Must be processed by the player using the information provided by the map interface or other classes. Consider, for example, a situation where you want to allow a player to walk on walls, walk on water or similar things - this is the player who changes, not the map!

0
source

All Articles