当我运行游戏时,我只看到黑屏,没有图像。
我在kilobolt游戏开发指南http://www.kilobolt.com/day-4-enter-the-robot.html
的帮助下编程我的游戏我真的很想知道我做错了什么。
package HideAndSeek;
import java.awt.*;
import java.awt.image.ImageObserver;
public class Player
{
private Image image;
private double velocity;
private int x;
private int y;
public Player(Image image,double velocity,int x,int y)
{
this.image = image;
this.velocity = velocity;
this.x = x;
this.y = y;
}
public void update(Graphics g,ImageObserver io)
{
g.drawImage(image, 0, 0, io);
}
}
package HideAndSeek;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Game extends Applet implements Runnable,KeyListener
{
private Image background;
private Graphics graphics;
private java.net.URL base;
private Player player;
@Override
public void init()
{
background = createImage(this.getWidth(), this.getHeight());
graphics = background.getGraphics();
setSize(800, 480);
setBackground(Color.BLACK);
setFocusable(true);
java.awt.Frame frame = (java.awt.Frame) this.getParent().getParent();
frame.setTitle("Hide and Seek");
base = getCodeBase();
addKeyListener(this);
}
@Override
public void start()
{
player = new Player(getImage(base, "data/character.png"),1.0,0,0);
Thread thread = new Thread(this);
thread.start();
}
@Override
public void stop()
{
}
@Override
public void destroy()
{
}
public void update()
{
if (background == null)
{
background = createImage(this.getWidth(), this.getHeight());
graphics = background.getGraphics();
}
graphics.setColor(getBackground());
graphics.fillRect(0, 0, getSize().width, getSize().height);
graphics.setColor(getForeground());
paint();
graphics.drawImage(background, 0, 0, this);
}
public void paint()
{
player.update(graphics,this);
}
@Override
public void run()
{
while(true)
{
update();
repaint();
try
{
Thread.sleep(17);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
@Override
public void keyPressed(KeyEvent arg0)
{
switch (arg0.getKeyCode())
{
case KeyEvent.VK_UP:
System.out.println("You pressed up arrow");
break;
case KeyEvent.VK_DOWN:
System.out.println("You pressed down arrow");
break;
case KeyEvent.VK_LEFT:
System.out.println("You pressed left arrow");
break;
case KeyEvent.VK_RIGHT:
System.out.println("You pressed right arrow");
break;
case KeyEvent.VK_SPACE:
System.out.println("You pressed the space key");
break;
}
}
@Override
public void keyReleased(KeyEvent arg0)
{
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0)
{
// TODO Auto-generated method stub
}
}
答案 0 :(得分:0)
你做错了。每次调用paint
时,用于在屏幕上绘制内容的图形对象都是不同的。除此之外,您还没有正确覆盖paint
方法,因此缺少一个参数。只需将方法更改为此,它应该可以工作:
public void paint(Graphics g)
{
player.update(g, this);
}