- package com.MyTankGame;
- import java.awt.*;
- import javax.swing.*;
- import java.awt.event.*;
- public class MyTankGame extends JFrame{
- Mypanel mp=null;
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- MyTankGame mtg=new MyTankGame();
- }
- public MyTankGame()
- {
- mp=new Mypanel();
- this.add(mp);
- this.addKeyListener(mp);
- this.setSize(400, 300);
- this.setVisible(true);
- this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- this.setLocation(350, 200);
- }
- }
- class Mypanel extends JPanel implements KeyListener
- {
- Hero hero=null;
- int x=150;
- int y=200;
- public void Hero()
- {
- hero=new Hero(10,10);
- }
- public void paint(Graphics g)
- {
- super.paint(g);
- g.fillRect(0, 0, 400, 300);
- g.setColor(Color.blue);
- this.drawTank(hero.getX(),hero.getY(), 1, g, 1);
- }
- //构造坦克函数
- public void drawTank(int x,int y,int direct,Graphics g,int Type)
- {
- switch (Type)
- {
- case 1:
- g.setColor(new Color(154,165,127));
- g.fill3DRect(x, y, 10, 30, true);
- g.fill3DRect(x+29, y, 10, 30, true);
- g.fill3DRect(x+10, y+5, 20, 20, false);
- g.drawOval(x+11, y+6, 15, 15);
- g.drawLine(x+18, y-5, x+18, y+15);
- break;
- }
- }
- //按下键
- public void keyPressed(KeyEvent e) {
- if(e.getKeyCode()==KeyEvent.VK_DOWN)
- {
- //设置Hero坦克fangxian
-
- y=y+5;
- }else if(e.getKeyCode()==KeyEvent.VK_UP)
- {
-
- y=y-5;
- }else if(e.getKeyCode()==KeyEvent.VK_RIGHT)
- {
-
- x=x+5;
- }else if(e.getKeyCode()==KeyEvent.VK_LEFT)
- {
-
- x=x-5;
- }
- this.repaint();
- }
- //释放键
- public void keyReleased(KeyEvent e) {
- // TODO Auto-generated method stub
-
- }
- //键上的值被输出
- public void keyTyped(KeyEvent e) {
- // TODO Auto-generated method stub
-
- }
- }
- class Tank
- {
- int x;
- int y;
- //0↑ 1↓ 2← 3→
- int direct;
- 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 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;
- }
- }
- class Hero extends Tank
- {
- public Hero(int x,int y)
- {
- super(x, y);
- }
- //创建坦克移动方法
- public void moveUp()
- {
- y-=speed;
- }
- public void moveDown()
- {
- y+=speed;
- }
- public void moveRight()
- {
- x+=speed;
- }
- public void moveLeft()
- {
- x-=speed;
- }
- }
复制代码 |