当前位置:网站首页>Realize that you can continue to play

Realize that you can continue to play

2022-06-11 18:37:00 C_ x_ three hundred and thirty

Implementation record

To realize recording , Here we use IO Flow related knowledge

Define record class

package com.Cx_330.TankGame4;

import java.io.*;
import java.util.Vector;

public class Recorder {
    
    private static int totalTankNums; // Record the number of enemy tanks hit 
    private static BufferedWriter bw;// Character output stream 
    private static BufferedReader br;// Character input stream 
    private static String recordFile="src\\myRecord.txt";// Define the address to store 
     private static Vector<EnemyTank> enemyTanks=new Vector<>();// Record the position of the remaining tanks at the end / Direction 

    // If you want to keep going , You need to design a Vector Container to receive Node object 
    private static Vector<Node> nodes=new Vector<>();

    public static String getRecordFile() {
    
        return recordFile;
    }

    // To continue the game , from E Take out the position and direction information of the tank at the end of the last time 
    public static Vector<Node> getTankInfo(){
    
        try {
    
            br=new BufferedReader(new FileReader(recordFile));
            String begin=br.readLine();
            String[] split = begin.split(":");
            totalTankNums=Integer.parseInt(split[1]);
            String line="";
            while ((line=br.readLine())!=null){
    
                String[] s = line.split(" ");
                int x=Integer.parseInt(s[0]);
                int y=Integer.parseInt(s[1]);
                int direct=Integer.parseInt(s[2]);
                Node node = new Node(x, y, direct);
                nodes.add(node);
            }
        } catch (IOException e) {
    
            throw new RuntimeException(e);
        }finally {
    
            try {
    
                br.close();
            } catch (IOException e) {
    
                throw new RuntimeException(e);
            }
        }
        return nodes;
    }


    // When you quit the game , Store the remaining tank coordinates E Under the root directory 
    public static void keepRecord(){
    
        try {
    
            bw=new BufferedWriter(new FileWriter(recordFile));
            bw.write(" The number of enemy tanks you destroyed is :"+totalTankNums);
            bw.newLine();
            for (int i = 0; i < enemyTanks.size(); i++) {
    
                EnemyTank enemyTank = enemyTanks.get(i);
                if(enemyTank.leap){
    
                    String s=enemyTank.getX()+" "+enemyTank.getY()+" "+enemyTank.getDirect();
                    bw.write(s+"\r\n");
                }
            }
        } catch (IOException e) {
    
            throw new RuntimeException(e);
        }finally {
    
            if(bw!=null){
    
                try {
    
                    bw.close();
                } catch (IOException e) {
    
                    throw new RuntimeException(e);
                }
            }
        }
    }

    // Whenever you hit an enemy tank ,totalTankNums Add 1
    public static void countTankNums(){
    
      totalTankNums++;
    }
    public static int getTotalTankNums() {
    
        return totalTankNums;
    }

    public void setTotalTankNums(int totalTankNums) {
    
        totalTankNums = totalTankNums;
    }

    public static void setEnemyTanks(Vector<EnemyTank> enemyTanks) {
    
        Recorder.enemyTanks = enemyTanks;
    }
}

Definition NODE class

package com.Cx_330.TankGame4;

public class Node {
    
    private int x;
    private int y;
    private int direct;

    public Node(int x, int y, int direct) {
    
        this.x = x;
        this.y = y;
        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 int getDirect() {
    
        return direct;
    }

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

The final solution of Sketchpad optimization

package com.Cx_330.TankGame4;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.util.Vector;

public class Mypanel extends JPanel implements KeyListener,Runnable {
    

    // Define a to receive the input stream Vector Containers 
    Vector<Node>nodes=new Vector<>();
    // Define my tank 
    Hero hero=null;
    // Define enemy tanks 
    Vector<EnemyTank> enemyTanks=new Vector<>();
    // Initialize the number of enemy tanks 
    int enemySize=5;
    // Define bomb set   When the submunition hits the tank, store the bomb 
    Vector<Boom> booms=new Vector<>();
    // Define the picture of the explosion 
    Image image1=null;
    Image image2=null;
    Image image3=null;

    public Mypanel(String choice){
    

        File file = new File(Recorder.getRecordFile());
        if(file.exists()){
    
            // receive Vector<Node> Containers 
            nodes = Recorder.getTankInfo();
        }else {
    
            System.out.println(" The file does not exist , The game will restart ");
            choice="1";
        }
        // At the very beginning, put EnemyTanks Assemble to Recorder Class to record 
        Recorder.setEnemyTanks(enemyTanks);
        hero = new Hero(800,300);// Initialize your own tank 
        hero.setSpeed(10);// set speed 

        // Do judgment  1 Reopen   still 0 continue 
        switch (choice){
    
            case "1":
                // Initialize enemy tanks   And put the bullet   And start the thread 
                for (int i = 0; i < enemySize; i++) {
    
                    // Define a tank 
                    EnemyTank enemyTank=new EnemyTank(100*(i+1),0);
                    // Set tank direction 
                    enemyTank.setDirect(2);
                    // Set enemy tank speed 
                    enemyTank.setSpeed(1);
                    // Define a bullet 
                    Shot shot = new Shot(enemyTank.getX()+20,enemyTank.getY()+60,2);
                    // Start the tank thread 
                    new Thread(enemyTank).start();
                    // Add bullets to the enemy tank collection 
                    enemyTank.shots.add(shot);
                    // Start bullet thread 
                    new Thread(shot).start();
                    // Add tanks to enemy tanks collection 
                    enemyTanks.add(enemyTank);
                }
                break;
            case "0":

                // Initialize enemy tanks   And put the bullet   And start the thread 
                for (int i = 0; i < nodes.size(); i++) {
    
                    Node node = nodes.get(i);
                    // Define a tank 
                    EnemyTank enemyTank=new EnemyTank(node.getX(),node.getY());
                    // Set tank direction 
                    enemyTank.setDirect(node.getDirect());
                    // Set enemy tank speed 
                    enemyTank.setSpeed(1);
                    // Define a bullet 
                    Shot shot = new Shot(enemyTank.getX()+20,enemyTank.getY()+60,2);
                    // Start the tank thread 
                    new Thread(enemyTank).start();
                    // Add bullets to the enemy tank collection 
                    enemyTank.shots.add(shot);
                    // Start bullet thread 
                    new Thread(shot).start();
                    // Add tanks to enemy tanks collection 
                    enemyTanks.add(enemyTank);
                }
                break;
            default:
                System.out.println(" Wrong choice ");
                System.exit(0);
                break;
        }

        // Initialize picture 
        image1=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/b1.jpg"));
        image2=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/b3.jpg"));
        image3=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/b3.jpg"));

        // Specify the path to play music 
            new AePlayWave("src\\x.wav").start();
    }

    // Draw a simple interface 
    public void showInfo(Graphics g){
    

        g.setColor(Color.red);
        Font font = new Font(" Song style ", Font.BOLD, 35);
        g.setFont(font);
        g.drawString(" The number of enemy tanks you have accumulated ",1024,50);
        this.drawTank(1024,90,g,0,1);
        // Reset color   Because the color of the brush changed when painting the tank 
        g.setColor(Color.black);
        g.drawString(Recorder.getTotalTankNums()+"",1200,130);
    }
    @Override
    public void paint(Graphics g) {
    
        super.paint(g);
        // Draw the size of the game interface 
        g.fillRect(0,0,1000,750);
        // Draw interface information 
        showInfo(g);
        // Draw your own tank 
        if(hero.leap){
    
            drawTank(hero.getX(),hero.getY(),g,hero.getDirect(),0);
        }

        // Draw the explosive effect 
        for (int i = 0; i < booms.size(); i++) {
    
            Boom boom=booms.get(i);
            if(boom.life>6){
    
                g.drawImage(image2,boom.x,boom.y,80,80,this);
            }
            else if (boom.life>3){
    
                g.drawImage(image1,boom.x,boom.y,80,80,this);
            }
            else {
    
                g.drawImage(image3,boom.x,boom.y,80,80,this);
            }
            // Reduce bomb health   With dynamic explosion effect 
            boom.lifeTime();
            // If a bomb has a health value of 0  from booms Delete 
            if(boom.life<=0){
    
                booms.remove(boom);
            }
        }


        // Draw enemy tanks 
        for (int i = 0; i < enemyTanks.size(); i++) {
    
            EnemyTank enemyTank = enemyTanks.get(i);
            enemyTank.setEnemyTanks(enemyTanks);
            if(enemyTank.leap){
    
                // Draw enemy tanks 
                drawTank(enemyTank.getX(),enemyTank.getY(),g,enemyTank.getDirect(),1);
                // Draw enemy bullets 
                for (int j = 0; j < enemyTank.shots.size(); j++) {
    
                    // Take the bullet first 
                    Shot shot=enemyTank.shots.get(j);
                    // Draw a bullet   First judge whether the coordinates are out of bounds   If the boundary is crossed, the shots Remove from the set   Otherwise draw 
                    if(!shot.isLive){
    
                        enemyTank.shots.remove(j);
                     } else{
    
                        g.setColor(Color.green);
                        g.draw3DRect(shot.x,shot.y,3,3,false);
                    }
                }
            }
        }
        // Draw your own bullets 
        for (int i = 0; i < hero.shots.size(); i++) {
    
            Shot shot = hero.shots.get(i);
            if(shot!=null&&shot.isLive==true){
    
                g.setColor(Color.cyan);
                g.draw3DRect(shot.x,shot.y,3,3,false);
            }else {
    
                hero.shots.remove(shot);
            }
        }
    }

    /** * * @param x  The upper left corner of the tank x coordinate  * @param y  The upper left corner of the tank y coordinate  * @param g  paint brush  * @param direct  Direction  * @param type  Tank type ( own / The enemy ) */
    public void drawTank(int x,int y,Graphics g,int direct,int type){
    

        //0 My tank  1 Enemy tanks 
        switch (type){
    
            case 0:
                g.setColor(Color.cyan);
                break;
            case 1:
                g.setColor(Color.green);
                break;
        }

        // Direction  (w 0 On  1d 2 Right  s 3 Next  a Left )
        switch (direct){
    
            case 0://
                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);// Body frame 
                g.fillOval(x+10,y+20,20,20);// The lid 
                g.drawLine(x+20,y,x+20,y+20);// Barrel 
                break;
            case 1://
                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);// Body frame 
                g.fillOval(x+20,y+10,20,20);// The lid 
                g.drawLine(x+60,y+20,x+20,y+20);// Barrel 
                break;
            case 2://
                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);// Body frame 
                g.fillOval(x+10,y+20,20,20);// The lid 
                g.drawLine(x+20,y+20,x+20,y+60);// Barrel 
                break;
            case 3://
                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);// Body frame 
                g.fillOval(x+20,y+10,20,20);// The lid 
                g.drawLine(x,y+20,x+20,y+20);// Barrel 
                break;
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {
    

    }

    @Override
    public void keyPressed(KeyEvent e) {
    
        if(e.getKeyCode()==KeyEvent.VK_W){
    
           if(hero.getY()>0){
    
               hero.moveUp();
           }
            hero.setDirect(0);
        } else if (e.getKeyCode()==KeyEvent.VK_D) {
    
            if(hero.getX()+60<1000){
    
                hero.moveRight();
            }
            hero.setDirect(1);
        }
        else if (e.getKeyCode()==KeyEvent.VK_S) {
    
            if (hero.getY()+60<750){
    
                hero.moveDown();
            }
            hero.setDirect(2);
        }else if (e.getKeyCode()==KeyEvent.VK_A) {
    
            if (hero.getX()>0){
    
                hero.moveLeft();
            }
            hero.setDirect(3);
        }

        if (e.getKeyCode()==KeyEvent.VK_J){
    
            hero.shotEnemyTank();
        }

        this.repaint();
    }

    @Override
    public void keyReleased(KeyEvent e) {
    

    }

    public void EnemyHitMyTank(Shot shot,Hero hero){
    
        switch (hero.getDirect()){
    
            case 0:
            case 2:
                if(shot.x>hero.getX()&&shot.x<hero.getX()+40
                        &&shot.y>hero.getY()&&shot.y<hero.getY()+60){
    
                    shot.isLive=false;

                    Boom boom=new Boom(hero.getX(),hero.getY());
                    if(hero.leap){
    
                        booms.add(boom);
                        hero.leap=false;
                    }
                }
                break;
            case 1:
            case 3:
                if(shot.x>hero.getX()&&shot.x<hero.getX()+60
                        &&shot.y>hero.getY()&&shot.y<hero.getY()+40){
    
                    shot.isLive=false;

                    Boom boom=new Boom(hero.getX(),hero.getY());
                    if(hero.leap){
    
                        booms.add(boom);
                        hero.leap=false;
                    }
                }
                break;
        }
    }
    // Determine whether the bullet hit the tank 
        public void hitEnemyTank(Shot shot, EnemyTank enemyTank){
    
        switch (enemyTank.getDirect()){
    
            case 0:
            case 2:
                if(shot.x>enemyTank.getX()&&shot.x<enemyTank.getX()+40
                &&shot.y>enemyTank.getY()&&shot.y<enemyTank.getY()+60){
    
                    shot.isLive=false;
                    enemyTank.leap=false;
                    enemyTanks.remove(enemyTank);
                    hero.shots.remove(shot);
                    Recorder.countTankNums();
                    Boom boom=new Boom(enemyTank.getX(),enemyTank.getY());
                    booms.add(boom);
                }
                break;
            case 1:
            case 3:
                if(shot.x>enemyTank.getX()&&shot.x<enemyTank.getX()+60
                        &&shot.y>enemyTank.getY()&&shot.y<enemyTank.getY()+40){
    
                    shot.isLive=false;
                    enemyTank.leap=false;
                    enemyTanks.remove(enemyTank);
                    hero.shots.remove(shot);
                    Recorder.countTankNums();
                    Boom boom=new Boom(enemyTank.getX(),enemyTank.getY());
                    booms.add(boom);
                }
                break;
        }
    }

    @Override
    public void run() {
    
        while (true){
    
            try {
    
                Thread.sleep(100);
            } catch (InterruptedException e) {
    
                throw new RuntimeException(e);
            }
            
            // Judge whether your own bullet collection hits enemy tanks 
            for (int i = 0; i < hero.shots.size(); i++) {
    
                Shot shot = hero.shots.get(i);
                if(shot!=null && shot.isLive){
    
                    for (int j = 0; j < enemyTanks.size(); j++) {
    
                        EnemyTank enemyTank=enemyTanks.get(j);
                        hitEnemyTank(shot,enemyTank);
                    }
                }
            }

            // Judge whether the enemy's bullet collection hits your own tank 
            for (int i = 0; i < enemyTanks.size(); i++) {
    
                    EnemyTank enemyTank = enemyTanks.get(i);
                    for (int j = 0; j < enemyTank.shots.size(); j++) {
    
                        Shot shot = enemyTank.shots.get(j);
                        if(shot!=null && shot.isLive){
    
                            EnemyHitMyTank(shot,hero);
                        }
                    }
                }

            this.repaint();
        }
    }
}


The final optimization of the framework

package com.Cx_330.TankGame4;

import sun.awt.WindowClosingListener;

import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Scanner;

public class TankGame03 extends JFrame {
    
    private Mypanel mp=null;
    public static void main(String[] args) {
    
        TankGame03 tankGame01 = new TankGame03();
    }
    Scanner scanner=new Scanner(System.in);

    public TankGame03() {
    
        System.out.println(" Please make your choice  1-- Reopen  0-- Keep going ");
        String choice=scanner.next();
        // Start the sketchpad thread 
        mp=new Mypanel(choice);
        Thread thread = new Thread(mp);
        thread.start();
        // Add a Sketchpad to the frame 
        this.add(mp);
        // Add keyboard listening events to the framework 
        this.addKeyListener(mp);
        // Initialize the size of the frame 
        this.setSize(1500,810);
        // Set to automatically end when closing JVM virtual machine 
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // Visualize the graphics drawn on the drawing board 
        this.setVisible(true);
        // Add processing for closing windows 
        this.addWindowListener(new WindowAdapter() {
    
            @Override
            public void windowClosing(WindowEvent e) {
    
                Recorder.keepRecord();
                System.exit(0);
            }
        });
    }
}

原网站

版权声明
本文为[C_ x_ three hundred and thirty]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111819132367.html