标签:key ram list main lov java .com ble rate
临近期末考试,给大家整一个轻松一些的代码
做个坦克大战中的坦克
当然要想做成小游戏还是要努努力呀~
祝大家考个好成绩
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Tank extends JFrame implements KeyListener{
int x = 10;
int y = 50;
int a;//保存按键的编号
Tank(){
this.setTitle("坦克大战");
this.addKeyListener(this);
this.setSize(400,400);
this.setVisible(true);
}
public static void main(String[] args) {
new Tank();
}
//1 重写paint方法
// 1 显示图形界面的时候自动调用
// 2 窗口还原的时候调用
// 3 repaint调用
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.gray);
//绘制左边轮胎
g.fill3DRect(x, y, 5, 40, false);
//绘制右边轮胎
g.fill3DRect(x+30, y, 5, 40, false);
//绘制中间的圆
g.fillOval(x+2, y+10, 30, 20);
g.setColor(Color.red);
//绘制炮台
g.fill3DRect(x+15, y+28, 5, 20, false);
if(a==88){//按下的X键(x键编号是88)
g.fillOval(x+10, y+70, 10, 10);
g.fillOval(x+2, y+120, 20, 20);
g.fillOval(x-5, y+170, 30, 30);
a = 0;//重置按键编号
}
}
//按住不放
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
//按下某个键调用
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
a = e.getKeyCode();//获得按件的编号
switch(a){
case 38: //上
y-=5;
break;
case 40: //下
y+=5;
break;
case 37: //左
x-=5;
break;
case 39: //右
x+=5;
break;
}
this.repaint();//重新绘图
}
//释放某个键
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
class Panels extends JPanel{
}
}
展示一下运行效果
标签:key ram list main lov java .com ble rate
原文地址:https://www.cnblogs.com/tianyating/p/9200928.html