我必须准备一个受这个游戏启发的游戏。当然它应该很简单,但不幸的是它必须使用客户端-服务器通信才能让两个玩家一起玩。到目前为止,我准备了纹理,并试图让其中一辆汽车移动。可悲的是,它并不像看起来那么简单。我被卡住了,无法继续……我只想使用四个箭头:UP - 汽车加速,DOWN - 汽车减速,LEFT - 左转,RIGHT - 右转。当然,如果我们不按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