Python Forum
Coding RPG Game - Need Fresh Eyes.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Coding RPG Game - Need Fresh Eyes.
#4
As mentioned by others, the issue here is relying on global variables. Your Player.create() creates a local player object, that isn't assigned to the global player variable. I have a feeling you'll have a similar issue with the Account.

The pattern you're using (kind of) is called the Singleton. You have a Player class, but you don't really expect to create more than one instance of that class. You can read more about this in The Book: https://gameprogrammingpatterns.com/singleton.html

As a side note, that entire book is very well written. The code examples are all c++, but all the code is (for the most part) very simple and designed to illustrate the point, and can be understood even if you don't know c++.

Normally, these sorts of classes are Builders, that have a GetInstance method. For your player, here's how I'd do it:
>>> class Player:
...     __players = []
...     def __init__(self, name):
...         self.name = name
...         Player.__players.append(self)
...     @classmethod
...     def get(cls, player_id=0):
...         if len(cls.__players) > player_id:
...             return cls.__players[player_id]
...         raise Exception(f"Player {player_id} does not exist.")
...
>>> me = Player('george')
>>> me
<__main__.Player object at 0x0000026450096CD0>
>>> me.name
'george'
>>> # elsewhere in our codebase...
>>> player = Player.get()
>>> player.name
'george'
This way, the class itself controls the instance, and you just ask it for that instance.
Reply


Messages In This Thread
RE: Coding RPG Game - Need Fresh Eyes. - by nilamo - Feb-11-2021, 05:31 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to begin coding for game making [Install pygame on mac] mattkrebs 2 4,990 Apr-02-2017, 10:57 AM
Last Post: machrider

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020