编程知识 cdmana.com

Java version of super Mary game

Technology selection

platform :Windows development tool :Intelij IDEA

JDK Environmental Science :Java 8

UI Interface : be based on Swing Desktop programming technology based on .

Graphic technology :Graphics

Collections framework

IO flow

Multithreading etc.

Map configuration

Map map.txt file

0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,1,0,0,0,1,1,1,1,0,0,2,2,0,0,0,0,0,0,3
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

 

Read the map

package cn.tx.util;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 *  Map configuration class 
 * @author  Ren Liang 
 * @company  Pay Extension Education 
 * @QQ:206229531
 */
public class GameMap {

    // Data container 
    public List<String> list = new ArrayList<>();

    //  Two dimensional array elements are a one-dimensional array : Row and column matrix 
    public int[][] map = null;

    //  unit testing : verification Map Class readMap() Method does configure the map file map.txt
    //  It's loaded into a two-dimensional array 
    @Test
    public void testResult() throws Exception {
        int[][] result = readMap();
        //  Two dimensional array content output , Let's see if it's the configuration information of the map 
        for(int i = 0 ; i < result.length ; i++ ){
            for(int j = 0 ; j < result[i].length ; j++) {
                System.out.print(result[i][j]+" ");
            }
            System.out.println();
        }
    }

    public int[][] readMap() throws Exception {
        //  Construct file input stream 
        FileInputStream fis = new FileInputStream("map.txt");
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader br = new BufferedReader(isr);

        // Read a row of data directly 
        String value = br.readLine();

        while (value != null) {
            // Add a row of data read into the container 
            list.add(value);
            value = br.readLine();
        }

        br.close();

        // How many rows, how many columns 
        int row = list.size();
        int cloum = 0;

        for (int i = 0; i < 1; i++) {
            String str = list.get(i);
            String[] values = str.split(",");
            cloum = values.length;
        }


        map = new int[row][cloum];

        // Convert the read character creation to an integer , And assign it to a binary array map
        for (int i = 0; i < list.size(); i++) {
            String str = list.get(i);
            String[] values = str.split(",");
            for (int j = 0; j < values.length; j++) {
                map[i][j] = Integer.parseInt(values[j]);
            }
        }
        return map;
    }


}

Define the role

The roles in super Mary include , Water pipe , The monster , Bricks, etc . And display to the main interface .

Obstacle Abstract parent class Enemy

package cn.tx.role;

import java.awt.Image;
/**
   The enemy abstract class 
 * @author  Ren Liang 
 * @company  Pay Extension Education 
 * @QQ:206229531
 */
public abstract class Enemy {
	// coordinates 
	public int x,y;
	// Wide and high 
	public int width,height;
	// picture 
	public Image img;

	public Enemy(int x, int y, int width, int height, Image img) {
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
		this.img=img;
	}
}

Water pipes

package cn.tx.role;
import java.awt.Image;

/**
 *  Water pipes 
 * @author  Ren Liang 
 * @company  Pay Extension Education 
 * @QQ:206229531
 */
public class Pipe extends Enemy {


	public Pipe(int x, int y, int width, int height, Image img) {
		super(x, y, width, height, img);
	}
}

Bricks

package cn.tx.role;

import java.awt.Image;

/**
 *  Brick 
 *
 * @author  Ren Liang 
 * @company  Pay Extension Education 
 * @QQ:206229531
 */
public class Brick extends Enemy {



    public Brick(int x, int y, int width, int height, Image img) {
        super(x, y, width, height, img);
    }
}

Gold coins

package cn.tx.role;

import java.awt.Image;

/**
    Gold coins 
 * @author  Ren Liang 
 * @company  Pay Extension Education 
 * @QQ:206229531
 */
public class Coin extends Enemy {
	public Coin(int x, int y, int width, int height, Image img) {
		super(x, y, width, height, img);
	}
}

Bullets

package cn.tx.role;
/**
   Bullets 
 * @author  Ren Liang 
 * @company  Pay Extension Education 
 * @QQ:206229531
 */
public class Boom {
	// The coordinates of the bullet , size , Speed 
	public int x,y;
	public int width;
	public int speed=1;
	
	public Boom(int x, int y, int width) {
		super();
		this.x = x;
		this.y = y;
		this.width = width;
	}
}

Mario class

package cn.tx.mario;

import java.awt.Image;
import java.awt.Rectangle;
import javax.swing.ImageIcon;

import cn.tx.ui.GameFrame;
import cn.tx.role.Enemy;

/**
 *  Mary 
 *
 * @author  Ren Liang 
 * @company  Pay Extension Education 
 * @QQ:206229531
 */
public class Mario extends Thread {
    // Form object 
    public GameFrame gf;
    // Whether to jump 
    public boolean jumpFlag = true;

    // Mario's coordinates , The origin is the upper left corner , therefore y The smaller the week, the higher Mary 
    public int x = 50, y = 358;
    // Mario's speed 
    public int xspeed = 5, yspeed = 1;
    // Mario's width and height 
    public int width = 30, height = 32;
    // Mario's picture 
    public Image img = new ImageIcon("image/mari1.png").getImage();
    // Whether the top, bottom, left and right of the keyboard are pressed 
    public boolean left = false, right = false, down = false, up = false;

    public String Dir_Up = "Up", Dir_Left = "Left", Dir_Right = "Right", Dir_Down = "Down";


    public Mario(GameFrame gf) {
        this.gf = gf;
        this.Gravity();
    }

    //  The logic of Mary's flight  ; The logic of movement is here .
    public void run() {
        while (true) {
            // turn left 
            if (left) {
                // It hit 
                if (hit(Dir_Left)) {
                    this.xspeed = 0;
                }
                // Didn't hit the obstacle 
                if (this.x >= 0) {
                    // Mario's location update 
                    this.x -= this.xspeed;
                    // Change Mario's picture 
                    this.img = new ImageIcon("image/mari_left.gif").getImage();
                }

                this.xspeed = 5;
            }

            // turn right 
            if (right) {
                //  The right side collision detection should be carried out when walking to the right 
                //  Collision detection : At least the protagonist ( Mary , Collider )
                if (hit(Dir_Right)) {
                    this.xspeed = 0;
                }
                // Let the character move to the right 
                if (this.x < 400) {
                    this.x += this.xspeed;
                    this.img = new ImageIcon("image/mari_right.gif").getImage();
                }
                // Mario x The coordinates of the axis are greater than 400 What happened when 
                if (this.x >= 400) {
                    // The background moves to the left 
                    gf.bg.x -= this.xspeed;
                    // The obstacle moves to the left 
                    for (int i = 0; i < gf.eneryList.size(); i++) {
                        Enemy enery = gf.eneryList.get(i);
                        enery.x -= this.xspeed;
                    }
                    // Icon changes 
                    this.img = new ImageIcon("image/mari_right.gif").getImage();
                }
                this.xspeed = 5;
            }

            // Jump up 
            if (up) {

                if (jumpFlag && !isGravity) {
                    jumpFlag = false;
                    new Thread() {
                        public void run() {
                            jump();
                            jumpFlag = true;
                        }
                    }.start();
                }
            }

            try {
                this.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    // Functions that jump up 
    public void jump() {
        // Define the height value 
        int jumpHeigh = 0;
        for (int i = 0; i < 150; i++) {
            // Mary's y Axis position minus Mary's y Shaft speed 
            gf.mario.y -= this.yspeed;
            // Mary's height is increasing 
            jumpHeigh++;
            // If you hit an obstacle, jump out 
            if (hit(Dir_Up)) {
                break;
            }
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // Mary jumped up and fell 
        for (int i = 0; i < jumpHeigh; i++) {
            // Mary's y Axis height plus y Shaft speed 
            gf.mario.y += this.yspeed;
            // If you hit the obstacle below, stop 
            if (hit(Dir_Down)) {
                this.yspeed = 0;
            }
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }
        this.yspeed = 1;// Reduction rate 
    }

    // Detect collision 
    public boolean hit(String dir) {
        // Swing In technology , They have already provided !!
        Rectangle myrect = new Rectangle(this.x, this.y, this.width, this.height);

        Rectangle rect = null;

        for (int i = 0; i < gf.eneryList.size(); i++) {
            Enemy enery = gf.eneryList.get(i);

            if (dir.equals("Left")) {
                rect = new Rectangle(enery.x + 2, enery.y, enery.width, enery.height);
            } else if (dir.equals("Right")) {
                //  Right side collision detection .
                rect = new Rectangle(enery.x - 2, enery.y, enery.width, enery.height);
            } else if (dir.equals("Up")) {
                rect = new Rectangle(enery.x, enery.y + 1, enery.width, enery.height);
            } else if (dir.equals("Down")) {
                rect = new Rectangle(enery.x, enery.y - 2, enery.width, enery.height);
            }
            // collision detection 
            if (myrect.intersects(rect)) {

                return true;
            }
        }

        return false;
    }

    // Check that it's on the floor 
    public boolean isGravity = false;

    //  Gravity threads !
    public void Gravity() {
        new Thread() {
            public void run() {

                while (true) {
                    try {
                        sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }


                    while (true) {
                        // If you don't jump out 
                        if (!jumpFlag) {
                            break;
                        }
                        // If you hit the obstacle below, jump out 
                        if (hit(Dir_Down)) {
                            break;
                        }

                        // Greater than 385  Under the ground 
                        if (y >= 358) {
                            isGravity = false;
                        } else {
                            // On the ground 
                            isGravity = true;
                            //y It's Mario's vertical position 
                            y += yspeed;
                        }

                        try {
                            sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }.start();
    }
}

forms

package cn.tx.ui;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JFrame;

import cn.tx.mario.Mario;
import cn.tx.role.*;
import cn.tx.util.GameMap;
import cn.tx.util.MusicUtil;
/**
    Main window interface : Show the character .
 */
public class GameFrame extends JFrame{
	//  Super Marie : The interface needs a super Mary .
	public Mario mario;
	//  Defining the : Water pipe , Gold coins and bricks 
	public Enemy pipe ,coin , brick;
	// Background image 
	public BackgroundImage bg ;
	// Define a collection container to hold enemy objects 
	public ArrayList<Enemy> eneryList = new ArrayList<Enemy>();
	// Define a collection container to load bullets 
	public ArrayList<Boom> boomList = new ArrayList<Boom>();
	// The speed of the bullet 
	public int bspeed=0;

	// Map data , Make rules , yes 1 Draw bricks , yes 2 Draw gold coins , yes 3 Drawing water pipes 
	public int[][] map = null;
	// Object code block :  When the current class is created 
	{
		//  The instance code block initializes the data of map resources 
		GameMap mp = new GameMap();
		map = mp.readMap();
	}

	// The constructor initializes the background image and Mario object 
	public GameFrame() throws Exception {
		//  Create a background image 
		bg = new BackgroundImage();
		// Initializes the form related property information data 
		// this Represents the current main interface object .
		this.setSize(800,450);
		this.setTitle(" Super Marie ");
		this.setResizable(true);
		//  Center display window 
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setVisible(true);

		//  Create a Mary object 
		mario = new Mario(this);



		//  Read the map , And configure the map 
		for (int i = 0; i < map.length; i++) {
			for (int j = 0; j < map[0].length; j++) {
				// What I read is 1, Draw bricks 
				if(map[i][j]==1){
					// x
					brick = new Brick(j*30,i*30,30,30,new ImageIcon("image/brick.png").getImage());
					eneryList.add(brick);
				}
				// Read 2 Draw gold coins 
				if(map[i][j]==2){
					coin = new Coin(j*30,i*30,30,30,new ImageIcon("image/coin_brick.png").getImage());
					eneryList.add(coin);
				}
				// Read 3 Drawing water pipes 
				if(map[i][j]==3){
					pipe = new Pipe(j*30,i*30,60,120,new ImageIcon("image/pipe.png").getImage());
					eneryList.add(pipe);
				}
			}
		}

		mario.start();

		// Open a thread responsible for the window redraw thread of the interface 
		new Thread(){
			public void run(){
				while(true){
					// Redraw the form 
					repaint(); //  Automatically triggers... In the current window paint Method 
					// Check if the bullet is out of bounds 
					//checkBoom();
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();


		// Set up background music 
		new Thread(new Runnable() {
			@Override
			public void run() {
				MusicUtil.playBackground();
			}
		}).start();
	}

	/**
	 *  Drawing forms 
	 * @param g
	 */
	@Override
	public void paint(Graphics g) {
		// Use double buffer to draw background image and Mario 
		BufferedImage bi =(BufferedImage)this.createImage(this.getSize().width,this.getSize().height);
		// Create drawing objects 
		Graphics big = bi.getGraphics();
		// Painting background 
		big.drawImage(bg.img, bg.x, bg.y, null);

		//  Start drawing enemies on the interface .
		for (int i = 0; i < eneryList.size(); i++) {
			Enemy e = eneryList.get(i);
			// Draw the enemy 
			big.drawImage(e.img, e.x, e.y, e.width, e.height,null);
		}

		// Draw bullets 
		for (int i = 0; i < boomList.size(); i++) {
			Boom b =boomList.get(i);
			Color c =big.getColor();
			big.setColor(Color.red);
			big.fillOval(b.x+=b.speed, b.y, b.width, b.width);
			big.setColor(c);
		}

		// Drawing people   Mary herself 
		big.drawImage(mario.img, mario.x, mario.y, mario.width, mario.height,null);
		g.drawImage(bi,0,0,null);

	}

	// Check if the bullet is out of bounds , Out of bounds is removed from the container , If you don't remove it , Memory leaks 
	public void checkBoom(){
		for (int i = 0; i < boomList.size(); i++) {
			Boom b = boomList.get(i);
			if(b.x<0 || b.x>800){
				boomList.remove(i);
			}
		}
	}
}

  Keyboard event monitoring

package cn.tx.util;

import cn.tx.role.Boom;
import cn.tx.ui.GameFrame;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.ImageIcon;


// Keyboard press monitor class 
public class KeyListener extends KeyAdapter {

    //  Received the current main interface : Game interface 
    public GameFrame gf;

    public KeyListener(GameFrame gf) {
        this.gf = gf;
    }

    // Keyboard monitor 
    @Override
    public void keyPressed(KeyEvent e) {
        //code Is the corresponding value of the key pressed on the keyboard 
        int code = e.getKeyCode();
        switch (code) {
            // turn right 
            case 39:
                gf.mario.right = true; //  Signal bit 
                break;
            // turn left 
            case 37:
                gf.mario.left = true;
                break;
            case 66:
                addBoom();
                break;
            // Jump up 
            case 38:
                gf.mario.up = true;
                break;
        }
    }

    // Add bullets 
    public void addBoom() {
        Boom b = new Boom(gf.mario.x, gf.mario.y + 5, 10);
        if (gf.mario.left) b.speed = -2;
        if (gf.mario.right) b.speed = 2;
        gf.boomList.add(b);
    }

    // Keyboard release monitor 
    @Override
    public void keyReleased(KeyEvent e) {
        int code = e.getKeyCode();
        // Release the right button 
        if (code == 39) {
            gf.mario.right = false;
            gf.mario.img = new ImageIcon("image/mari1.png").getImage();
        }
        // Release left key 
        if (code == 37) {
            gf.mario.left = false;
            gf.mario.img = new ImageIcon("image/mari_left1.png").getImage();
        }
        // Release the top button 
        if (code == 38) {
            gf.mario.up = false;
        }
    }
}

 

Main method and event binding

import cn.tx.ui.GameFrame;
import cn.tx.util.KeyListener;
/**
   Super Mary startup class .
 */
public class Run {
	// The main function , Program entrance 
	public static void main(String[] args) throws Exception {
		GameFrame gf = new GameFrame();
		//  Create a listener object 
		KeyListener kl = new KeyListener(gf);
		//  Add a keyboard listener to the form 
		gf.addKeyListener(kl);
	}
}

Complete source code and explanation QQ Add group :685168267

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

Scroll to Top