繁体   English   中英

使用适当的OOP模式在Java中构建游戏

[英]Using proper OOP patterns to build a game in Java

我正在创建一个游戏,该游戏需要游戏的某些部分与其他部分进行交互。 这是我的声明。

world = new World();
player = new Player(world);
touchpad = new Touchpad(player);
background = new Background(player);
  • player需要来自world信息才能处理碰撞(修改玩家的位置)。
  • touchpad需要参考播放器,以控制/修改其位置。
  • background需要有关播放器位置的信息,以便根据其位置更改颜色。

我不确定这是否是正确的方法。 我读过一些东西,我的声明不应该依赖于上面写的内容,而是应该可以随意移动并仍然起作用。 这个对吗?

我不确定到底要去哪里。 是否应该将某些类中包含的某些信息放在其他地方? 我是否应该创建更多的类来进一步分解当前的内容? 我这样做是完全错误的,应该采取其他方法吗?

我读过一些东西,我的声明不应该依赖于上面写的内容,而是应该可以随意移动并仍然起作用。

这听起来像是在主张松散耦合 通常这很好。

例如 ,此TouchPad类只能用于移动Player

public class TouchPad {
   public TouchPad(Player player) {
   }
}

TouchPad可以控制类实现了Controllable对象。

public interface Controllable {
   void move(int x, int y);
}

public class TouchPad {
   public TouchPad(Controllable player) {
   }
}

public class Player implements Controllable {

这比较干净,因为它限制了TouchPad可用的Player的功能。 而且TouchPad不知道它在控制Player

您可以采用两种方法,首先编写代码,然后“重构”它,使其更加宽松,或者使您的方法更加宽松。 单元测试 / 测试驱动开发时,默认情况下,您倾向于前者。

您在上方创建的是一个有关系的 因此,我认为对自己进行描述可以帮助您-像这样:

Controller controller = new Keybord(); //use interfaces. There may be more controllers in the future.
Player player = new SinglePlayer(controller); //as a person who plays a game. Maybe interface won't be needed. Player has a controller rather than controller has a player.

Hero hero = new SomeHero();
Word world = SomeUglyWorld(hero); //a world has a hero rather than a hero has a world. World can define something like gravity and so on.
Level level = new SomeLevel(world); //level can begin, end, have some check points. Level has a world -> has a hero.
Level level = new SomeOtherLevel(theSameOrDifferentWorld);
Game game = new Game(player, listOfLevels);  //as a game itself, it can iterate through the levels, start/stop them. Game has levels -> worlds -> heros. Game has a player.

以上所有(游戏除外)都是使用接口创建的。

我认为这可以帮助您并且非常重要,因为您将能够灵活地切换级别/英雄/世界。 您不会在对象之间建立牢固的联系(世界只会知道它可以对英雄做什么,而不会知道如何完成)。

保持类尽可能的小也是很有用的,这样每个类都负责程序的一小部分。 方法也一样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM