[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Initializing and Reinitializing Instance variables



‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐
On Saturday, May 25, 2019 8:55 PM, mspaintmaestro@xxxxxxxxx <mspaintmaestro@xxxxxxxxx> wrote:

> For just a score variable, it's probably not a big deal to have an = 0 in there twice as duplicate code, but games are complicated and so I'm sure you've got lots of other fields as well, and that's where the duplication becomes problematic, especially if it's just there to appease the linter. I'm assuming the Game object is sort of an application context that survives the entire duration of the program's runtime, and that aside from score, you have a variety of other fields as well that need to be reset. For things like this, I would split game into a 2-tiered object, where each object has the desired lifespan. Something like this...
>
> class ApplicationContext:
>   def __init__(self):
>     self.session = GameSession()
>
>   def reset(self):
>     self.session = GameSession()
>
> class GameSession:
>   def __init__(self):
>     self.score = 0
>     self.player_location = (0, 0)
>     self.zombies = self.build_zombie_list()
>     self.im_just_making_up_examples = etc
>

This looks like a possible solution, but I would advise against it. I've gone there a couple times I guess, and I ended up throwing away code that looked like this every time. Your `Game` can perfectly well deal with state itself. If you start writing state-holder objects, you'll create more work for yourself down the line. You'll think about it and then you're likely going to transparently proxy `GameSession` into `Game` using `__getattr__()`, and maybe even `__setattr__()` methods. Why, then, pretend you were dealing with attributes of your `Game` instance when you could and should just do that?

I think the best solution would be setting `self.score = None` in `__init__` and having it set to a proper value by .reset(). But I do admit that I'd probably type the line only to shut up a linter and not for any real purpose.

cheers!
mar77i


Sent with ProtonMail Secure Email.