Java game programming preliminary

xiaoxiao2021-03-06  78

The popular game now seems to be developed with C or C . There is almost no great and playable popular game on the Java platform. Since Java is a new language, many of his characters have to be explored by everyone, but we cannot deny that Java's power in game programming. This article will lead you a step by step to learn to write Java games. Finally create your own Java game.

We have to confirm that you have installed Java JDK and have installed browser software such as IE. This chapter is an Internet as a development object. Step by step, you can meet the Java's Thread, Applets .... And some of the game programming should pay attention to some of the side and attach the corresponding source code for everyone to refer, and finally we will also Guidelines for our game program. In the article, we also put a lot of constructive issues, let readers participate in our development. However, since this chapter is led to the threshold, most of the knowledge will not be detailed, interested readers can check the relevant information supplements. We have to confirm some basic properties that you already know, inherit, and Java languages.

Basic applet

Applets is a small program on a web browser. Because applet is absolutely secure, what it does is limited than AAPLICATION, but for the client's program, Applets is still a very powerful tool. For browsing and running, we will develop objects as applets.

Develop Applets programs, we have to inherit the Applet class, override the necessary functions, the following functions control the Applet generation and execution on the web page.

Function The function init () This function is automatically called, executes the initialization action of the applet - including the allocation of the component in the layout, you must overwrite it Start () Whenever the browser displays the applet content, let Applet Turn on its formal work (especially those that are closed by STOP ()), and then call this function STOP () whenever the browser does not display content, it will call it. Let Applet closes some resource work, then call this function DESTROY () browser, call it to remove the applet from the web page, to execute "Applet is no longer used" should do The final release resource, etc. Action Paint () allows you to make the corresponding painting movements on the Applet interface, once every time you refresh, you will be redrawn.

All applet file source file names are as .java as extensions, compiled execution file extensions are .class, because there is no main () function in the applet, it is automatically integrated with HTML, so We want to execute the applet, to put a specific label (tag) in the HTML source file, can you tell the web page how to load and execute this applet, here you have to pay attention to the webpage we execute, you must execute the Java program.

Ordinary HTML source format

This line is the execution of the applet.

Applet executes documentation = "HelloWorld.class" tells web "Applet" extension files for HelloWorld.class

Width and Height tell the browser that the size of the applet displayed

For instructions for tag (TAG), you can find a lot of related instructions documents online. Thread

Due to the execution of the Apllet, Java applications is related to the thread. Let's probably understand the concept of threads.

Threads are also called light processes (LWP). Each thread can only be active, collaborate, and data exchange within the scope of a single process, and is very cheap in computing resources. The thread requires the support of the operating system, so it is not all the machines to provide a thread. Java programming language, as a quite new language, has been integrated with the thread support and language itself, which provides a strong support for threads.

The Thread class is a specific class, ie not an abstract class, which encapsulates the behavior of threads. To create a thread, the programmer must create a new class exported from the Thread class. The programmer must override the thread's Run () function to complete useful work. The user does not call this function directly; but must call the Start () function of Thread (), the function calls Run ().

However, using the Thread class to implement threads, add the program's class level, so the general programmers are implemented by another Java thread interface runnable interface, and the runnable interface has only one function run (). This function must be implemented by a class that implements this interface. .

There are several important ways in threads to know:

Thread.Start (): Start a thread

Thread.stop (): Stop a thread

Thread.sleep (Time In MilliseConds): Suspend the thread in a waiting time.

Animation technology

Free landing animation

After understanding some basic concepts, let's start our substantive work. We designed a ball from the top of the screen to the screen, and the program is relatively simple, but this is an indispensable part of the game animation. Let's take a look at our Applet start statement before starting.

import java.awt *;. import java.applet *;. public class Ball extends Applet implements Runnable {public void init () {} public void start () {} public void stop () {} public void destroy () {} Public void run () {} public void paint (graphics g) {}}

In the start function we have to create the main thread of the program and launch this thread. Once you do these preparations, when Applet is first displayed, an instance of a thread object is created, and the THIS object is used as the parameter of the constructing method, and then you can start the animation.

Public void start () {// Defines a new thread thread TH = New Thread (this); // Start thread th.start ();}

Now let's take a look at the RUN method of the thread, which redraws the animation scene every 20 milliseconds in the cyclic while (). This method is important. If there is no part in the Run cycle, the round redrapporn action will be executed very quickly, and other methods will not be effectively executed, that is, we will not see the ball on the screen.

Public void Run () {// while (true) {// Heavy painting applet screen repaint (); try {// Tervity thread 20 millisecond Thread.Sleep (20);} catch (interruptedException ex) {}}}

Before we read, there were several questions to answer. You may ask, the browser calls the START and STOP methods of the Java applet? How is the RUN method called? The situation is that when the browser starts an internal thread, start the applet's operation. When the web is displayed, the start method of the applet is launched. The Start method creates a thread object and transmits the Applet itself to the thread to implement the RUN method. At this point, two threads are running: the initial thread that is started by the browser, and the thread of the animation. Quickly view the Start method of the applet, you can know that it creates a thread and starts it. Similarly, when the web is hidden, the APPLET's STOP method calls the thread's STOP method.

Note: START / STOP subroutines in Applets and Threads

There are START and STOP methods in both classes of Applet and Thread, but their features are different. Once the Applet is displayed, call the Applet's Start method. Once Applet hide, the Applet's STOP method is called. Instead, the start method of the thread will call the RUN method, and the thread's STOP method will stop the thread being executed.

Public void Paint (Graphics G);

Parameters in the Paint () method - Java.awt.graphics object will be an image representative of a cropped correlation display area (not the entire display area). Our drawing of sphere graphic elements is done by overwriting the Paint () method, which is completed in which the incoming Graphics object G is completed.

When our application's logic is updated, call the repaint () method to notify the AWT thread to refresh the operation. The repaint () method actually allows the AWT thread to call another method, Update. The UPDATE method will do two things by default, one is to clear the current area content, and the other is to call its Paint () method to complete the actual drawing. Paint, repaint, update three method relationships are shown in the figure:

But how do we make our circle? Here we use the FillOval function of the function Graphics class to set the round start position x, y. Now we have increased the value of Y per unit time in the thread run method, and the thread will re-draw a circular position within each unit time. The larger the Y value per unit, the faster the decline. On the screen we will see this round ball for free landing. The following code shows:

While (TRUE) {// Set Animation Movement Speed ​​Y = 1;} Public Void Paint (Graphics G) {// Set the color g.SetColor (color.blue) of the ball; // Draw one from the X, Y position Solid round G. Filloval (x, y, 2 * r, 2 * r);

Before this, we need to set some variables at the beginning, define the default location values ​​of x, y. r here is the radius of the circle we draw.

INT x = 100; int y = 20; int R = 10;

Our free landing animation is over. Is it very simple, if you still don't understand, you can download the full code and application here. Take a look at the real demo effects and code. Each section below will also be downloaded in the final source code and application download. If you are interested, you can change the value of Y, and the value of X, you will get different falling effects.

Double buffer, eliminate flashing

Everyone may notice that our decline in the above example does not look very clear, with very serious flashes. This phenomenon is a common phenomenon in writing a game program. This is due to the result of our repaint () function, because it automatically clears the screen before calling the Paint () function, we will see a blank screen in a millisecond, and there is a fast transform operation. Flashing phenomenon. There are several ways to solve this flicker. The following is a list of two ways, and everyone can try themselves.

The first: we have never cleared the screen display, but this method will bring an attachment, we decline the circle is not a circle, but a straight line, because there is no breakpoint during the decline, keep all the points Ball icon. As long as we add the following code Update (Graphics G) {Paint (g)} in Ball.java, you will see a long line. Interested friends can try it.

Second: Double buffer mechanism (Double Buffering)

Now most of the games use dual buffer mechanism to solve the flashing phenomenon of the screen, we will explain this as an example, and the concept of buffer and related buffer mechanisms can be referred to the buffering description of the appendix.

And our program is simple to say that before displaying the drawings we want, put all the drawings first draws and stored in the corresponding image variables in the back. You can copy it directly to the front screen when you need to display.

Implementation:

1. First we use the CreateImage method to create a rear image type variable

2. Then use the getGraphics () method to get the graphical association of the current image.

3. Process all related processing in the background, such as clear screen, background painting, etc.

When all the background work is completed, copy the image to the front desk and override the presence image of the front desk. So all of our operations are in front of the background, and these contents already exist in the background before the new image is displayed. So you will not see the existence of the empty screen at any time. That is, the representative flicker is eliminated.

Let's take a look at the relevant code description:

Before starting, we have to declare two instance variables in the beginning of the program to store the background drawing. as follows:

Private image bgimage; private graphics bg;

Then we use the UPDATE () method to implement a double buffer mechanism.

Update () method To implement the following three steps:

1. Clear the components on the screen

2. Set the foreground color of the associated components

3. Call the PAINT method to redraw screen

Public void update (graphics g) {// Initialization Bufferif (bgimage == null) {bgimage = createImage (this.getsize (). Width, this.getsize (); bg = bgimage.getgraphics ();} / / Background clear screen, which is the same color as the spheres and backgrounds, size bg.SetColor (GetBackground ()); Bg.FillRect (0, 0, this.getsize (). Width, this.getsize (). HEight) ; // Draw the corresponding element components Bg.SetColor (GetForeground ()); Paint (bg); // Heavy painting on the screen Soldering a round G.DrawImage (bgimage, 0, 0, this);}

Here G is the screen graphics, the BG is associated with the background of G. BGIMAGE includes BG graphics. Please take a look at our source code example and demo effect.

Change the direction of movement

We have solved two important issues of animation, moving animation and blinking. But we will find a problem soon, and the ball fell from the top of the screen. This is not what we need. What we want is a vivid picture. How to make our balls do not pass on the screen? Before you start, I suggest that you will find a way to solve it, if you can handle it yourself. Your level will have a big improvement. If you don't want to make a good way, it doesn't matter, let's take a very detailed description of the direction of the direction of the ball. I don't know if you pay attention, when we talk about the moving of the ball, we will make the new circle position and graphics by adding the value of Y. If the decline speed of the size of the value of the value is changed will also change. Yes, this is our solution, we only use a variable to store this speed size without a fixed value. In the thread execution, that is, the RUN method we use the code to change the speed of the speed, the direction of the ball will also change. That is, this variable "speed" is "-1". Of course, we must make judgments before setting the value, you want the ball to start the screen from doing the display, or rebound back and forth! If you want to rebound back, we will not let the radius value of the ball exceed the applet screen display area. Here we use R / 2 to represent the radius of the ball.

// Substall the drop ball if (y> appletsize_y - r / 2) {// change direction x_speed = -1;} // rebound to rise ball ELSE IF (

As for how to let the ball reappear from the top of the screen, we have not explained here, and it will not explain it. Leave yourself to think about it, it is very simple. In the following we have the source code and execution files of two ways. If you run the program, everyone may find that there are some changes in the size and speed of our ball. Here is to better reactive demo effects.

multimedia

Use multimedia sound

Multimedia features are a lot of parts in the game, beautiful music, and beautiful interfaces are often a condition for successful games.

Before starting, let's take a look at the main small sound file type: Au - (extension is Au or SND) Suitable for short sound files, the general file format for Solaris and next generation machines, is also the standard audio format of the Java platform . The three typical audio formats used by the AU type file are: 8-bit μ-Law type (usually sampling frequency is 8kHz), 8-bit linear type, and 16-bit linear type.

WAV - (extension WAV) is developed by Microsoft and IBM, and support for WAV has been added to Windows 95 and extends to Windows 98. WAV files can store various formats including μ-Law, A-Law and PCM ( Linear) data. They can be played by all Windows applications that support sound.

AIFF - (Extension AIF or IEF) Audio Interchange File Format is a standard audio file format shared for Macintosh Computers and Silicon Graphics (SGI) computers. AIFF and AIFF-C are almost the same, except for the latter to support, for example, μ-Law and IMA ADPCM type compression.

MIDI - (Extension MID) Musical instrument digital interface MIDI is a standard recognized for music manufacturing, primarily to control equipment such as synthesizer and sound card.

On JDK1.0, Java only supports * .au format sound files, but Java2's API and sound pack provide very powerful support for sound technology. And in order to make everyone quickly grasp the basic knowledge of game programming, we only use the Audioclip interface class to achieve "* .wav". If you are interested in referring to the SAPMLE of the Sun Java website, the above provides complete instances and tutorial descriptions.

Using the AUDIOCLIP interface is relatively simple, we only need to instance objects, after loading the sound file, play anywhere. The simplest way to recover and play sound is the Play () method of the Applet class. AudioClip interface

1. Play Play 2. Cycle loop 3. Stop STOP start and stop the sound file, or loop play, you must load it into the Audioclip object with the getaudioclip method of the applet, GetAudioclip method To use one or two parameters, as played Indicate. The first or unique parameter is the URL parameter, used to indicate the location of the sound file, the second parameter is the folder path pointer.

The following code line example will now describe the loading sound file into the clip-3: "Gun.wav" below refers to the sound file in the current directory. We can also replace files with * .au format.

Audioclip co = GetaudioClip (getCodeBase (), "gun.wav");

The getaudioclip () method can only be called within the applet. As Java2 introduces, the application can also load the sound file with the Newaudioclip method of the Applet class. The former example can be rewritten for Java applications:

Audioclip co = newaudioclip ("gun.wav")

We can now use Method Play play to play our voice anywhere. Play () once the call begins to restore and play sound. But this is a little attention: If the sound file cannot be found, there will be no error information, just silence. Source code and applications are downloaded here.

Image processing technology

The processing of the picture is as simple as the processing of the sound. Set the picture variable to get the graph, and finally draw the graph. We analyze directly from the code. Here we draw a background illustration of an applet. Before starting to draw, we must declare graphical variables to store graphics files.

Image backimage; // Load picture file backimgage = getImage (getCodeBase (), "black.gif");

Below our Paint () method to draw our graphics using the function DrawImage.

g.drawImage (Backmage, 0, 0, this);

BlackImage in the DrawImage parameter is the graphics we get, while the back 0, 0 represents the X coordinate and Y coordinate of the graphic .This: The class represents the class, which refers to the Picture class. It is recommended to use the image file in the * .gif format. Because if it is an Internet, the size of the file also determines how fast your applet is loaded, no one is very willing to wait for a long time to play your game, even if your game is relatively good. Source code and demo program download.

Do you have seen the character image walking when playing a game? Animation that runs back and forth? These are based on graphic technology. As long as we use the code above, we use the array variable to store our getting graph file group, and use the DrawImage () method to play the playback of animation images.

Image [] backmage; // load picture file for (int i = 4, i

You can refer to the Animation example in the JDK package, which is an example of a good set of image files.

Event processing

Mouse monitoring technology

When playing games, whether it is a small poker card and a large RPG game, it is necessary to participate in the role of the game. Good, interactive, game has a function of interacting to say is a complete game. Even programming games such as robotic football, Robocode must be programmers to participate in writing code and observe the game. There are two mainstream methods to achieve the interaction of the game: mouse and keyboard. Of course, there is also a gymnastic bar, but now in most PCs or mouse and keyboards. Based on these two, we will explain the response process of the event in the game. To determine the action of the corresponding mouse: Is it clicked or moved. We must monitor our mouse. To listen to the mouse event, you must call one of these interfaces, or extend a mouse adapters class. AWT provides two listening interfaces: java.awt.event.mouselistener and java.awt.event.mousemotionListener .

Now I design a mouse event, when you click on the Applet screen, the drop ball moves in the opposite direction. To achieve a simple control of the game.

MouseListener has a total of 5 methods, mainly used to achieve mouse click events. Here you should pay attention to a little: Since MouseListener is the interface we want to overload all of it in the implementation class.

Mouse click event

· MousePressed () happens when the user presses the mouse button.

· MouseReleased () happens when the user releases the mouse button.

MouseClicked () occurs when the user presses and releases the mouse button. The user usually clicks the mouse button when selecting or double-click the icon. Users can move the mouse before launch the mouse, click the mouse corresponding event.

· Because clicking the mouse is a combination of the mouse and release the mouse, the mousepressed () and mousereleased () methods are simultaneously called before the event is assigned to the mouseclicked () method.

Mouse status processing:

MouseEntered () activates the event when the mouse leaves the current component and enter the component you listen.

MouseExited () happens when the mouse leaves you listen.

Mouse Mobile Event

Mouse movement is mainly implemented by interface MouseMotionListener:

MouseDragged () When the user presses the mouse button and moves before being released. After mousedragged (), the mouse will not cause mouseclicked ().

MouseMoved () occurs when the mouse moves on the component and drags from time to time.

Based on our game design, we should use the Mouselistener interface here. Implement the interface. We want to add listener addMouselisner () to the init () function to listen to the response event to the applet.

Know the process of the mouse event, let's review the ball rebound design mentioned above, how do we handle the control of the ball? Let us think about it, good, maybe you have discovered that we can do the rebound control operation by changing the SPEED direction. Add the following code in the mousepressed () {} event, our rebound control is designed.

Speed ​​= -4

I remember that when I release the Applet resource, we have to release the Mouselistener resource. Add to Destory ()

REMOVEMOUSELISTENER (THIS);

Maybe some friends will use the mousedown () method, mousedown () here I suggest that you don't use this method again, it is already the product being eliminated. It is to bring to JDK1.0 to JDK1.4.

Keyboard listening technology

Knowing the operation of the mouse, the operation processing of the keyboard is very simple. We only need to implement the keylistener interface and join the code we want to implement in the corresponding event.

KeyPressed: When the button is button

Keyreleased: occurs when the translation key

KeyTyped: When the button is hitting

Because we don't use the keyboard operation in the game we design, the keyboard event handles us will be handed over to everyone. Now let's take a look at what we can do? Move an object, load sounds and pictures, and use the mouse to control the game. Oh, my day, we can already do your own very simple game. Yes, you can, I think there is this, everyone can put down the tutorial, the game you have always want to play, the game you have always wanted to do when you have a program, this for your help will be very big of. It is also a big improvement to your programming level.

Of course, if you still think that you know it is not very deep, let us design a complete game. This will be a very interesting process.

The first game - "Defense"

Main line ideas:

It is always very exciting to do your own game. Before starting anything, we have a good design, the game is more no exception. Let's take the above example. Design a "defender" game. The game ideas are very simple. From the top of the screen, there is a bomb, and our "defenders" should click on the mouse before they land, let it fall back, do not let it fall to the ground, but the ball is rising In the process, we should also pay attention to not let it hit on top. If you hit the top or painted, your life points will be reduced. Your fraction of a bomb in each point will increase. When your life points are zero. "Game over".

Design structure:

1. Module design:

The structure of the game is simple, consisting of three modules.

DENFEN Class: DENFEN Class Controls the entire game main thread, initialization bomb, and draws the number of bombs on the screen and the movement of the bomb, and listening to the mouse event

BOMB class: Mainly to determine the speed, direction of the bomb, hit the ground and click event

DENFENSE Class: Mainly used to handle the number of players and the number of life points

2. Method implementation:

Denfen:

INIT (): Initialize all objects, including the loading of the sound file, the generation of BOMB classes

Run (): Handling the decline in the bomb

Paint (...): Draw bombs and related data records

Update (...): Implement the double buffer of the screen image, eliminate flashing

MouseProcess (...): Use the MouseEvent event listening to handle the mouse to press the event, and determine if the X coordinate and Y coordinates at the time of the mouse.

Addbomb (): Using the default value to dynamically implement BMB generation, here we use an array to record. The default is 3, you can increase or reduce records according to your own hobbies.

Denfense:

Score: Points

Life: Life Point

Addscore (): Add the player's points

DEATH (): Reduce the number of gamers' life points

Getscore (): Get the current number of points

getLife (): Get the current life point

Bomb:

Bomb (...): Constructor, the value of the location of the bomb, the sound, color, etc. related to variables.

Down (): Processing BMB drop

IsreBound (): reverse rebound bomb, and speeds up the fell speed of bombs according to points

UserHit (int X, int y): Whether the player is bomb.

WashiteAarth (): Judging whether the bomb hits the ground or top, if it is a life point will be reduced.

Drawbomb (Graphics G): Draw Bomb Image.

3. Working principle:

First we load all the resources necessary for all games in the init () method, including sound, mouse event monitoring, background, etc. Use the addbomb () method to increase the number of BOMBs, initial positions, and initialization colors. Use the start () to start the thread. The thread calls the Run () method, and processing the bomb down movement DOWN (). Repaint () will call the Paint () method in each unit time, Paint () calls bomb.addbomb () draw bomb. When the player presses the mouse, the mousepress () event is activated, and it is determined whether the bomb is in. If addscore () is 1 point in your point. If you don't have a bomb, the bomb will continue to drop, when hitting the screen WashiteAarth () method, call the death () method, reduce the DenfenseSer.life life point, and audio.play () handle the playback of the sound, to prompt the game By. "Game over" when your life point is less than 0. This game is not very perfect. Here is some improvement method, you can try it. Make a game style that is suitable for you. For specific source code and implementation, please download. 4. Improvement of games:

Background Replacement, this background of this example is used as a function setBackground (), and you can replace it with the corresponding graph.

In order to reduce complexity, the number of bombs used by the example is fixed value 3, which we can add the number of bombs in the game according to the integration.

The level setting, there is no level in this game. If you join the level in the game, it will be a very interesting process based on different levels of changing the game.

Mode changes. We can implement your own mode in the game. Such as destroying the bomb. A bomb, let the bomb destroy from the screen.

We can also add a player to increase the playability of the game. Increase the processing function of the keyboard. Increase the flexibility of the game.

There are still a lot of processing and play, which is waiting for you to discover. I believe that Java game programming will be a very interesting learning process.

Appendix: Buffer mechanism

The buffer buffer is used to store colored pixels (images) in the video memory. The size of the buffer is determined by the resolution and color depth, such as the 800x600, 16 bit colored buffer occupies 800x600x2 (16bit = 2Bytes) memory area.

(1) The front buffer is the buffer currently displayed on the screen, and the rear buffer is a buffer that has not been displayed on the screen.

(2) SINGLE BUFFERING uses a front buffer, simultaneously displayed on the screen while colored. Therefore, when the screen is updated, it will flash. Single Buffering is rarely used in the current program.

(3) Double Buffering uses two buffers, a front buffer, a back buffer. The so-called preamp and back is relatively. The front cache pixel is displayed on the screen, and the graphics are tightly colored in the rear cache.

The colors of the rear cache are waiting in the form of vsync signals. After the front cache and the rear cache exchange, the new round of coloring work is restarted. This is just like the stage and background actor. When performing the front desk, the actors in the background are still in the final rehearsal. The actor at the front desk is now the time of the background actor debut. The only difference is that the preamp and rear cache is a cycle, and the actor is generally no longer playing. Most games are currently in Double Buffering.

(4) Triple Buffering uses a pre-cache and two back cache. After the data completed in the first rear buffer, the second rear buffer is immediately processed. Today, many new games are Triple Buffering, TRIBLE BUFFERING is gradually become a trend of development, because it does not have Vsync (the vertical refresh frequency of the screen) waiting time, the game will be more smooth. Triple Buffering is also an internal setting of 3DMark2000 test.

转载请注明原文地址:https://www.9cbs.com/read-108574.html

New Post(0)
CopyRight © 2020 All Rights Reserved
Processed: 0.069, SQL: 9