我一直在关注youtube关于在java中制作游戏的教程系列,在教程中的某一点,程序必须读取64x64 PNG图像中每个像素的RGB值并创建类的实例因此,当我完成代码时,我得到的只是一个空白屏幕。图像是在paint.net中创建的,我使用eclipse neon 2.我们提前感谢! :)
这是我的代码:
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
public class Game extends Canvas implements Runnable{
private static final long serialVersionUID = 1L;
private boolean isRunning = false;
private Thread thread;
private Handler handler;
private SpriteSheet ss;
private BufferedImage level = null;
private BufferedImage sprite_sheet = null;
private BufferedImage floor = null;
public Game(){
new Window(1000, 563, "Wizard Game", this);
start();
handler = new Handler();
this.addKeyListener(new KeyInput(handler));
BufferedImageLoader loader = new BufferedImageLoader();
level = loader.LoadImage("wizard_level.png");
loadLevel(level);
sprite_sheet = loader.LoadImage("/sprite_sheet.png");
floor = ss.grabImage(4, 2, 32, 32);
}
private void start(){
isRunning = true;
thread = new Thread(this);
thread.start();
}
private void stop(){
isRunning = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run(){
this.requestFocus();
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 60;
while(isRunning){
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1){
tick();
delta --;
}
if(isRunning)
render();
frames ++;
if(System.currentTimeMillis() - timer > 1000){
timer += 1000;
System.out.println("FPS: " + frames);
frames = 0;
}
}
stop();
}
public void tick(){
handler.tick();
}
public void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null){
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
for(int xx = 0; xx < 30*72; xx += 32){
for(int yy = 0; yy < 30*72; yy += 32){
g.drawImage(floor, xx, yy, null);
}
}
handler.render(g);
g.dispose();
bs.show();
}
private void loadLevel(BufferedImage image){
int w = image.getWidth();
int h = image.getHeight();
for(int xx = 0; xx > w; xx++){
for(int yy = 0; yy < h; yy++){
int pixel = image.getRGB(xx, yy);
int red = (pixel >> 16) & 0xff;
int blue = (pixel >> 8) & 0xff;
int green = (pixel) & 0xff;
if(red == 255)
handler.addObject(new Block(xx*32, yy*32, ID.Block, ss));
if(blue == 255)
handler.addObject(new Wizard(xx*32, yy*32, ID.Player, handler, ss));
}
}
}
public static void main(String args[]){
new Game();
}
}
答案 0 :(得分:2)
以下for循环不会执行..
for(int xx = 0; xx > w; xx++){
它将循环xx > w
,它始终为假(其中xx从0开始,图像的宽度为正)
根据其中的yy
循环是正确的,将大于的值更改为小于
for(int xx = 0; xx < w; xx++){
如果仍未获得预期结果,请记录red
和blue
的实际值,以查看图像中实际存在哪些颜色元素。仅当像素的红色和蓝色分量为255