【发布时间】:2018-05-09 06:00:29
【问题描述】:
我的 java 程序有一个(可能是一个简单的)问题。我正在尝试创建一个可以从一个地方移动到另一个地方的圆圈。地图是一个简单的对话游戏的一部分,上面写着“去这里”,地图应该对此做出反应。它必须使用观察者设计模式。
到目前为止,我已经在游戏中实现了地图,但我无法理解如何在使用 Observer 的同时使圆圈发挥应有的作用。感谢您的帮助
package GUI;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Circle;
import logika.Game;
import logika.IGame;
import main.Main;
import utils.Observer;
public class Mapa extends AnchorPane implements Observer{
private IGame game;
private Circle dot;
//private double posTop = 0.0;
//private double posLeft = 0.0;
public Mapa(IGame game){
this.game = game;
game.getGamePlan().registerObserver(this);
init();
}
private void init(){
ImageView obrazekImageView = new ImageView(new Image(Main.class.getResourceAsStream("/zdroje/mapa.gif"),255,255,false,true));
tecka = new Circle(10, Paint.valueOf("red"));
//this.setTopAnchor(tecka, 15.0);
//this.setLeftAnchor(tecka, 20.0);
this.getChildren().addAll(obrazekImageView, dot);
update();
}
public void newGame(IGame newGame){
game.getGamePlan().removeObserver(this);
game= newGame;
game.getGamePlan().registerObserver(this);
update();
}
@Override
public void update(){
this.setTopAnchor(this, game.getGamePlan().getCurrentPlace().getPosTop());
this.setLeftAnchor(this, game.getGamePlan().getCurrentPlace().getPosLeft());
}
}
【问题讨论】:
-
该模式背后的想法是所有观察者(或监听者)都注册一个事件。如果事件发生,它将通知所有观察者(调用他们的方法)。 观察者可以对事件做出反应。 (对比来自维基百科的UML diagram)
-
您能否更具体地说明您尝试实现的总体目标?我不明白你想如何使用该模式,因为我不明白你想要实现的目标。
-
当然。我需要点(简单的圆圈)从这里开始 i.imgur.com/lrlJqK4.jpg ,然后我需要它向左/向右/(从那里可以去的任何地方)我在对话游戏中命令。我需要它在命令后做出反应,以便它知道去哪里。我希望我很清楚,英语不是我的第一语言:-)
-
您可以编辑您的答案并包含您刚才所说的内容。我认为您应该为每个图像创建一个具体的
Observer。对于事件,您可以选择“输入命令”,然后作为观察者,如果不是您的图片则拒绝,如果是您的图片。所以这次活动将是一种public void commandEntered(String command, Circle circle)。 -
是否有可能在地图旁边有一个组合框窗口之类的东西,您可以在其中选择您想去的地方,并且点会随着您选择的任何东西移动?因此,您可以根据您在组合框中选择的内容将圆的位置编码为 xy。尽管那时似乎很难编码
标签: java design-patterns geometry observer-pattern observers