Java Small Game Code

Source: Internet
Author: User
Tags gety

A Demand analysis

Once upon a while, the game was synonymous with heroin, and people were associated with Wanwusangzhi. was once subjected to social resentment and parental resistance. But. With the development of the Internet, and the potential advantages of the game are found. The value of the game begins to be recognized by the society, and people begin to accept, recognize and understand the many advantages of the game.

Students now have a heavy burden of schoolwork, less time for entertainment, less interpersonal communication, and a corresponding addition to worry and stress. In fact, playing games not only helps students to adjust their moods, but also to exercise and improve their reflexes and the high-speed coordination ability of the hand brain. At the same time help them understand computer and network knowledge. It's a lot more than one swoop.

According to the survey, students who often play games are active, expressive and optimistic, and will be more flexible in solving the problem.

I've been working all day at school during the day. At night, you need an easy way to relieve stress and relax your emotions. So the game is very good to meet the demand, "stick hit pig" simple operation. The picture is beautiful. Let play, after playing can get great satisfaction and relaxation.

Stick hit Pig is a simple single-machine mini-game. After-school entertainment for young students. When this game is executed, the nine dark lattice in the game interface will randomly pop up a little piggy, with the mouse to control the small hammer click. The game will take you to the speed and number of points the player is hitting on the pig.

Two Descriptive narrative of the program

2.1 Purpose of the program design

Through the Java Development Technology course, I initially learned how to use the Java language Coding code. After the course is over. According to the teacher's request, after looking for information, I finished the Stick beat pig this program.

In the process. The main goal is to achieve two goals. One is to test and consolidate professional knowledge, the second is to improve the comprehensive quality and ability. Through the preparation of the program. I can combine the theoretical knowledge that I have mastered in class with the ability to deal with actual needs, so as to test the breadth and depth of my knowledge and the ability to use knowledge comprehensively.

2.2 Requirements for program design

(1) "Stick hit pig head" is a kind of game similar to hitting the hamster. The program interface of the nine dark lattice will randomly appear a pig head, the player is using the mouse to control the hammer Movement and percussion action (when the mouse button is pressed).

(2) in the game, when the hammer hit the pig will add a score (each hit a plus ten points). and display this score on the status bar.

(3 The main interface of the program is to give the player a fresh, natural and enjoyable game interface.)

2.3 Environment of the programming

Windows XP operating system,jcreator editing tools,jdk1.7

Third, analysis and design

3.1 Game Processing Flow

The process of this game design, such as the

3.2 Main classes and important algorithms of the program

There are two characters in the game. One is the pigsprite class that represents the pig's head, the other is the hammersprite class that represents the hammer, they are all inheriting the game main class supersprite class. Another indispensable game main class-Thehitpighead class.

The game is composed of 9 pigsprite class instances and a hammersprite class instance. These necessary class instances are built into the init() method in the main class of the game, and the status of the role is converted in the animation loop, and the role itself is drawn in the paint() method.

Because the hammer character has a mouse-controlled direct conversion state, there is only the code to convert the character of the pig in the animation loop:

for (int i=0;i<9;i++)// convert pig head Sprite

Pigsprite[i].updatestate ();

In the paint() method, the program code that requires the role to draw itself such as the following:

drawing the Pig 's head Sprite

for (int i=0;i<9;i++)

Pigsprite[i].paintsprite (Drawoffscreen);

draw a hammer Sprite

Hammersprite.paintsprite (Drawoffscreen);

The action of waving a hammer: the first is to wave the action of the Hammer, the correct treatment is when the left mouse button is displayed hammer2, release the key after the display hammer1, which is by the hammer the updatestate() method of the Sprite is implemented.

public void Updatestate ()

{

Convert Hammer Image

if (currentimage==hammer1)

Currentimage=hammer2;

Else

Currentimage=hammer1;

}

The hit () method of the head character can be used to test whether a hammer character hits the head of the head, and the techniques used for collision detection are as follows:

if (this. X+P_WIDTH>=X) && (this. y+ (P_HEIGHT/2) >=y)

&& (x+ (H_WIDTH/2) >=this. X) && (y+ (H_HEIGHT/2) >=this. Y) && Showpig)

{

Showpig=false;

return true;

}

else return false;

The program detects if the hammer hits the head when the mouse button is pressed, and theprogram code in the Mousepressed () method detects the action when the hit () method is called:

test to see if you hit the pig head Sprite

for (int i=0;i<9;i++)

{

assuming hit adds a score and displays the score in the Status column

if (Pigsprite[i].hit (x,y,framewidth,frameheight,hammerwidth,hammerheight) ==true)

{

score=score+10;

Showstatus (" score now:" +score);

}

}

3.3 Program Execution Results


Iv. Experience

1) through this semester of Java learning, I mastered the basic knowledge of the Java language, through Java I have learned a lot of other practical things. For example, algorithms, data structures.

I had a strong love for Java after I learned about Java.

2) Through the experiments of the past few weeks. Let me take this semester to learn the knowledge applied to practice, the theory to pay to practice is really very difficult, master the basic knowledge started at all do not know how to organize. But my love for Java is impossible to be stifled.

Through my internet search, the book read. Move hands. The end of Kung fu is not a conscientious.

I finished the experiment smoothly.

3) This experiment gave me a lot of knowledge of the Java swing programming, filling up a lot of my vacancies. In the implementation of the function I understand the importance of the algorithm to the program, a good algorithm can make your program more robust. The amount of code you write is even less.

Handling exceptions is always the norm in Java. Through experiments. I'm more sure of the usual exception handling. More.

4) The Secret of learning is perseverance and persistence. Learning Java is the same truth, I believe that only I insist on going on. Java is going to be a stage for me.

"Stick hit the Pig" code:

/** * @ (#) Hitpighead.java * * * @author * @version 1.00 2012/6/4 */import java.awt.*;import java.util.*;import java.applet . *;import Java.awt.event.*;abstract class Supersprite{int X,y,width,height;boolean visible,active;abstract public    void Paintsprite (Graphics g), abstract public void updatestate ();p ublic int GetX () {return X;}    public int GetY () {return Y;} public void setlocation (Int. x,int Y) {this.      X=x; This.    Y=y;    } public int getwidth () {return width;    } public int getheight () {return height;    } public void setSize (int width,int height) {this.width=width;    This.height=height;    } public boolean canvisible () {return visible;    } public void setvisible (Boolean v) {visible=v;    } public boolean Canmove () {return active;    } public void Setmove (Boolean m) {active=m;             }}class Pigsprite extends Supersprite//pig head sprite{int seed;      Generates a random number image spriteimage,frame; The Sprite itselfImage applet Game;      Random R;boolean Showpig are used when drawing images; Draw the pig head Image public Pigsprite (image spriteimage,image Frame,applet Game) {r=new Random (); Spriteimage=spriteimage;this. Frame =frame;this.    Game=game;showpig=false;setvisible (TRUE);       Visible Setmove (True); Movable}public void Updatestate () {if (active==true) {//Convert pig head image appears with vanishing state if (R.nextint (seed)%100<1) {if (showpig==false) Showpig=true;} else if (R.nextint (seed)%100 >) {if (showpig==true) Showpig=false;}}}    public void Paintsprite (Graphics g)//Draw pig head sprite{if (Visible = = True) {g.drawimage (frame,x,y,game);      In the last parameter, enter the applet if (Showpig = = True) g.drawimage (Spriteimage,x+12,y+18,game); }}public void setseed (int seed) {this.seed=seed;} Test whether to hit the pig head public boolean hits (int x,int y,int p_width,int p_height,int h_width,int h_height) {if (this. X+P_WIDTH&GT;=X) && (this. y+ (P_HEIGHT/2) >=y) && (x+ (H_WIDTH/2) >=this. X) && (y+ (H_HEIGHT/2) >=this. Y) && showpig) {Showpig=false;return true;} Elsereturn False;}}      Class Hammersprite extends Supersprite//hammer sprite{image hammer1,hammer2,currentimage;          Hammer Image applet Game; The public hammersprite (image hammer1,image Hammer2,applet Game) {This.hammer1=hammer1;this.hammer2=hammer2 is used when drawing the image; This.    Game=game;currentimage=hammer1;setlocation (0,0); setvisible (false);       Invisible Setmove (false); Non-removable}public void updatestate () {//Convert hammer image if (currentimage==hammer1) currentimage=hammer2;elsecurrentimage=hammer1;}    public void Paintsprite (Graphics g)//Draw hammer sprite{if (Visible = = True) g.drawimage (Currentimage,x,y,game); Enter the Applet}}public class Hitpighead extends Applet//define the game main class implements RUNNABLE,MOUSELISTENER,MO in the last number of parameters usemotionlistener {int appletwidth,appletheight,framewidth,frameheight,countx,county,hammerwidth,hammerheight, Score; Image Frame,pig,hammer1,hammer2,offscreen; Thread Newthread; Graphics Drawoffscreen; Mediatracker MT; Pigsprite Pigsprite []; Hammersprite Hammersprite; public void init () {Addmouselistener (this); Registration time Processing Method Addmousemotionlistener (this); Appletwidth = GetSize (). width; Appletheight = GetSize (). Height;         countx=3;         X-axis 3 pig head texture county=3;          Y-Axis 3 pig head texture score=0; Recording score//using mediatracker tracking image MT = new Mediatracker (this); Pig = GetImage (Getdocumentbase (), "images/pig1.gif"); frame = GetImage (Getdocumentbase (), "images/frame1.gif"); Hammer1 = GetImage (Getdocumentbase (), "images/hammer1.gif"); Hammer2= GetImage (Getdocumentbase (), "images/hammer2.gif"); Mt.addimage (pig,0); Mt.addimage (frame,0); Mt.addimage (hammer1,0); Mt.addimage (hammer2,0);     try {mt.waitforall ();} catch (Interruptedexception E) {}//no exception handling framewidth=frame.getwidth (this);     Pig Head Texture width frameheight=frame.getheight (this);      The height of pig head texture Pigsprite =new pigsprite[9]; Use 9 pig head image (3*3) for (int i=0;i<9;i++) {//Build pig head Sprite pigsprite[i]=new pigsprite (pig,frame,this);//Set position Pigsprite[i] . setlocation (I%countx*framewidth,i/county*frameheight); Pigsprite[i].setseed (i+100);     Set the range of random numbers}//Build Hammer Sprite hammersprite=new hammersprite (hammer1,hammer2,this);    Hammerwidth=hammer1.getwidth (this);   Hammer Image Width Hammerheight=hammer1.getheight (this); Hammer Image Height//Create sub-screen offscreen=createimage (appletwidth,appletheight); Drawoffscreen=offscreen.getgraphics (); Resize (framewidth*countx,frameheight*county);    } public void Start ()//start () method {Newthread=new Thread (this); Establish and start a new thread Newthread.start ();         } public void Stop ()//stop () method {newthread=null; Cheng the line to null} public void Paint (graphics g) {//clear only the image of this part of the area drawoffscreen.clearrect (0,0,appletwidth,appletheight); Draw the pig head sprite for (int i=0;i<9;i++) pigsprite[i].paintsprite (Drawoffscreen); Draw Hammer Sprite Hammersprite.paintsprite (drawoffscreen); Paste the sprite onto the main screen g.drawimage (offscreen,0,0,this);        The public void update (Graphics g)//update () method {paint (g);} public void Run () {while (newthread!=null) {repaint ();    Repaint the image try {thread.sleep (33); Pause 33 milliseconds} catch (Interruptedexception E) {} for (int i=0;i<9;i++)//convert pig Head sprite pigsprite[i].updatestate ();  }}//========== implements MouseListener interface ====================== public void mouseexited (MouseEvent e)//mouse away component {             Hammersprite.setvisible (FALSE);              Do not draw hammer Sprite hammersprite.setlocation (0,0); Return at Origin} public void mouseclicked (MouseEvent e) {}//mouse button is pressed and released public void mouseentered (MouseEvent e)//mouse enters comp           onent {hammersprite.setvisible (true); Draw Hammer Sprite Hammersprite.setlocation (E.getx ()-(HAMMERWIDTH/2), E.gety ()-(HAMMERHEIGHT/2));         } public void mousepressed (MouseEvent e)//mouse button was pressed {hammersprite.updatestate ();          Convert Hammer Sprite int x=hammersprite.getx ();           Get the x-coordinate of the hammer sprite int y=hammersprite.gety (); Get the Y-coordinate of the hammer Sprite//test whether hitting the pig head sprite for (int i=0;i<9;i++) {//assuming hit adds fractions and displays fractions in the Status column if (Pigsprite[i].hit (x,y,framewidth , frameheight,hammerwidth,hammerheight) ==true) {score=score+10; Showstatus ("Score Now:" +score);}} }public void mousereleased (MoUseevent e)//mouse button release {hammersprite.updatestate (); Convert Hammer sprite}//================= implement Mousemotionlistener interface ================public void mousemoved (MouseEvent e)//mouse movement When {//mouse cursor is placed in the center of the Hammer Sprite Hammersprite.setlocation (E.getx ()-(HAMMERWIDTH/2), E.gety ()-(HAMMERHEIGHT/2));} public void mousedragged (MouseEvent e)//mouse drag when {//mouse cursor is placed in the center of the Hammer Sprite Hammersprite.setlocation (E.getx ()-(HAMMERWIDTH/2 ), E.gety ()-(HAMMERHEIGHT/2));}}


Java Small Game Code

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.