我目前正在开发一款 Java 游戏,它会在屏幕顶部生成块并且它们会掉下来(你必须躲避它们)。目前我在屏幕顶部从一个数组中生成游戏块,但我不知道如何使它们的 y 位置下降 (int)。
基本上我只需要帮助创建一个公共 void 来检查一个对象数组,并且对于一个对象的每个实例,它发现它会将它的 y 位置降低 12。
从代码中选择的片段:
static Object[][] food = new Object[7][700];
public void draw() {
try {
Graphics g = bufferStrategy.getDrawGraphics();
g.clearRect(0, 0, this.getSize().width, this.getSize().height);
// Draw to back buffer
g.setColor(Color.WHITE);
g.fillRect(0, 0, this.getSize().width, this.getSize().height);
g.setColor(Color.BLUE);
g.fillRect(Player.getX(), Player.getY(), Player.WIDTH, Player.HEIGHT);
g.setColor(Color.GRAY);
for(int x = 0; x < food.length; x++) {
for(int y = 0; y < food[x].length; y ++) {
Object o = food[x][y];
if(o instanceof Hamburger) {
new Hamburger(x * 100, y, g);
}
else if(o instanceof Salad) {
new Salad(x * 100, y, g);
}
}
}
GUI.draw(g);
} catch(Exception e) {
e.printStackTrace();
} finally {
bufferGraphics.dispose();
}
}
public void dropBlocks() {
}
public void addBlock() {
if(new Random().nextInt(2) == 1) {
food[new Random().nextInt(7)][0] = new Hamburger(0, 0);
} else food[new Random().nextInt(7)][0] = new Salad(0, 0);
}
public void drawBackbufferToScreen() {
bufferStrategy.show();
Toolkit.getDefaultToolkit().sync();
}
public void run() {
int i = 0;
while(running) {
i++;
draw();
Player.update();
drawBackbufferToScreen();
if(i == 50) {
addBlock();
i = 0;
}
dropBlocks();
Thread.currentThread();
try {
Thread.sleep(10);
} catch(Exception e) {
e.printStackTrace();
}
}
}
Food.java(汉堡和沙拉扩展的内容)
public class Food {
public static int x;
public static int y;
public static int HEIGHT;
public static int WIDTH;
public int type;
private static Image blockImage;
// Default constructor
public Food() {
Food.x = 0;
Food.y = 0;
Food.HEIGHT = 80;
Food.WIDTH = 80;
}
public Food(int x, int y) {
Food.x = x;
Food.y = y;
Food.HEIGHT = 80;
Food.WIDTH = 80;
}
// Getters and setters