0

New to oop. Writing in Python 3.

I am developing a multiplayer game. These are the classes I need:

  • a class 'server' - which is the main entry point from which all starts
  • a class 'game', that contains the game logic
  • a class 'gameroom' to allow multiple simultaneous games to run
  • a class 'player' with all the players details
  • a class 'session' which is the combination of player and game, containing player related info while playing

diagram of classes

It seems obvious that session should be a child of both player and gameroom. However, how does an instance of session know which instance of gameroom and player are its parents?

Suppose:

  • I have 5 player instances with playerIDs 1,2,3,4 and 5
  • I have 2 intances of gameroom with roomIDs 1 and 2.

Now I want an instance of 'session' for playerID = 2 and roomID = 2. How do I 'pass' the roomID and playerID to the new instance of session?

Is this the correct implementation? Or can I somehow implicitly create an instance of session without needing to save player and room in a variable?

from player import player
from room import room

class session(player,room):
    def __init__(self, player: player, room: room):
        self.point = 0
        self.player = player
        self.room = room
        print('player {} has joined room {}'.format(player.id,room.id))
Jimmy
  • 209
  • 2
  • 8
  • 2
    TBH it’s not obvious that a session is a specialized player - what about multiplayer games where the session has several players - that phrasing tells me the player(s) are an attribute of a session, i.e. there’s no inheritance. And in general My suggestion is to avoid multiple inheritance and deep inheritance trees as much as possible. – DisappointedByUnaccountableMod Apr 25 '20 at 15:35

2 Answers2

2

Inheritance is not the right tool here. You should just pass a player and a room instance to the __init__ method of session.

Inheritance is used to model extensions of classes. If one class inherits another, e.g. Car inherits Vehicle and you instantiate a Car object with car = Car(), car is also an instance of Vehicle.

You can read more on this topic in the application section of the wikipedia article on inheritance.

Erich
  • 1,838
  • 16
  • 20
0

Something like this, assuming that Player and Room have instance attributes name and roomID

class Session(Player,Room):
    def __init__(self, name, roomID ):
        Player.__init__(self, name)
        Room.__init__(self, roomID)
        self.point = 0
        print('player {} has joined room {}'.format(name,roomID))
Julia
  • 981
  • 1
  • 8
  • 16