Trying to understand and implement best OOP practices

Hi, even if I code since years, not all the time I used OOP, most of OOP i used thanks to frameworks I guess. Now I am trying to stimulate me with creating and organising objects, so I started with a mini-game in JS, a plane flying on a google-map. You may say now that ok … JS is not OOP but let’s refer only on Objects.

So until now I have this entities with properties:

  • Game

    • player
    • map
    • start()
  • Player

    • score
    • lives
    • plane = new Plane()
  • Plane

    • name
    • defaultCoordinates
    • icon
    • currentSpeed
    • maxSpeed
    • direction
    • driveLeft()
    • driveRight()
    • increaseSpeed()
    • decreaseSpeed()
    • setIcon()
    • setName()
  • GameMap

    • map
    • planes[]
    • createMarker(position, icon)
    • updatePlanesOnMap()

Until now this schema looks logic to me, what do you think? Even for me seems ok I still have some problems, on the GameMap entity I used googleMaps code and logic for initialising the map, creating markers but I can’t figured out how can I keep the google logic separated from the plane logic.

On my Game.start() I have:


this.map   = new GameMap({lat: '52.423534', lng: '17.455464'}); //with start position on those coords
this.player = new Player({name: 'Sebastian'});
this.player.plane.setName('My Plane');
this.player.plane.setIcon('plane.png');
this.player.plane.setPosition({lat: '52.423534', lng: '17.455464'});

this.map.addPlaneToMap(this.player.plane);
//and even if I tried to make something like this.player.plane.fly(); I didn’t manage to do some logic and to not include some google map code in the plane methods, so I ended with:

this.map.updatePlanesOnMap(); // which iterates all the planes and move markers

What would be your perspective about this?

1 Like

this looks fine - you seem to have encapsulated googlemaps code in GameMap so I’m not sure what else you want separated

I like to have a GameController class that owns and drives the game loop - GameController creates all game objects and injects or adds one to another to create dependencies and relationships - something like

// GameController does
let game=new Game()
let player=new Player()
let map=new GameMap()
// then this
game.addPlayer(player)
// or this
player.joinGame(game)
// also
game.setMap(map)
// then
game.init()
// game loop
while(!game.over) {
  player.fly()
  game.update()
}

When we assign some mark or point on Google maps it also returns the reference to that marker, so store that, either in player object or make an array / a lookup.
Did you add your plane as marker or what ? if marker then you can see an example here markers removal.
Yes, above is for removing the markers but if you have the reference then you can also modify it.
So, create a new method named:
this.map.updatePlaneOnMap( planeReference )