gpt4 book ai didi

Java游戏,颜色不出现

转载 作者:太空宇宙 更新时间:2023-11-04 12:21:49 25 4
gpt4 key购买 nike

我有一个名为 Wave 的游戏的代码,通常当我运行它时,它应该是一个黑色窗口,其中有白色方 block 。但 window 是白色的, window 左边有一条很细的黑色条纹。我几乎看不到它。

有人知道为什么会发生这种情况吗?

package wave.myFirstGame;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.util.Random;

public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 3580879553502102315L;
public static final int WITDH = 640, HEIGHT = WITDH / 12 * 9;

private Thread thread;
private boolean running = false;

private Random r;
public Handler handler;

public Game() {
new Window(WITDH, HEIGHT, "Wave", this);

handler = new Handler();
r = new Random();

for(int i = 0; i < 50; i++){
handler.addObject(new Player(r.nextInt(WIDTH), r.nextInt(HEIGHT), ID.Player));
}

handler.addObject(new Player(200, 200, ID.Player));
}

public synchronized void start() {// initializing the thread
thread = new Thread(this);
thread.start();
running = true;
}

public synchronized void stop() {
try {
thread.join();
running = false;
} catch (Exception e) {
e.printStackTrace();
}
}

// GAME LOOP
public void run() {
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while (delta >= 1) {
tick();
delta--;
}
if (running)
render();
frames++;

if (System.currentTimeMillis() - timer > 1000) {
timer += 1000;
System.out.println("FPS " + frames);
frames = 0;
}
}
stop();
}

private void tick(){
handler.tick();
}
private void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
this.createBufferStrategy(3);
return;
}

Graphics g = bs.getDrawGraphics();
g.setColor(Color.black);

g.fillRect(0, 0, WIDTH, HEIGHT);
handler.render(g);

g.dispose();
bs.show();
}

public static void main(String[] args) {
new Game();
}
}

最佳答案

查看 Canvas 的 API 。在那里你会发现:

Fields inherited from interface java.awt.image.ImageObserver
[...] HEIGHT, [...], WIDTH

因此,既然您从 Canvas 类扩展了您的类,您已经有了 WIDTH 和 HEIGHT 常量,并且由于某种原因 WIDTH 接缝的值为 1
因此,只需重命名您的常量,它就会按预期显示。

关于Java游戏,颜色不出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38786702/

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