0

我创建了一个包含所有内容的 pacman 游戏,但问题是幽灵及其动画需要大量代码。

例子:

目前,每个幽灵都需要 3 个 if 语句,即每个幽灵 20 行代码,如果我在游戏中有 3 个幽灵,则 3 x 20 = 60 行无用代码。

以我的 php 经验,我会说.. 使用 foreach 循环或类似的东西.. 但我应该如何在 Java 中做到这一点?有人可以给我一个例子吗?我现在的做法发表在下面:

创建幽灵对象;

DrawPacMan ghost1 = new DrawPacMan();
DrawPacMan ghost2 = new DrawPacMan();

这幅画是这样的:

int g1x = 0;
boolean g1r = true;
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    // pacman movement
    diameter = 75;   
    pacman.drawPacMan(g, getHorPlaats(), getVerPlaats(), diameter, getView(), Color.yellow);
    // ghosts movement
    if(g1r == true) {
        g1x += ghostSpeed;          
    }       
    if(g1r == false) {          
        g1x -= ghostSpeed;
    }
    if(g1x == 500 || g1x == 0) {
        g1r = !g1r;
    }
    System.out.println(g1r);
    ghost1.drawGhost(g, g1x, 40, diameter, Color.red);
    ghost2.drawGhost(g, 170, 70, diameter, Color.blue);
}
4

3 回答 3

7

在我看来,您并没有以面向对象的方式处理此问题。为什么不使用幽灵的集合,例如。并用它的位置、颜色等List<Ghost>定义一个对象?Ghost

这一行:

  ghost1.drawGhost(g, g1x, 40, diameter, Color.red);

然后将替换为

  ghost.draw(g);

你会遍历列表,调用draw()每一个。

  for(Ghost ghost : ghosts) {
     ghost.draw(g); // pass in the graphics context
  }

每个幽灵都知道它的位置、颜色、状态等,您可以根据需要创建任意数量:

  List<Ghost> ghosts = new ArrayList<Ghost>();
  for (int i = 0; i < 10; i++) {  
      ghosts.add(new Ghost());
  }
于 2012-10-12T08:30:19.540 回答
2

由于您似乎是 Java 新手,并且仍在了解最好的习语,因此我会就一些不直接回答您的问题但在更一般意义上的问题提供建议。你的代码

if(g1r == true) {
    g1x += ghostSpeed;          
}       
if(g1r == false) {          
    g1x -= ghostSpeed;
}

可以重写为

g1x += ghostSpeed * (g1r? 1 : -1);

一般注意事项:永远不要将布尔值与文字值进行比较。b == true与 just 相同,bb == false相同!b

这段代码

if (g1x == 500 || g1x == 0) {
    g1r = !g1r;
}

可能会在运行时导致错误,因为您没有在它之前添加围栏代码:g1x可以轻松超越您的限制。你应该改写

if (g1x >= 500) { g1x = 500; g1r = false; }
else if (g1x <= 0) { g1x = 0; g1r = true; }
于 2012-10-12T08:49:19.317 回答
0
  1. 在同一个函数中将 ghost 对象作为另一个参数传递 paintComponent(Graphics g, Ghost gr)
  2. 您可以使条件语句内联,例如 g1r == true ?g1x += ghostSpeed : g1x -= ghostSpeed
于 2012-10-12T08:36:52.407 回答