JAVA坦克大战代码(一)

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.Serializable;

/**
 * @ProjectName TankClient
 * @ClassName TankClient
 * @Desicription TODO
 * @Author Zhang Xueliang
 * @Date 2019/10/25 13:39
 * @Version 1.0
 **/
public class TankClient extends Frame {
    public static final int GAME_WITH=800;
    public static final int GAME_HEIGHT=600;


    int x=50,y=50;
    Image offScreenImage=null;
    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 update(Graphics g){
        if (offScreenImage==null){
            offScreenImage=this.createImage(GAME_WITH,GAME_HEIGHT);
        }
        Graphics gOffScreen = offScreenImage.getGraphics();
        Color c = gOffScreen.getColor();
        gOffScreen.setColor(Color.GREEN);
        gOffScreen.fillRect(0,0,GAME_WITH,GAME_HEIGHT);
        gOffScreen.setColor(c);
        paint(gOffScreen);
        g.drawImage(offScreenImage,0,0,null);
    }
    public void lauchFrame(){
        this.setLocation(400,300);
        this.setSize(GAME_WITH,GAME_HEIGHT);
        this.setTitle("TankWar");
        this.addWindowListener(new WindowAdapter() {//关闭窗口
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        this.setResizable(false);//不让改变窗口大小
        this.setBackground(Color.GREEN);//设置背景颜色为绿色
        setVisible(true);
        new Thread(new PaintThread()).start();
        this.addKeyListener(new KeyMonitor());
    }

    public static void main(String[] args) {
        TankClient tc = new TankClient();
        tc.lauchFrame();
    }

    //让坦克动起来
    private class PaintThread implements Runnable{
        @Override
        public void run() {
            while (true){
                repaint();//重画一次
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //键盘控制坦克移动
    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;
            }
        }
    }
}

 

你可能感兴趣的:(Java基础)