java implementation of simple form games -- Ball battle

java implementation of simple form games -- Ball battle
requirement analysis
1. Analyze the attributes of the ball:

Coordinate, size, color, direction, speed

2. Abstract class: Ball

Design class: BallMain - create form

BallJPanel - draw a small ball

BallAndBall - handle the relationship between balls

3. Process:

1) drawing of small ball

2) generate a small ball, let one small ball play, and let more than one small ball play.

3) small ball collision

4) achieve big ball and small ball

The source code is as follows:
Ball.java

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;

public class Ball {

/* Basic properties of the ball */
int x, y;//Define x, y coordinates
int d;//diameter
Color ballColor;//The color of the ball
int speed;//The speed of the ball
int position;//The direction of the ball

/*The direction of the ball*/
public static final int LEFT_UP = 0;//Left upper
public static final int RIGHT_UP = 1;//Right upper
public static final int LEFT_DOWN = 2;//Left lower
public static final int RIGHT_DOWN = 3;//lower right

/*Construction method*/
public Ball(int x, int y, int position, int d, int speed, Color ballColor){
    this.x = x;
    this.y = y;
    this.position = position;
    this.d = d;
    this.speed = speed;
    this.ballColor = ballColor;
}
//Construct player ball
public Ball(int x, int y, int d, int speed, Color ballColor){
    this.x = x;
    this.y = y;
    this.d = d;
    this.speed = speed;
    this.ballColor = ballColor;
}

//Draw a ball
public void drawBall(Graphics g){
    g.setColor(ballColor);
    g.fillOval(x, y, d, d);
}
public void drawBall2(Graphics g){
    g.setColor(ballColor);
    g.fillOval(x, y, d, d);
    
    //Ball plus text
    g.setColor(Color.RED);
    //Set font size
    Font font = new Font(Font.DIALOG, Font.BOLD, 14);
    g.setFont(font);
    g.drawString("^_^", x+d/2, y+d/2);
}

//The direction of the ball
public void ballMove(){

switch (this.position) {
case LEFT_UP:
    x -= speed;
    y -= speed;
    if (x <= 0) {
        this.position = RIGHT_UP;
    }else if (y <= 0) {
        this.position = LEFT_DOWN;
    }
    break;
case RIGHT_UP:
    x += speed;
    y -= speed;
    if (x >= BallMain.SCREEN_WIDTH - d) {
        this.position = LEFT_UP;
    }else if (y <= 0) {
        this.position = RIGHT_DOWN;
    }
    break;
case LEFT_DOWN:
    x -= speed;
    y += speed;
    if (x <= 0) {
        this.position = RIGHT_DOWN;
    }else if (y >= BallMain.SCREEN_HEIGHT - d) {
        this.position = LEFT_UP;
    }
    break;
case RIGHT_DOWN:
    x += speed;
    y += speed;
    if (x >= BallMain.SCREEN_WIDTH - d) {
        this.position = LEFT_DOWN;
    }else if (y >= BallMain.SCREEN_HEIGHT - d) {
        this.position = RIGHT_UP;
    }
    break;
    }
}

}

BallMain.java

import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.swing.JFrame;

import sun.audio.AudioData;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
import sun.audio.ContinuousAudioDataStream;

/Create form/
public class BallMain extends JFrame{

//Width and height of the form
public static final int SCREEN_WIDTH = 1360;
public static final int SCREEN_HEIGHT = 760;

//Full screen
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int width = (int)d.getWidth();
int height = (int)d.getHeight();

public BallMain(){
    this.setTitle("V1.0");
    //Setting position
    this.setBounds(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
    
    //Add a small ball to the form
    BallJPanel bj = new BallJPanel();
    this.add(bj);
    
    //Add listening event for keyboard
    this.addKeyListener(bj);
    
    /*frame.addKeyListener(tj);
    tj.addKeyListener(tj);
    */
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);    
}

public static void main(String[] args) {
    BallMain b = new BallMain();
    //Add music
            try {
                FileInputStream f =new FileInputStream("music/yyyy.wav");
                AudioStream as = new AudioStream(f);
                AudioPlayer.player.start(as);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
        
                e.printStackTrace();
            }
}

}

BallJPanel.java

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/ painting balls /
public class BallJPanel extends JPanel implements KeyListener{

//Set of storage spheres
List<Ball> ballList = new ArrayList<Ball>();
int x1 = 450;
int y1 = 450;
int d1 = 40;
private Color white;
//Player ball
Ball game = new Ball(x1, y1, d1, 50, white);

//Number of balls
private int ballNumber = 100;

public BallJPanel(){
    addBall();
    startBalls();
}

//How to make a small ball
public void addBall(){
    for (int i = 0; i < ballNumber; i++) {    
        //Randomly generate 100 balls
        int x = (int)(Math.random()*BallMain.SCREEN_WIDTH);
        int y = (int)(Math.random()*BallMain.SCREEN_HEIGHT);
        int position = (int)(Math.random()*4);
    //    int d = (int)(Math.random()*50 + 1);
        int d = 20;
        int speed = 1;
        
        //Color tricolor R G B
        int red = (int)(Math.random()*255 + 1);
        int green = (int)(Math.random()*255 + 1);
        int blue = (int)(Math.random()*255 + 1);
        Color ballColor = new Color(red, green, blue);
        Ball b = new Ball(x, y, position, d, speed, ballColor);
        
        //Add the ball to the collection
        ballList.add(b);    
    }
}

public void paint(Graphics g){
    super.paint(g);
    
    BufferedImage img =null;
    //Add pictures
    try {
        img = ImageIO.read(new File("music/timg.png"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    g.drawImage(img, 0, 0, 1360, 760, this);
    
    this.setBackground(Color.CYAN);
    
    for (int i = 0; i < ballList.size(); i++) {
        Ball ball = ballList.get(i);
        ball.drawBall(g);
        
    }
    
    //Game player
    game.drawBall2(g);
    
}

public void startBalls(){
    //Start thread ----- anonymous inner class
    new Thread(){
        public void run() {
            while (true) {
                //Ergodic Ball Set
                for (int i = 0; i < ballList.size(); i++) {
                    //Remove balls
                    Ball b = ballList.get(i);
                    //Let every little ball move
                    b.ballMove();
                }
                for (int i = 0; i < ballList.size(); i++) {
                    //Take the first ball first
                    Ball b1 = ballList.get(i);
                    for (int j = i+1; j < ballList.size(); j++) {
                        Ball b2 = ballList.get(j);
                        BallAndBall bad = new BallAndBall();
                        //bad.ballCrach(b1, b2);
                        if(bad.isBallCrach(b1, b2)){
                            if (b1.d >= b2.d) {
                                b1.d += b2.d/3;
                                ballList.remove(b2);
                                break;
                            }else if(b1.d < b2.d){
                                b2.d += b1.d/3;
                                ballList.remove(b1);
                                break;
                            }
                        }
                        if (bad.isBallCrach(b1, game)) {
                            if (bad.isBallCrach(b1, game)) {
                                if (b1.d > game.d) {
                                    System.out.println("GAME OEVR");
                                    JOptionPane.showMessageDialog(null, "GAME OVER");
                                    return;
                                }else{
                                    game.d += b1.d/3;
                                    ballList.remove(b1);
                                    break;
                                }
                            }
                        }
                    }
                }
                repaint();//Repaint
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
    }.start();
}

@Override
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub
    
}

@Override
public void keyPressed(KeyEvent e) {
    // TODO Auto-generated method stub
    if (e.getKeyCode() == KeyEvent.VK_UP) {
    //    System.out.println("the up key is clicked");
        game.y -= 10;
    }
    
    if (e.getKeyCode() == KeyEvent.VK_DOWN) {
    //    System.out.println("click the down button");
        game.y += 10;
    }


      if (e.getKeyCode() == KeyEvent.VK_LEFT ) {
    //    System.out.println("left arrow key clicked");
          game.x -= 15;
    }

      if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    //    System.out.println("right click");
        game.x += 15; 
    }
    if (e.getKeyCode() == KeyEvent.VK_1) {
        //    System.out.println("right click");
            game.x += 10; 
            game.y -= 10;
    }
    if (e.getKeyCode() == KeyEvent.VK_2) {
        //    System.out.println("right click");
            game.x -= 10; 
            game.y -= 10;
    }
    if (e.getKeyCode() == KeyEvent.VK_3) {
        //    System.out.println("right click");
            game.x -= 10;
            game.y += 10;
    }
    if (e.getKeyCode() == KeyEvent.VK_4) {
        //    System.out.println("right click");
            game.x += 10;
            game.y += 10;
    }
    repaint();

}

@Override
public void keyReleased(KeyEvent e) {
    // TODO Auto-generated method stub
    
}

}

BallAndBall.java

/Dealing with the relationship between the balls/
public class BallAndBall {

//Two little balls collide
public void ballCrach(Ball b1, Ball b2){
    int x1 =  b1.x + b1.d/2;
    int y1 =  b1.y + b1.d/2;
    int x2 =  b2.x + b2.d/2;
    int y2 =  b2.y + b2.d/2;
    
    double e = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
    //If there is a collision
    if (e <= b1.d/2 + b2.d/2) {
        //b1 ball
        switch (b1.position) {
        case Ball.LEFT_UP:
            b1.position = Ball.RIGHT_DOWN;
            break;
        case Ball.RIGHT_UP:
            b1.position = Ball.LEFT_DOWN;
            break;
        case Ball.LEFT_DOWN:
            b1.position = Ball.RIGHT_UP;
            break;
        case Ball.RIGHT_DOWN:
            b1.position = Ball.LEFT_UP;
            break;
        }
        //b2 ball
        switch (b2.position) {
        case Ball.LEFT_UP:
            b2.position = Ball.RIGHT_DOWN;
            break;
        case Ball.RIGHT_UP:
            b2.position = Ball.LEFT_DOWN;
            break;
        case Ball.LEFT_DOWN:
            b2.position = Ball.RIGHT_UP;
            break;
        case Ball.RIGHT_DOWN:
            b2.position = Ball.LEFT_UP;
            break;
        }
    }
}

//Check for collision
public boolean isBallCrach(Ball b1, Ball b2){
    boolean flag = false;
    int x1 =  b1.x + b1.d/2;
    int y1 =  b1.y + b1.d/2;
    int x2 =  b2.x + b2.d/2;
    int y2 =  b2.y + b2.d/2;
    //Calculate center distance
    double e = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
    
    if (e <= b1.d/2 + b2.d/2) {
        return true;
    }
    
    return false;
}

}

Among them, music and pictures can be modified by themselves, just by modifying the path. The music format is wav, and my personal music is CDU forest.** https://www.kugou.com/song/#hash=91968197C4524D5D9CDE382E824F0B01&album_id=15251465

Change the format after downloading

Author: "Shibo lime" Shibo@
Source: CSDN
Original text: https://blog.csdn.net/qq_40603408/article/details/90145769
Copyright notice: This is the original article of the blogger. Please attach the link of the blog!

Tags: Java

Posted on Sat, 02 Nov 2019 19:11:14 -0700 by sbacelic