Java OOD and code duplication

前端 未结 2 1131
走了就别回头了
走了就别回头了 2021-01-29 10:48

I started creating a basic roleplaying game, and now I work on the basics. I have a code duplication for creating new characters and for existed character, which is a very bad t

2条回答
  •  不知归路
    2021-01-29 11:03

    Whilst this is not a direct solution to your problem, this should help you in the long run. When it comes to games, especially RPG genre, where you have lots of objects which seem to be similar yet different, inheritance isn't best foundation for design. On top of the example you have, one will also have problems when designing consumable items / weapons / gear / NPC, etc. This means you end up with having duplicate code in many classes simply because using abstract class would mean all subclasses have same behavior, but this is not true.

    A better approach in this case is to avoid inheritance and use ECS. This means everything is a type of Entity. In order to add some "functionality" to an entity you would use Component types. For example, items don't have HP property, but say when dropped on the ground, they can be attacked and destroyed. Meaning we need to add a dynamic property to it. We can do that as follows:

    entityItem.addComponent(new HPComponent(50));
    

    This will allow other systems like Attack/Damage to "see" that the entity has HP component and can be attacked.

    This is just a tiny example of ECS and there's lots more to it. I'd suggest reading more about it, as this will make game development design (for most games) significantly smoother.

提交回复
热议问题