Java foundation - Tank War (Chapter 2, realizing tank rotation and movement)

Posted by niekos on Wed, 12 Jan 2022 22:32:34 +0100

This chapter - get the tank moving

Java event handling mechanism

1. Listen for keyboard events - KeyListener interface

package com.tao.event_;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * Create By Liu Hongtao
 * 2022/1/12 20:40
 */
public class BallMove extends JFrame {
    Mypanel mp = null;

    public static void main(String[] args) {
        BallMove ballMove = new BallMove();
    }

    //constructor 
    public BallMove() {
        mp = new Mypanel();
        this.add(mp);
        this.setSize(400, 300);  //Window size
        this.setLocationRelativeTo(null);           //Center
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    //close
        this.setVisible(true);                  //so
        //The window JFrame object can listen for keyboard events, that is, it can listen for keyboard events on the panel
        this.addKeyListener(mp);
    }
}

//Panel, you can draw a small ball
//KeyListener is a listener that can listen for keyboard events
class Mypanel extends JPanel implements KeyListener {
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.fillOval(10, 10, 20, 20);
    }

    //This method is triggered when there is character output
    @Override
    public void keyTyped(KeyEvent e) {

    }

    //This method is triggered when a key is pressed
    @Override
    public void keyPressed(KeyEvent e) {
        System.out.println((char)e.getKeyCode() + "Pressed..");
    }

    //This method is triggered when a key is released (released)
    @Override
    public void keyReleased(KeyEvent e) {

    }
}

2. Demonstrate how to control the movement of the ball through the keyboard key position

package com.tao.event_;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * Create By Liu Hongtao
 * 2022/1/12 20:40
 */
public class BallMove extends JFrame {
    Mypanel mp = null;

    public static void main(String[] args) {
        BallMove ballMove = new BallMove();
    }

    //constructor 
    public BallMove() {
        mp = new Mypanel();
        this.add(mp);
        this.setSize(400, 300);  //Window size
        this.setLocationRelativeTo(null);           //Center
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    //close
        this.setVisible(true);                  //so
        //The window JFrame object can listen for keyboard events, that is, it can listen for keyboard events on the panel
        this.addKeyListener(mp);
    }
}

//Panel, you can draw a small ball
//KeyListener is a listener that can listen for keyboard events
class Mypanel extends JPanel implements KeyListener {

    //In order for the ball to move, set the coordinates (X, Y) of its upper left corner as a variable
    int x = 10;
    int y = 10;
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.fillOval(x, y, 20, 20);
    }

    //This method is triggered when there is character output
    @Override
    public void keyTyped(KeyEvent e) {

    }

    //This method is triggered when a key is pressed
    @Override
    public void keyPressed(KeyEvent e) {
//        System.out.println((char)e.getKeyCode() + "pressed..);
        //Handle the movement of the ball (up, down, left and right keys) according to the different keys pressed by the user

        //ctrl + b query VK in detail_ Hexadecimal encoding of down
        if(e.getKeyCode() == KeyEvent.VK_DOWN){ //KeyEvent.VK_DOWN is the code corresponding to the down arrow = 0 * 28 (hexadecimal representation) = hexadecimal 28 = decimal 40
            y++;
            System.out.println("lower");

        } else if(e.getKeyCode() == KeyEvent.VK_UP){
            y--;
            System.out.println("upper");
        }else if(e.getKeyCode() == KeyEvent.VK_LEFT){
            x--;
            System.out.println("Left");
        }else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
            x++;
            System.out.println("right");
        }
//        Panel redrawing
        this.repaint();
    }

    //This method is triggered when a key is released (released)
    @Override
    public void keyReleased(KeyEvent e) {

    }
}

Basic description

Java event processing adopts the "delegated event model". When an event occurs, the object generating the event will pass this "information" to the "event listener" for processing. The "information" here is actually Java awt. The object created by a class in the event event class library is called "event object".

Sketch Map

In depth understanding of event handling mechanism

  1. We mentioned several important concepts, event source, event and event listener. Let's introduce them comprehensively.
  2. Event source: an event source is an object that generates events, such as buttons, windows, etc
  3. Event: an event is an object that carries the change of event source state. For example, when keyboard event, mouse event, window event, etc., an event object will be generated. This object stores a lot of information about the current event. If the KeyEvent object has meaning, the Code value of the pressed key will be generated. java.awt.event package and javax swing. Various event types are defined in the event package
Event classexplain
ActionEventUsually occurs when a button is pressed, a list item is double clicked, or a menu is selected
AdjustmentEventOccurs when a scroll bar is manipulated
ComponentEventSend when a component is hidden, moved, or resized
ContainerEventOccurs when a component is added or removed from a container
FocusEventOccurs when a component gains or loses focus
ItemEventWhen a check box or list item is selected, when a selection box or selection menu is selected
KeyEventOccurs when the key from the keyboard is pressed and released
MouseEventWhen the mouse is dragged, moved, clicked, pressed
TextEventOccurs when the text in the text area and text field changes
WindowEventWhen a window is activated, closed, disabled, restored, minimized

Event listener interface:

  1. When the event source generates an event, it can be sent to the event listener for processing
  2. The event listener is actually a class that implements an event listener interface. For example, in our previous case, mypane is a class that implements the KeyListener interface. It can be used as an event listener to process the received events
  3. There are many kinds of event listener interfaces. Different event listener interfaces can listen to different events. A class can implement multiple listening interfaces
  4. These interfaces are in Java awt. Event package and javax swing. Defined in the event package.

The tank rotates up, down, left and right

  • Implementation principle, coordinate rotation
     //Draw the corresponding tank shape according to the tank direction
     //
        switch(direct){
            case 0: //Indicates up
                g.fill3DRect(x, y,10,60,false);                  //Left wheel
                g.fill3DRect(x + 30, y,10,60,false);          //Right wheel
                g.fill3DRect(x + 10,y + 10,20,40,false);    //lid
                g.fillOval(x + 9, y + 18, 20,20);               //turret
                g.drawLine(x + 19, y - 10,x + 19,y + 20);           //barrel
                break;
            case 1: //towards the left
                g.fill3DRect(x, y,60,10,false);                  //Left wheel
                g.fill3DRect(x , y + 30,60,10,false);          //Right wheel
                g.fill3DRect(x + 10,y + 10,40,20,false);    //chassis
                g.fillOval(x + 18, y + 9, 20,20);               //turret
                g.drawLine(x - 10, y + 19,x + 20,y + 19);           //barrel
                break;

            case 2: //down
                g.fill3DRect(x, y,10,60,false);                  //Left wheel
                g.fill3DRect(x + 30, y,10,60,false);          //Right wheel
                g.fill3DRect(x + 10,y + 10,20,40,false);    //chassis
                g.fillOval(x + 9, y + 18, 20,20);               //turret
                g.drawLine(x + 19, y + 50,x + 19,y + 20);           //barrel
                break;
            case 3: //towards the right
                g.fill3DRect(x, y,60,10,false);                  //Left wheel
                g.fill3DRect(x , y + 30,60,10,false);          //Right wheel
                g.fill3DRect(x + 10,y + 10,40,20,false);    //lid
                g.fillOval(x + 18, y + 9, 20,20);               //turret
                g.drawLine(x + 50, y + 19,x + 20,y + 19);           //barrel
                break;
            default:
                System.out.println("Not handled yet");
        }

Realize tank movement

  • Firstly, draw the rotation images of the tank in four directions, then select the receiving direction in the case, correct the parameters through the encapsulated tank x and y positions and the move method, and call repaint() to redraw to realize the tank movement
package com.tao.tankgame02;

/**
 * Create By Liu Hongtao
 * 2022/1/12 4:38
 */
public class Tank {
    private int x;  //Abscissa of tank
    private int y;  //Ordinate of tank
    private int direct; //Return value of tank direction
    private int speed = 50;  //Tank speed

    public int getDirect() {
        return direct;
    }

    public void moveUp(){
        y -= speed;
    }
    public void moveRight(){
        x += speed;
    }
    public void moveDown(){
        y += speed;
    }
    public void moveLeft(){
        x -= speed;
    }

    public void setDirect(int direct) {
        this.direct = direct;
    }

    public Tank(int x, int y){
        this.x = x;
        this.y = y;
    }

    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;
    }
}

package com.tao.tankgame02;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * Create By Liu Hongtao
 * 2022/1/12 4:41
 * Drawing area of tank war
 */
public class MyPanel extends JPanel implements KeyListener {
    //Define my tank
    Hero hero = null;
    public MyPanel(){

        hero = new Hero(100,100);   //Initialize your own tank
        hero.setSpeed(1000);               //Initialize tank speed
    }

    @Override
    public void paint(Graphics g){
        super.paint(g);
        g.fillRect(0,0,1000,750);    //Fill rectangle, default black
        //Draw the tank - packaging method
        drawTank(hero.getX(),hero.getY(),g,hero.getDirect(),1);        //Type tank type
    }

    //Write the method and draw the tank

    /**
     *
     * @param x x coordinate of the upper left corner of the tank
     * @param y y coordinate of the upper left corner of the tank
     * @param g paint brush
     * @param direct    Tank direction (up, down, left and right)
     * @param type  Tank type
     */
    public void drawTank(int x, int y, Graphics g,int direct,int type){
        switch (type) {
            case 0: //Enemy tanks
                g.setColor(Color.CYAN);
                break;
            case 1: //My tank
                g.setColor(Color.yellow);
                break;
        }

        //Draw the corresponding tank shape according to the tank direction
        //
        switch(direct){
            case 0: //Indicates up
                g.fill3DRect(x, y,10,60,false);                  //Left wheel
                g.fill3DRect(x + 30, y,10,60,false);          //Right wheel
                g.fill3DRect(x + 10,y + 10,20,40,false);    //lid
                g.fillOval(x + 9, y + 18, 20,20);               //turret
                g.drawLine(x + 19, y - 10,x + 19,y + 20);           //barrel
                break;
            case 1: //towards the left
                g.fill3DRect(x, y,60,10,false);                  //Left wheel
                g.fill3DRect(x , y + 30,60,10,false);          //Right wheel
                g.fill3DRect(x + 10,y + 10,40,20,false);    //chassis
                g.fillOval(x + 18, y + 9, 20,20);               //turret
                g.drawLine(x - 10, y + 19,x + 20,y + 19);           //barrel
                break;

            case 2: //down
                g.fill3DRect(x, y,10,60,false);                  //Left wheel
                g.fill3DRect(x + 30, y,10,60,false);          //Right wheel
                g.fill3DRect(x + 10,y + 10,20,40,false);    //chassis
                g.fillOval(x + 9, y + 18, 20,20);               //turret
                g.drawLine(x + 19, y + 50,x + 19,y + 20);           //barrel
                break;
            case 3: //towards the right
                g.fill3DRect(x, y,60,10,false);                  //Left wheel
                g.fill3DRect(x , y + 30,60,10,false);          //Right wheel
                g.fill3DRect(x + 10,y + 10,40,20,false);    //lid
                g.fillOval(x + 18, y + 9, 20,20);               //turret
                g.drawLine(x + 50, y + 19,x + 20,y + 19);           //barrel
                break;
            default:
                System.out.println("Not handled yet");
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    //Processing key press operation
    @Override
    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_W){    //upper
            //Change the direction of the tank
            hero.setDirect(0);
            hero.moveUp();

        }else if(e.getKeyCode() == KeyEvent.VK_D){  //right
            hero.setDirect(3);
            hero.moveRight();
//            hero.setX(hero.getX() + 1);
        }else if(e.getKeyCode() == KeyEvent.VK_S){  //lower
            hero.setDirect(2);
            hero.moveDown();
//            hero.setY(hero.getY() + 1);
        }else if(e.getKeyCode() == KeyEvent.VK_A){  //Left
            hero.setDirect(1);
            hero.moveLeft();
//            hero.setX(hero.getX() - 1);
        }
        repaint();
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }
}

Topics: Java Back-end