gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:45:51 26 4
gpt4 key购买 nike

在我的代码中,每当变量分数比第一个多 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com