java - 试图以 500 分的增量提高我的游戏速度,但我有太多 if 语句。

标签 java

在我的代码中,每当变量分数比第一个多 500 时,变量速度就需要增加。因此,当分数为 500 时:speed++。当分数为 1000 时:再次 speed++,以此类推。

这是我的代码:

import java.awt.*;

public class Enemy {
    static int x = -100;
    static int y = -100;
    Player player;
    private int enemy_xspeed = 0;
    private int enemy_yspeed = 0;
    private int speed = 0;

    public Enemy(Player player) {
        this.player = player;
    }

    public void update(){
        if(Player.getX() < x){
            enemy_xspeed = -2 - speed;
        }
        if(Player.getX() > x){
            enemy_xspeed = 2 + speed;
        }
        if(Player.getY() > y){
            enemy_yspeed = 2 + speed;
        }
        if(Player.getY() < y){
            enemy_yspeed = -2 - speed;
        }   

        x += enemy_xspeed;
        y += enemy_yspeed;
    }

    public void scoreMethod(){
        //THIS BLOCK OF CODE BELOW TAKES TOO MANY LINES I NEED THIS HERE WRITTEN IN NOT MANY LINES
        if(GameClass.score == 500){
            speed ++;
        }
        if(GameClass.score == 1000){
            speed ++;
        }
        if(GameClass.score == 1500){
            speed ++;
        }
        if(GameClass.score == 2000){
            speed ++;
        }
        if(GameClass.score == 2500){
            speed ++;
        }
        if(GameClass.score == 3000){
            speed ++;
        }
        if(GameClass.score == 3500){
            speed ++;
        }
        if(GameClass.score == 4000){
            speed ++;
        }
        if(GameClass.score == 4500){
            speed ++;
        }
    }

    public void paint(Graphics g){
        g.setColor(Color.ORANGE);
        g.fillRect(x, y, 20, 20);
    }
}

最佳答案

此答案基于您的游戏分数只会增加的假设。

public void scoreMethod(){       
    if(GameClass.score % 500 == 0){
        speed++;
    }
}

它的作用是检查游戏得分是否可以除以 500 而没有任何余数(就像您的 if 语句一样)。


但是,如果您的游戏分数可能会降低,上述解决方案可能会对您的游戏设计产生负面影响:

Score 480,
Score 490,
Score 500, speed increase (to level 2)
Score 480,
Score 490,
Score 500, another speed increase (Though now we're on level 3, when we should be level 2 again)

在那种情况下,请考虑以下代码,它跟踪上次速度增加的时间,以防止上述重复:

int lastSpeedIncrease = -1;  //class or 'global' variable
//initialize to -1 and not 0

public void scoreMethod(){               
    if(GameClass.score > lastSpeedIncrease){
        if(GameClass.score % 500 == 0){
            speed++;
            lastSpeedIncrease = GameClass.score;
        }
     }
}

关于java - 试图以 500 分的增量提高我的游戏速度,但我有太多 if 语句。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32278261/

相关文章:

java - 定义变量并使用开关

java - JTree 线型和 Nimbus

java - 如何操作和打印二维 ArrayList?

Java代码混淆

java - 值仅返回0

java - Spring Boot @ConfigurationProperties 到 map 的 map 或(嵌套 map /MultiKeyMap)

java - 如何解锁 Jackrabbit 中由开放范围锁持有的节点?

java - 如何使用 Apache Commons Net 通过 IMAP 获取电子邮件?

java - JNA 捕获异常

java - XPath lower-case() 获取小写值的集合