package com.Tank;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TankGame1 extends JFrame{
MyPanel mp=null;
public static void main(String[] args) {
// TODO Auto-generated method stub
TankGame1 tg=new TankGame1();
}
//构造函数
public TankGame1()
{
mp=new MyPanel();
this.add(mp);
mp.setLayout(null);
//注册监听
this.addKeyListener(mp);
this.setSize(400,300);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
//我的面板
class MyPanel extends JPanel implements KeyListener
{ //定义一个我的坦克
Hero hero=null;
//构造函数
public MyPanel()
{
hero=new Hero(100,100);
}
//重新paint
public void paint(Graphics g)
{
super.paint(g);
g.fillRect(0, 0, 400, 300);
this.drawTank(hero.getX(), hero.getY(), g, 0, 1);
}
//画出坦克的函数
public void drawTank(int x,int y,Graphics g,int direct,int type)
{
//判断是什么类型的坦克
switch (type)
{
case 0:
g.setColor(Color.CYAN);
break;
case 1:
g.setColor(Color.yellow);
break;
}
//判断方向
switch(direct)
{
//向上
case 0:
//画出我的坦克
//1.画出左边矩形
g.fill3DRect(x, y, 5, 30,false);
//2.画出右边矩形
g.fill3DRect(x+15, y, 5, 30,false);
//3.画出中间矩形
g.fill3DRect(x+5, y+5, 10, 20,false);
//4.画出圆形
g.fillOval(x+5, y+10, 10, 10);
//5.画出线
g.drawLine(x+10, y+15, x+10, y);
break;
}
}
@Override
//键按下处理 a:向左 s:向下 w:向上 d:向右
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getKeyCode()==KeyEvent.VK_W)
{
//设置我的坦克的方向
this.hero.setDirect(0);
this.hero.moveUp();
}
else if(arg0.getKeyCode()==KeyEvent.VK_D)
{
//向右
this.hero.setDirect(1);
this.hero.moveRight();
}else if(arg0.getKeyCode()==KeyEvent.VK_S)
{
//向下
this.hero.setDirect(2);
this.hero.moveDown();
}else if(arg0.getKeyCode()==KeyEvent.VK_A)
{
//向左
this.hero.setDirect(3);
this.hero.moveLeft();
}
//必须重新绘制panel
this.repaint();
System.out.println("按下"+arg0.getKeyChar());
}
@Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
//坦克类
class Tank
{
//横坐标
int x=0;
//纵坐标
int y=0;
public int getX() {
// TODO Auto-generated method stub
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
//坦克方向
//0:上 1:右 2:下 3:左
int direct=0;
//设置坦克的速度
int speed=1;
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getDirect() {
return direct;
}
public void setDirect(int direct) {
this.direct = direct;
}
public Tank(int x,int y)
{
this.x=x;
this.y=y;
}
}
//我的坦克
class Hero extends Tank
{
public Hero(int x,int y)
{
super(x,y);
}
//坦克向上移动
public void moveUp()
{
y-=speed;
}
//坦克向右移动
public void moveRight()
{
x+=speed;
}
//坦克向下移动
public void moveDown()
{
y+=speed;
}
//坦克向左移动
public void moveLeft()
{
x-=speed;
}
}
想做一个坦克大战的游戏,后台可以接收到键盘按键,但是不能控制坦克动起来是怎么回事呢