我必须准备一款受此game启发的游戏。当然它应该很简单,但不幸的是它必须使用客户端 - 服务器通信才能让两个玩家一起玩。到目前为止,我准备了纹理,我试图让其中一辆汽车移动。可悲的是,它并不像看起来那么简单。我卡住了,我不能继续......我只想使用四个箭头:UP - 车速加速,DOWN - 车速减慢,左转 - 左转,右转 - 右转。当然如果我们不按下UP按钮或DOWN按钮,汽车应该减速,但更轻微。我求求你的提示!
这是我的代码:
package destructionderby;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
class CRX extends JFrame implements KeyListener
{
File imageFile2;
BufferedImage crxModel;
public int speed;
int posX, posY;
JPanel crxPanel;
public CRX()
{
speed = 0;
posX=562;
posY = 420;
crxPanel = new JPanel();
imageFile2 = new File("crx.png");
try
{
crxModel = ImageIO.read(imageFile2);
}
catch (IOException e)
{
System.err.println("File access error");
}
addKeyListener(this);
}
public void paint(Graphics g)
{
while (true)
{
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(crxModel, posX+speed, posY, null);
repaint();
}
}
//-------------------KEY LISTENER--------------------
public void keyTyped (KeyEvent key)
{
if (key.getKeyCode()==38) //38 == UP; 40==DOWN; 37==LEFT; 39==RIGHT
{
speed +=10;
}
if (key.getKeyCode()==40)
{
if (speed >10)
{
speed-=10;
}
else speed=0;
}
}
@Override
public void keyPressed(KeyEvent key)
{
}
@Override
public void keyReleased(KeyEvent key)
{
}
}
class MainWindow extends JFrame
{
JPanel mainWindow;
BufferedImage backgroundImage;
CRX crx;
MainWindow()
{
super("Destruction Derby");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(800,600);
setResizable(false);
setVisible(true);
init();
}
void init()
{
mainWindow = new JPanel();
File imageFile= new File("background.png");
//:::...ZAŁADOWANIE OBRAZKA TŁA:::...
try
{
backgroundImage = ImageIO.read(imageFile);
}
catch (IOException e)
{
System.err.println("File access error");
}
crx = new CRX();
paint(getGraphics());
}
@Override
public void paint(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(backgroundImage, 0, 0, this);
crx.paint(getGraphics());
}
}
public class DestructionDerby
{
public static void main(String[] args)
{
new MainWindow();
}
}
还有我的NetBeans项目:http://www2.zippyshare.com/v/30402578/file.html
答案 0 :(得分:3)
JFrame默认情况下永远不会对KeyEvent做出反应,放在那里JPanel
不要直接对JFrame绘制(),而是使用JPanel
覆盖JPanel中的paintComponent,将super.paintComponent()添加为第一个代码行(对于paint()相同)
使用KeyBindings(这里有关于这些键的例子)而不是KeyListener
为什么有两个JFrame的原因,不要扩展JFrame,创建局部变量
将图片加载到本地变量