加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
TankClient6.java 2.71 KB
一键复制 编辑 原始数据 按行查看 历史
17678900298 提交于 2023-04-23 21:10 . V0.6
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TankClient6 extends Frame {
int x = 50, y = 50;
Image offScreenImage = null;
public static final int GAME_WIDTH=800;
public static final int GAME_HEIGHT=600;
public void paint(Graphics g) {
Color c = g.getColor();
g.setColor(Color.RED);
g.fillOval(x, y, 30, 30);
g.setColor(c);
y += 5;
}
public void launchFrame() {
this.setLocation(300, 50);
this.setSize(GAME_WIDTH, GAME_HEIGHT);
this.setBackground(Color.green);
this.setTitle("TankWar");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setResizable(false);
setVisible(true);
this.addKeyListener(new KeyMonitor());
setVisible(true);
new Thread(new PaintThread()).start();
}
private class KeyMonitor extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
switch (key) {
case KeyEvent.VK_LEFT:
x -= 5;
break;
case KeyEvent.VK_UP:
y -= 5;
break;
case KeyEvent.VK_RIGHT:
x += 5;
break;
case KeyEvent.VK_DOWN:
y += 5;
break;
}
}
}
private class PaintThread implements Runnable {
//内部类 (可以方便的访问包装类的方法。不方便公开的,只为包装类服务的类应当定义为内部类)
@Override
public void run() {
while (true) {
repaint();//会自动调用update方法
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void update(Graphics g){
if(offScreenImage==null){
offScreenImage=this.createImage(GAME_WIDTH,GAME_HEIGHT);
}//拿到这个图片的颜色
Graphics gOffScreen=offScreenImage.getGraphics();
Color c=gOffScreen.getColor();
gOffScreen.setColor(Color.green);
gOffScreen.fillRect(0,0,GAME_WIDTH,GAME_HEIGHT);
gOffScreen.setColor(c);
print(gOffScreen);
g.drawImage(offScreenImage,0,0,null);
}
public static void main(String[] args) {
TankClient6 tankClient6=new TankClient6();
tankClient6.launchFrame();
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化