用于不同对象的for-each循环

Res*_*had 0 java foreach

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

例:

每个幽灵需要3个if语句,此刻每个幽灵有20行代码,如果我在游戏中有3个鬼,那就是3 x 20 = 60行无用编码.

用我的PHP经验,我会说..使用foreach循环或类似的东西..但我应该如何在Java中这样做?有人可以举个例子吗?我现在这样做的方式发表如下:

创造幽灵物体;

DrawPacMan ghost1 = new DrawPacMan();
DrawPacMan ghost2 = new DrawPacMan();
Run Code Online (Sandbox Code Playgroud)

这幅画如下:

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);
}
Run Code Online (Sandbox Code Playgroud)

Bri*_*new 7

在我看来,你并没有以面向对象的方式接近它.为什么不使用鬼魂的集合,例如.List<Ghost>Ghost用它的位置,颜色等定义一个对象?

这一行:

  ghost1.drawGhost(g, g1x, 40, diameter, Color.red);
Run Code Online (Sandbox Code Playgroud)

然后将替换为

  ghost.draw(g);
Run Code Online (Sandbox Code Playgroud)

你会遍历列表,呼唤draw()每一个.

  for(Ghost ghost : ghosts) {
     ghost.draw(g); // pass in the graphics context
  }
Run Code Online (Sandbox Code Playgroud)

每个鬼都知道它的位置,颜色,状态等,你可以创建任意多个:

  List<Ghost> ghosts = new ArrayList<Ghost>();
  for (int i = 0; i < 10; i++) {  
      ghosts.add(new Ghost());
  }
Run Code Online (Sandbox Code Playgroud)