/*功能:坦克大战
* 1.画坦克
* 2.让坦克动起来
*
*
* */
package com.gxd.tank;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class DrawTank extends JFrame{
MyPanel mp=null;
public static void main(String[] args) {
// TODO Auto-generated method stub
DrawTank tank=new DrawTank();
}
public DrawTank()
{
mp=new MyPanel();
this.add(mp);
this.addKeyListener(mp);
this.setTitle("画坦克");
this.setSize(400,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
class MyPanel extends JPanel implements KeyListener
{
//定义一个我的坦克
Hero hero=null;
//构造函数
public MyPanel()
{
hero=new Hero(10, 10);
}
//重写paint函数
public void paint(Graphics g)
{
//画出我的坦克
super.paint(g);
g.fillRect(1, 1, 398, 298);
this.drowTank(hero.getX(), hero.getY(), g, 0, 0);
}
//画出坦克的函数
public void drowTank(int x,int y,Graphics g,int dic,int type)
{
switch (type)
{
case 0:
g.setColor(Color.red);
break;
case 1:
g.setColor(Color.yellow);
break;
}
switch (dic)
{
case 0:
g.fill3DRect(x, y, 5, 30,false);
g.fill3DRect(x+15, y, 5, 30,false);
g.fill3DRect(x+5, y+5, 10, 20,false);
g.drawOval(x+5, y+10, 9, 10);
g.fill3DRect(x+8, y, 4, 10, false);
}
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyCode()==KeyEvent.VK_RIGHT) {
int i=hero.getX();
i++;
hero.setX(i);
}else if(e.getKeyCode()==KeyEvent.VK_LEFT) {
int i=hero.getX();
i--;
hero.setX(i);
}else if(e.getKeyCode()==KeyEvent.VK_UP) {
int i=hero.getY();
i--;
hero.setY(i);
}else if(e.getKeyCode()==KeyEvent.VK_DOWN) {
int i=hero.getY();
i++;
hero.setY(i);
}
this.repaint();
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
//定义我的坦克
class Hero extends Tank
{
public Hero(int x,int y)
{
super (x,y);
}
}
class Tank
{
int x=0;//坦克的横坐标
int y=0;//坦克的纵坐标
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Tank(int x,int y)
{
this.x=x;
this.y=y;
}
}