import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class GameFrame extends JFrame implements Runnable{
private final int windowWidth;//画板的宽度
private final int windowHeight;//画板的高度
private final Graphics graphics; //画笔
private final Image imageBackground;
private final Image imagePlane;
private final Image imageBullet;
private int BackgroundY;
private int PlaneX;
private int PlaneY;
private long timerClick;
private int BulletX;
private int BulletY;
private final int PlaneWidth;
private final int PlaneHeight;
public GameFrame()
{
setLayout(null);
windowWidth = 629;
windowHeight = 990;
PlaneWidth = 128;
PlaneHeight = 128;
setSize(windowWidth, windowHeight);
setLocationRelativeTo(null);
setVisible(true);
graphics = getContentPane().getGraphics();
imageBackground = Toolkit.getDefaultToolkit().getImage( "resources\\images\\background_01.png");
imagePlane = Toolkit.getDefaultToolkit().getImage( "resources\\images\\Plane01.png");
imageBullet = Toolkit.getDefaultToolkit().getImage( "resources\\images\\bullet_01.png");
PlaneY = windowHeight - 200;
PlaneX = windowWidth / 2;
KeyCapture();
}
//读取键盘输入
public void KeyCapture()
{
this.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
System.out.println("keyCode: " + keyCode);
switch (keyCode)
{
case KeyEvent.VK_W:
PlaneY -= 4;
break;
case KeyEvent.VK_S:
PlaneY += 4;
break;
case KeyEvent.VK_A:
PlaneX -= 4;
break;
case KeyEvent.VK_D:
PlaneX += 4;
break;
default:
System.out.println("KeyCode error!"); break;
}
}
});
}
@Override
public void run() {
while (true)
{
timerClick++;
graphics.drawImage(imageBackground, 0, (BackgroundY % windowHeight - windowHeight), windowWidth,windowHeight, this);
graphics.drawImage(imageBackground, 0, BackgroundY % windowHeight, windowWidth, windowHeight, this);
graphics.drawImage(imagePlane, PlaneX, PlaneY, PlaneWidth, PlaneHeight, this);
graphics.drawImage(imageBullet, BulletX, BulletY , PlaneWidth / 2, PlaneHeight / 2, this);
BackgroundY += 3;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (timerClick % 60 == 0)
{
BulletX = PlaneX + PlaneWidth / (2*2);
BulletY = PlaneY - PlaneHeight / 2;
}
BulletY -= 4;
}
}
public static void main(String[] args)
{
GameFrame gameFrame = new GameFrame();
Thread thread = new Thread(gameFrame);
thread.start();
}
}
运行效果: