编程知识 cdmana.com

Java flying bird game

Game background         

        The origin of this game is the mobile game developed by independent developers in Vietnam , In a short time, it has occupied all the major cities in the world AppStore Top of the free list . In the game , Players control a bird flying through the gap between pillars . The farther you fly, the higher the score , See how long players can keep birds in the air . The initial interface is shown in the figure -1 Shown .

image.png

         Players in the picture -1 Any position of the interface shown , Press the left mouse button , Start the game .

         After the game begins , Players need to constantly control the frequency of the motor screen to adjust the bird's flight height and landing speed , Let the bird smoothly pass through the column gap at the right end of the screen . If the player accidentally touches the post or falls to the ground , Then the game is over . Pictured -2 Shown :

image.png

         Pictured -2 The top left corner shown shows the user's score , Every time I go through the gap of a column, I have to 1 branch . in addition , At this time, the player can be shown in the figure -2 Any position of the interface shown , Press the left mouse button , Restart the game .

Class design

image.png

Complete code

BirdGame The complete code for is as follows :

package com.itkzhan.bird;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BirdGame extends JPanel {
	Bird bird;
	Column column1, column2; 
	Ground ground;
	BufferedImage background;
	/**  End of game  */
	boolean gameOver;
	BufferedImage gameOverImage;
	/**  Game start state  */
	boolean started;
	BufferedImage startImage;
	// fraction 
	int score;
	/**  initialization  BirdGame  Property variable of  */
	public BirdGame() throws Exception {
		started = false;
		startImage = ImageIO.read(
			getClass().getResource("start.png"));
		gameOver = false;
		gameOverImage = ImageIO.read(
			getClass().getResource(
					"gameover.png"));
		score = 0;
		bird = new Bird();
		column1 = new Column(1);
		column2 = new Column(2);
		ground = new Ground();
		background = ImageIO.read(
			getClass().getResource("bg.png")); 
	}
	
	/** " rewrite ( modify )"paint Method to achieve rendering  */
	public void paint(Graphics g){
		g.drawImage(background, 0, 0, null);
		g.drawImage(column1.image, 
			column1.x-column1.width/2, 
			column1.y-column1.height/2, null);
		g.drawImage(column2.image, 
			column2.x-column2.width/2, 
			column2.y-column2.height/2, null);
		// stay paint Method to add the algorithm of drawing score 
		Font f = new Font(Font.SANS_SERIF,
				Font.BOLD, 40);
		g.setFont(f);
		g.drawString(""+score, 40, 60);
		g.setColor(Color.WHITE);
		g.drawString(""+score, 40-3, 60-3);
		
		g.drawImage(ground.image, ground.x, 
			ground.y, null);
		// rotate (rotate) Drawing coordinate system , yes API Method 
		Graphics2D g2 = (Graphics2D)g;
		g2.rotate(-bird.alpha, bird.x, bird.y);
		g.drawImage(bird.image, 
			bird.x-bird.width/2, 
			bird.y-bird.height/2, null);
		g2.rotate(bird.alpha, bird.x, bird.y);
		// stay paint Method to display the end of game status code 
		if(gameOver){
			g.drawImage(gameOverImage,0,0,null);
		}
		if(! started){
			g.drawImage(startImage, 0, 0, null);
		}
 
		// Add debug box 
//		g.drawRect(bird.x-bird.size/2, 
//				bird.y-bird.size/2, 
//				bird.size, bird.size);
//		g.drawRect(column1.x-column1.width/2, 
//				column1.y-column1.height/2, 
//				column1.width, 
//				column1.height/2-column1.gap/2);
//		g.drawRect(column1.x-column1.width/2, 
//				column1.y+column1.gap/2, 
//				column1.width, 
//				column1.height/2-column1.gap/2);		
	}//paint The end of the method 
	//BirdGame Add method in action()
	public void action() throws Exception {
		MouseListener l=new MouseAdapter(){
			//Mouse  The mouse  Pressed Press down 
			public void mousePressed(
					MouseEvent e){
				try{
					if(gameOver){
						synchronized(BirdGame.this){
					    	column1 = new Column(1);
					    	column2 = new Column(2);
					    	bird = new Bird();
					    	started = false;
					    	gameOver = false;
					    	score = 0;
						}
					}else{
						started = true;
						// Birds fly up 
						bird.flappy();
					}
				}catch(Exception ex){
					ex.printStackTrace();
				}
			}
		};
		// take l Hook to the current panel (game) On 
		addMouseListener(l);
		
		while(true){
			if( !gameOver ){// If it doesn't end, take a step 
				if(started){
					column1.step();
					column2.step();
					bird.step();
				}
				bird.fly();
				ground.step();
				// Scoring logic 
				if( bird.x == column1.x ||
					bird.x == column2.x ){
					score++;
				}
			}
			synchronized(BirdGame.this){
				// If the bird hits the ground, the game is over 
				if( bird.hit(ground)  ||
					bird.hit(column1) ||
					bird.hit(column2) ){
					gameOver = true;
				}
			}

			repaint();
			Thread.sleep(1000/60);
		}
	}
	
	/**  How to start the software  */
	public static void main(String[] args)
		throws Exception {
		JFrame frame = new JFrame();
		BirdGame game = new BirdGame();
		frame.add(game);
		frame.setSize(440, 670);
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(
				JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
		game.action();
	}
}
/**  ground  */
class Ground{
	BufferedImage image;
	int x, y;
	int width;
	int height;
	public Ground() throws Exception {
		image = ImageIO.read(
		  getClass().getResource("ground.png"));
		width = image.getWidth();
		height = image.getHeight();
		x = 0;
		y = 500;
	}// End of ground constructor 
	// In the terrestrial class , Add method , Move the ground one step 
	public void step(){
		x--;
		if(x==-109){
			x = 0;
		}
	}
}// The end of the ground class 
/**  Column type ,x,y It's the position of the center of the column  */
class Column{
	BufferedImage image;
	int x,y;
	int width, height;
	/**  The gap between the columns  */
	int gap;
	int distance;// distance , The distance between the two pillars 
	Random random = new Random();
	/**  Constructors : Initialization data ,n For the first pillars  */
	public Column(int n) throws Exception {
		image=ImageIO.read(
		  getClass().getResource("column.png"));
		width = image.getWidth();
		height = image.getHeight();
		gap=144;
		distance = 245;
		x = 550+(n-1)*distance;
		y = random.nextInt(218)+132;
	}
	// stay Column Add method in  step, stay action Call this method 
	public void step(){
		x--;
		if(x==-width/2){
			x = distance * 2 - width/2;
			y = random.nextInt(218)+132;
		}
	}
}//Column End of class 
/**  Bird type , x,y It's the center of the bird type  */
class Bird{
	BufferedImage image;
	int x,y;
	int width, height;
	int size;// The size of the bird , For collision detection 
	
	// stay Bird Add properties to class , Used to calculate the position of a bird 
    double g;//   Acceleration of gravity 
    double t;//   The interval between two positions 
    double v0;//  The initial up throw speed 
    double speed;//  Is the current up throw speed 
    double s;//      It's time t Later displacement 
    double alpha;//  It's the inclination of the bird   Radian unit 
    // stay Bird Definition in class 
    // Define a set ( Array ) picture , It's the animation frame of the bird 
    BufferedImage[] images;
    // Is the subscript position of the animation frame array element 
    int index;
    
	public Bird() throws Exception {
		image=ImageIO.read(
			getClass().getResource("0.png"));
		width = image.getWidth();
		height = image.getHeight();
		x = 132;
		y = 280;
		size = 40;
		g = 4;
		v0 = 20;
		t = 0.25;
		speed = v0;
		s = 0;
		alpha=0;
		// Create array , establish 8 Array of elements 
		// yes 8 Empty space , There is no picture object ,
		//8 Number of positions : 0 1 2 3 4 5 6 7
		images = new BufferedImage[8];
		for(int i=0; i<8; i++){
			//i = 0 1 2 3 4 5 6 7 
			images[i] = ImageIO.read(
  			  getClass().getResource(i+".png"));
		}
		index = 0;
	}
	// stay Bird Add flying (fly) Code for 
	public void fly(){
		index++;
		image = images[(index/12) % 8];
	}
	// stay Bird Add the movement method of the bird 
	public void step(){
		double v0 = speed;
		s = v0*t + g*t*t/2;// Calculate the up throw movement displacement 
		y = y-(int)s;// Calculate the bird's coordinate position 
		double v = v0 - g*t;// Calculate the next speed 
		speed = v;
//		if(y>=500){// If you get to the ground , Just throw it back 
//			y = 280;
//			speed = 35;
//		}
		// call Java API The arctangent function provided , Calculate the inclination 
		alpha = Math.atan(s/8);
	}
	// stay Bird Add method in 
	public void flappy(){
		// Reset the initial speed , Fly up again 
		speed = v0;
	}
	// Add methods to birds  hit
	// Check whether the current bird touches the ground ground
	// If you return true Indicates send collision 
	// Otherwise return to false No collision 
	public boolean hit(Ground ground){
		boolean hit = y + size/2 > ground.y;
		if(hit){
			y = ground.y-size/2;
			alpha = -3.14159265358979323/2;
		}
		return hit;
	}
	// Check if the current bird hit the post 
	public boolean hit(Column column){
		// First, check whether it is within the range of the column 
		if(x>column.x-column.width/2-size/2 &&
		   x<column.x+column.width/2+size/2){
			// Check if it's in the gap 
			if(y>column.y-column.gap/2+size/2 &&
			   y<column.y+column.gap/2-size/2){
				return false;
			}
			return true;
		}
		return false;
	}
}

you 're right , One class is done , It's that simple .

Focus on “ Monkeys learn to program ” official account , reply “ Flying birds ”, Get the project source code ( With pictures )

版权声明
本文为[Monkeys learn to program]所创,转载请带上原文链接,感谢

Scroll to Top