Java applet of the cottage version of Super Marie

Source: Internet
Author: User


Java applet of the cottage version of Super Marie

first, The basic function of the game1, can walk left to right (keyboard Monitoring) 2, can jump 3. Capable of firing bullets 4. Ability to detect collisions between obstacles 5. Movement of background images
second, the game running interface


three, The game roughly realize the Idea:
1. form
2. Add your own role
3. Adding a background image
4
. the movement of the background picture
5. Movement and jumping of characters
6. Adding obstacles such as bricks, pipes, etc.
7. Collision of tasks and obstacles

Difficulty analysis: 1. Multi-key Control of characters
1) set the direction for the character Boolean variable: left, right, up, down
2) change the direction of the variable value by the keyboard monitoring
When we press a key, we change the direction to true, and when we release it, we change
it to False.

2. Map Configuration
Custom file read Implementation: file stream usage and string class method invocation

3. Collision Detection
Encapsulates an object of a rectangle class

4. Bullets Added
1) first define a container, which is used to encapsulate all bullet objects
2) when a key is pressed, create a bullet object (initialized with the coordinates of the Character)
3) Add the Bullet object to the container
4) in the paint method, traverse the container, remove the bullet object and draw

5) if the bullet is outside the form boundary, you need to remove the current bullet from the Container.


iv. program Source Code:code structure diagram: divided into three packages, enemy class package, game interface class pack, game map configuration package
Com.huaxin.mario package:
Package Com.huaxin.mario;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 Com.huaxin.enery.Enery;import Com.huaxin.enery.pipe;import Util.map;public class Gameframe extends Jframe{public Mario mario;public enery pipe,cion, Brick;//background Picture public backgroundimage Bg;//container install enemy public arraylist<enery> enerylist = new Arraylist<enery> (); /bullet container public arraylist<boom> boomlist = new arraylist<boom> ();//bullet speed public int Bspeed=0;//draw map, make rules, is 1 draw bricks, is 2 draw gold coin, is 3 draw water pipe public int [] map =null;//constructor inside initialize background picture and Mario object public gameframe () throws Exception {mario = new Mario (this); MA Rio.start (); Map mp= New map (); bg = new backgroundimage ();//the form redraws thread new () {public void run () {while (true) {//redraw form repaint ();// Check to see if the bullet is out of bounds Checkboom (); try {thread.sleep (ten);} catch (interruptedexception e) {e.printstacktrace ()}}}. Start (); map=mp.readmap ();//read map and configure map for (int i = 0; i < map.length;I++) {for (int j = 0; J < map[0].length; j + +) {//read 1, Draw Brick if (map[i][j]==1) {brick = new Pipe (j*30,i*30,30,30,new imagei Con ("image/brick.png"). getImage ()); enerylist.add (brick);} Read 2 to draw gold if (map[i][j]==2) {cion = new Pipe (j*30,i*30,30,30,new imageicon ("image/coin_brick.png"). getImage ()); Enerylist.add (cion);} Read 3 draw the pipe if (map[i][j]==3) {pipe = new pipe (j*30,i*30,60,120,new imageicon ("image/pipe.png"). getImage ()); Enerylist.add (pipe);}}} Set the background music com.huaxin.music.Util.startMusic ("music/bg1.wav");} public void Initframe () {//set form related properties this.setsize (800,450); this.settitle ("cottage Super marie"); this.setresizable (false); This.setlocationrelativeto (null); this.setdefaultcloseoperation (3); this.setvisible (true);//the form adds a keyboard listener KeyListener KL = new KeyListener (this); this.addkeylistener (kl);} public void Paint (Graphics g) {//use double-buffered picture background picture and Mario BufferedImage bi = (bufferedimage) this.createimage (this.getsize (). Width,this.getsize (). height); Graphics Big =bi.getgraphics (); big.drawimage (bg.img, bg.x, bg.y, null); for (int i = 0; i <enerylIst.size (); I++) {enery e =enerylist.get (i); 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);} Painting characters 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, removed from the container without removing it, the memory leaks public void Checkboom () {for (int i = 0; i < boomlist.size (); I++) {Boom b = boomlist.ge T (i); if (b.x<0 | | b.x>800) {boomlist.remove (i);}}}

Package Com.huaxin.mario;import Java.awt.image;import Java.awt.rectangle;import javax.swing.imageicon;import Com.huaxin.enery.enery;//own role class public class Mario extends Thread{public gameframe gf;public boolean jumpflag=true;// Mario's coordinates public int X=0,y=358;//mario's speed public int xspeed=5,yspeed=1;//mario's wide public int Width=30,height=32;//mario pictures public Image img = new ImageIcon ("image/mari1.png"). getImage ();p ublic boolean left=false,right=false,down=false,up=false; Public String dir_up= ' up ', dir_left= ' left ', dir_right= ' right ', dir_down= ' down ';p ublic Mario (gameframe gf) {this.gf=gf; This. Gravity ();} public void Run () {while (true) {//go left} {//collision to if (hit (dir_left)) {this.xspeed=0;} If (this.x>=0) {this.x-=this.xspeed;this.img=new imageicon ("image/mari_left.gif"). getImage ();} this.xspeed=5;} Go right {if (dir_right) {this.xspeed=0;} Any character moves to the right if (this.x<400) {this.x+=this.xspeed;this.img=new imageicon ("image/mari_right.gif"). getImage (); If (this.x>=400) {//background move left gf.bg.x-=this.xspeed;//obstacle item left move for (int i = 0; I <gf.enerylist.size (); I++) {enery enery = gf.eneryList.get (i); enery.x-=this.xspeed;} This.img=new ImageIcon ("image/mari_right.gif"). getImage (); this.xspeed=5;} Jump upward if (up) {if (jumpflag &&!isgravity) {jumpflag=false;new Thread () {public void run () {jump (); jumpflag=true;}}. Start ();}} Try {this.sleep;} catch (interruptedexception e) {e.printstacktrace ();}}} The function to jump up public void jumps () {int jumpheigh=0;for (int i = 0; i < i++) {gf.mario.y-=this.yspeed;jumpheigh++;if (hit (Di R_up)) {break;} Try {thread.sleep (5);} catch (interruptedexception e) {e.printstacktrace ()}} for (int i = 0, i <jumpHeigh; i++) {gf.mario.y+=this.yspeed;if (hit (dir_down)) {this.yspeed=0;} Try {thread.sleep (5);} catch (interruptedexception e) {e.printstacktrace ()}} This.yspeed=1;//restore Speed}//detect Collision Public boolean hit (String dir) {Rectangle myrect = new Rectangle (this.x,this.y,this.width, this.height); Rectangle rect =null;for (int i = 0; i < gf.eneryList.size (); i++) {enery 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")) {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 whether the paste public is Boolean isgravity=false;public void Gravity () {new Thread () {public void run () {while (true) {try {sleep (10)} ;} Catch (interruptedexception e) {e.printstacktrace ();} If (!jumpflag) {}while (true) {if (!jumpflag) {break;} If (hit (DIR_DOWN)) {break;} If (y>=358) {isgravity=false;} else{isgravity=true;y+=yspeed;} Try {sleep];} catch (interruptedexception e) {e.printstacktrace ();}}}}. Start ();}}

Package Com.huaxin.mario;import Java.awt.event.keyadapter;import Java.awt.event.keyevent;import Javax.swing.imageicon;//keyboard Press Listener class public class KeyListener extends Keyadapter{public gameframe gf;public boolean Jumpflag =true;public KeyListener (gameframe Gf) {this.gf=gf;} Keyboard listener public void keypressed (keyevent e) {int code = E.getkeycode (); Switch (code) {//right walk case 39:gf.mario.right=true; Break;//left case 37:gf.mario.left=true;break;case 66:addboom () break;//jump up case 74: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 listener public void keyreleased (keyevent e) {int code=e.getkeycode (); if (code==39) {gf.mario.right=false;gf.mario.img =new ImageIcon ("image/mari1.png"). getImage (); If (code==37) {gf.mario.left=false;gf.mario.img=new imageicon ("image/mari_left1.png"). getImage ();} If (code==74) {gf.mario.up=false;}}}

Package Com.huaxin.mario;import Java.awt.image;import Javax.swing.imageicon;public class backgroundimage {public int x =0,y=0;public int ox=0,oy=0;public Image img=new imageicon ("image/startback.jpg"). getImage ();}

Package Com.huaxin.mario;//bullets public class Boom {//bullet coordinates, size, speed int x,y;int width;int speed=1;public Boom (int x, int y, int Width) {super (); this.x = x;this.y = Y;this.width = width;}}

the main function class, as the entry for the entire program
Package Com.huaxin.mario;public class Test {//main function, program entry public static void main (string[] Args) throws Exception {gameframe g f = new Gameframe (); gf.initframe ();}}


com.huaxin.enery package:
Package Com.huaxin.enery;import Java.awt.image;//the Abstract Parent class of the barrier is abstract class enery {public int x,y;public int width, Height;public Image img;public enery (int x, int y, int width, int height,image Img) {this.x = X;this.y = Y;this.width = WI Dth;this.height = height;this.img=img;}}

Package Com.huaxin.enery;import Java.awt.image;//gold Coin class public class Coin extends Enery{public Coin (int x, int y, int width, i NT height, Image img) {super (x, y, width, height, img);}}

Package Com.huaxin.enery;import Java.awt.image;//brick public class Brick extends Enery {public Brick (int x, int y, int width , int height, Image img) {super (x, y, width, height, img);}}

Package Com.huaxin.enery;import java.awt.image;//plumbing public class pipe extends Enery {public pipe (int x, int y, int width, int height, Image img) {super (x, y, width, height, img);}}


Com.huaxin.util package:
Package Util;import Java.io.bufferedreader;import Java.io.fileinputstream;import java.io.FileNotFoundException; Import java.io.inputstreamreader;import Java.util.arraylist;//map Configuration class public class map {//data container public arraylist< string> list = new arraylist<string> ();p ublic int [] [] map=null;public int[][] readmap () throws Exception {//construction 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) {//adds the read row of data to the container List.add (value);    Value =br.readline ();        } br.close ();    How many rows to get the column 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]; Converts the read character into an integer and assigns a value to the two-bit 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;}}


v. Summary of the Project:This small project looks very simple, in fact, there are many functions need to think carefully, before the game characters in the form to walk, feel that has been a person walking, in fact, the characters go to the middle or go to a certain position, the characters have been in situ, Instead of the long background behind the picture in the mobile, the task of moving around relatively simple implementation, jumping function is not so easy, the need for Yongda thread, collision detection with the back of the relationship, when not encountered, the characters to go down, a note will appear a variety of bugs, such as, Can jump, in the same time jump can also jump, there is the fall may not fall the same height, may be higher than the height of the ground, may be lower than the height of the ground; the addition of obstructions, we configure the map by the way, the configuration map is sometimes read into the file operation, The general principle is to divide the background image of the back into a lot of small lattice, the small lattice into a two-bit array, the two-dimensional array can be stored in different numbers, representing different obstacles, through the operation of the file can easily configure the map; first, read the file data into the file input stream, convert the characters to numbers, and stored in a two-dimensional array, after, by traversing the two-dimensional array of different positions of the values, the corresponding lattice filled with the corresponding barrier; the map is so well-equipped, I think the map is very cool, because there was a senior in the presentation of the time, feel very difficult, now I have mastered the feeling is not difficult, of course, It is inseparable from the Teacher's guidance; collision detection is similar to the collision detection of the ball before, here the main need to deal with some of the logic after the collision, how to avoid the collision (the characters stick to the obstacles cannot move) Otherwise the memory will be eaten soon;write the program, must follow the idea step by step, 1.1 points to achieve! Don't be too impatient! I used to think of myself as a small thing out, but I always very anxious, hope to make soon, the result, the idea is not clear, write up a mess! Lesson! All right, Let's just write this! Share!

Java applet of the cottage version of Super Marie

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.