JAVA game works - mine
Abstract: JAVA game works - mine
*************************** Programming ideas ******************** ***********
The fry are familiar with the game, the mouse click box mine, if it is mine, Manpanjieshu, if not mine, the mine opened boxes, showing that the number of minefields around. If this box around lap mine is not mine, the mine should be around the boxes are opened, and were in accordance with the above rules on iterative cycle, this cycle should come to an end in the face of boxes containing Lei Lei there, or all the minefields boxes have been detecting End, the difficulty of programming it here, we pay more attention to bones_box under the category of the left mouse button click events and bones_triggers () process, with special attention to
Is_clicked this Boolean value, it is precisely because he makes the use of iterative As for the smooth conduct of mine, I immediately adopted the way, it was said that the company's mines is very sophisticated, I do not know that the algorithm, as if still a very deep Mathematical problems, you who had nothing to feed on the bar
************************************************** *****************/
Import java.awt .*;
Import java.awt.event .*;
Import javax.swing .*;
Import javax.swing.border .*;
Import java.util .*;
Public class bones_game / / Lord of the game, initialization interface, generating minefields
(
Public static int clicked_counter = 450; / / counters, 0:00 to the successful conclusion of that mine
JFrame MainFrame; / / main form
JButton button_refresh;
Bones_box bones_box [];// Lei box
Public bones_game () / / constructor
(
Int i;
Bones_box new bones_box = [450];
Button_refresh = new JButton ( "re-start the game");
MainFrame = new JFrame ( "mine games");
MainFrame.getContentPane (). SetLayout (new BorderLayout ());
Container box_grid = new Container ();
Box_grid.setLayout (new GridLayout (15th and 30th));
For (i = 0; i <450; i ++)// draw all minefields box
(
Bones_box [i] = new bones_box (i, this);
Box_grid.add (bones_box [i]);
)
Bones_sts_refresh ();// updated information
MainFrame.getContentPane (). Add (button_refresh, BorderLayout.NORTH);
MainFrame.getContentPane (). Add (box_grid, BorderLayout.CENTER);
MainFrame.pack ();
MainFrame.show ();
MainFrame.addWindowListener (new WindowAdapter ()
(
Public void windowClosing (WindowEvent e) (
System.exit (0);
)
));
Button_refresh.addMouseListener (new MouseAdapter ()
(
Public void mouseClicked (MouseEvent e)
(
Bones_sts_refresh ();
)
));
)
Public static void main (String [] argus)
(
Games start new bones_game ();//
)
Public void bones_sts_refresh () / / set all minefields boxes, layout information
(
Int i, j;
Clicked_counter = 450;
For (i = 0; i <450; i + +)
(
Bones_box [i]. SetEnabled (true);
Bones_box [i]. Is_clicked = false;
Bones_box [i]. SetVisible (true);
Bones_box [i]. Is_bone = false;
Bones_box [i]. Number_of_real_bone = 0;
Bones_box [i]. Flag = "";
Bones_box [i]. SetText ( "");
Bones_box [i]. SetBorder (BorderFactory.createBevelBorder (BevelBorder.RAISED, Color.white, Color.black ));// processes for the initial state
Bones_box [i]. SetBackground (Color.gray);
)
For (i = 0; i <90; i ++)// random minefields
(
Bones_box [(int) (Math.random () * 449)]. Is_bone = true;
)
For (i = 0; i <450; i ++)// statistics were each Lei Lei the number of boxes around
(
If (bones_box [i]. Is_bone) / / Lei Lei in the box and does not participate in overlapping zone, by the Counter
(
Bones_game.clicked_counter–;
)
For (j = 0; j <8; j + +)
(
If (bones_box [i]. Bones_around [j] == 777)
(
Continue;
)
If (bones_box [bones_box] [i]. Bones_around [j]]. Is_bone)
(
Bones_box [i]. Number_of_real_bone + +;
)
)
/ / Open the code can look at the distribution of mine
/ / If (bones_box [i]. Is_bone)
/ / (
/ / Bones_box [i]. SetText ( "â—");
/ /)
)
)
Public void game_lose ()
(
Int type, k;
For (k = 0; k <450; k + +)
(
If (bones_box [k]. Is_bone)
(
Bones_box [k]. SetText ( "â—");
)
)
Type = JOptionPane.INFORMATION_MESSAGE;
JOptionPane.showMessageDialog (MainFrame, "I am sorry, you lose, I would like to thank !!!"," messages" type);
Bones_sts_refresh ();
)
Public void game_win ()
(
Int type;
Type = JOptionPane.INFORMATION_MESSAGE;
JOptionPane.showMessageDialog (MainFrame, "serious Congratulations, you won, Shaque !!!"," messages" type);
Bones_sts_refresh ();
)
)
Class bones_box extends JTextField / / Lei box
(
Public boolean is_clicked = false; / / check whether the signs
Public boolean is_bone = false; / / Is mine
Public int bone_id; / / Lei box logo,
Public int [] bones_around; / / minefields around the box BONE_ID to form an array of records
Public bones_game frame_handle; / / handle of the game
Public int number_of_real_bone; / / lap around the total number of minefields
Public String flag; / / right-click on the logo "↑": logo for the mine "?": Uncertain state ",": space
Public bones_box (int i, bones_game handle) / / constructor
(
Super ();
This.bone_id = i;
/ / This.setEnabled (false);
This.frame_handle = handle;
This.setCursor (frame_handle.MainFrame.getCursor ());
This.setForeground (Color.cyan);
This.bones_around = find_bones_around ();// access to the ID boxes around the mine, an array of deposit bones_around
This.addMouseListener (new MouseAdapter ()
(
Public void mouseClicked (MouseEvent e)
(
Int j;
/*——————- Bond pronged ———————-
Capture poor results, it gives rise to the slightest deviation below the left or right, do not know if you are better able to accurately capture the way this incident, like Microsoft, did not even fingers the keyboard at the same time, can be captured, if found, could be below code package, and I told DEV一声
(
Int k, li_num;
If (is_clicked)
(
For (k = 0, k <8, k + +)
(
If (frame_handle.bones_box [bones_around] [k]]. Flag == "↑")
(
Li_num + +;
)
)
If (li_num == number_of_real_bone)
(
For (k = 0, k <8, k + +)
(
If (frame_handle.bones_box [bones_around] [k]]. Flag == "↑")
(
Continue;
)
If (frame_handle.bones_box [bones_around] [k]]. Is_clicked)
(
Continue;
)
If (frame_handle.bones_box [bones_around] [k]]. Is_bone) / / failure
(
Frame_handle.game_lose ();
Return;
)
Frame_handle.bones_box [bones_around] [k]]. SetBorder (BorderFactory.createBevelBorder (BevelBorder.LOWERED, Color.white, Color.black ));// Lei box Waxia Show
Frame_handle.bones_box [bones_around] [k]]. SetBackground (Color.WHITE);
Frame_handle.bones_box [bones_around] [k]]. SetEnabled (false);
Frame_handle.bones_box [bones_around] [k]]. SetText (Integer.toString (frame_handle.bones_box [bones_around] [k]]. Number_of_real_bone ));// suggested that the number of minefields around
Frame_handle.bones_box [bones_around] [k]]. Is_clicked = true; / / mark the box in order to detect a mine, and avoid the frequent with each other have infinite loop
Bones_game.clicked_counter–;
)
)
)
Else
(
)
)
————————————————– –* /
If (e.getButton () == e.BUTTON1) / / left click on the
(
If (is_clicked)
(
Return;
)
If (flag == "↑") / / logo of the mine, click the direct return
(
Return;
)
If (is_bone) / / is mine, suggesting that the game failure
(
Frame_handle.game_lose ();
Return;
)
SetBorder (BorderFactory.createBevelBorder (BevelBorder.LOWERED, Color.white, Color.black ));// Lei box Waxia Show
SetBackground (Color.WHITE);
SetEnabled (false);
SetText (Integer.toString (number_of_real_bone ));// suggested that the number of minefields around
Is_clicked = true; / / mark the box in order to detect a mine, and avoid the frequent with each other have infinite loop
Bones_game.clicked_counter–;
Bones_triggers ();// trigger process
If (bones_game.clicked_counter <= 0)
(
Frame_handle.game_win ();
)
)
If (e.getButton () == e.BUTTON3) / / Right
(
If (is_clicked)
(
Return;
)
If (flag == "")
(
SetText ( "↑");
Flag = "↑";
Return;
)
If (flag == "↑")
(
SetText ("?");
Flag = "";
Return;
)
If (flag == "?")
(
SetText ("");
Flag = "";
Return;
)
)
)
));
)
Find_bones_around public int [] () / / in accordance with their own BONE_ID identify minefields lap around the ID box
(
Bones_around int [] = new int [8];
Int i, li_row, li_column;
Li_row = bone_id / 30;
Li_column bone_id-li_row * = 30;
Bones_around [0] = li_column - 1 + (li_row - 1) * 30;
Bones_around [1] = li_column + (li_row - 1) * 30;
Bones_around li_column [2] + = 1 + (li_row - 1) * 30;
Bones_around [3] = 1 + + li_column li_row * 30;
Bones_around li_column [4] + = 1 + (li_row + 1) * 30;
Bones_around [5] = li_column + (li_row + 1) * 30;
Bones_around [6] = li_column - 1 + (li_row + 1) * 30;
Bones_around [7] = li_column - 1 + li_row * 30;
If (li_column == 0) / / first out of the special treatment, because he left the air, and this will be marked as in the 777
(
Bones_around [0] = 777;
Bones_around [6] = 777;
Bones_around [7] = 777;
)
If (li_column == 29) / / Finally a special treatment, because his right is empty
(
Bones_around [2] = 777;
Bones_around [3] = 777;
Bones_around [4] = 777;
)
For (i = 0; i <bones_around.length; i + +)
(
If (bones_around [i] <0 | bones_around [i]> 449)
(
Bones_around [i] = 777;
)
)
Return bones_around;
)
Public void bones_triggers () / / trigger process
(
Int k;
Boolean is_all_free = true;
For (k = 0; k <8; k + +)
(
If (bones_around [k] == 777)
(
Continue;
)
If (frame_handle.bones_box [bones_around] [k]]. Is_bone)
/ / Not judge whether all around the mine, if the condition is not met, there will be no automatic trigger the necessary boxes around the mine, leaving players to hit their own
(
Is_all_free = false;
Break;
)
)
If (is_all_free) / / set up the conditions to begin automatically detect mines around the box
(
For (k = 0; k <8; k + +)
(
If (bones_around [k] == 777)
(
Continue;
)
If (frame_handle.bones_box [bones_around] [k]]. Flag == "↑") / / has been marked as mine, Skip
(
Continue;
)
If (frame_handle.bones_box [bones_around] [k]]. Is_clicked) / / detection, Skip
(
Continue;
)
Bones_game.clicked_counter–;
Frame_handle.bones_box [bones_around] [k]]. SetEnabled (false);
Frame_handle.bones_box [bones_around] [k]]. SetBorder (BorderFactory.createBevelBorder (BevelBorder.LOWERED, Color.white, Color.black));
Frame_handle.bones_box [bones_around] [k]]. SetBackground (Color.WHITE);
Frame_handle.bones_box [bones_around] [k]]. SetText (Integer.toString (frame_handle.bones_box [bones_around] [k]]. Number_of_real_bone));
Frame_handle.bones_box [bones_around] [k]]. Is_clicked = true;
Frame_handle.bones_box [bones_around] [k]]. Bones_triggers ();// iteration trigger continue
)
)
)
)
/*—————————— Edited by Cang, Bashen tools: EditPlus + JDK1.4.2—— ————————-*/
↑ Back
I studied with the Game Design Java Swing
Abstract: I studied with the Game Design Java Swing
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width="677" border="0"> <tr> <td width = " 395 ">
Who knows sky tower of Babylon spent a number of gravel? Who knows Rome experienced the completion of the number of day and night? We only know that there is no one piece of masonry features, there will be no winding Miles of the Great Wall; no boulder clay and the accumulation, there is no time immemorial unchanged pyramid. Thus, the basic knowledge for learning anything we are of the utmost importance, then, let us recognize Swing from some of the basic features, we have started the construction of Rome's great project!
Foreword
Java cafe has opened a lot of time, if you are already fond of the Java cup of coffee flavor, often to remember oh. This time, we all prepared for a large cup aromatic coffee - will be the development of a "Lianliankan" modelled on the game, and we learn together in Java Swing usage, when you taste carefully cup of coffee, you will found that not only Java cup of coffee also have some other flavor, but also learned the professional game development, is the best of both worlds!
</ Td> <td width="272" align="center"> </ td> </ tr> </ table>In order to let everyone see in advance the facilities, the chart is the title game. Members can download the game demo (download games; download source files), then use the command line mode java-jar kyodai.jar to run. In addition, I can go to the Home http://www.ismyway.com download stand-alone version of the game as well as a demo version of mobile phones (see Figure 1).
Java cafe previously introduced AWT knowledge, Swing and AWT then what is the difference? Learning Java people may have heard or seen a heavyweight controls and controls lightweight word AWT is that we usually referred to the heavyweight controls, it is lightweight Swing controls. We all know that Java is the slogan of "one preparation, running everywhere," which will require our procedures, to make the best use of pure Java code. Unfortunately, AWT rely on the local interface platform, therefore, in different operating systems, making use of AWT interface may seem there are some subtle differences. Swing is completely different, using pure Java Swing is prepared, therefore, prepared by the use of Swing interface can be guaranteed in all platforms have the same appearance. There is also a Tips: JDK, in order to facilitate the distinction between all Swing controls all capital letters J to the beginning, for instance, JButton (AWT in the corresponding Button is), so you can easily distinguish between AWT Swing controls and controls the.
Swing early experience
For those who want to learn Swing programming friends, we are all specially prepared for some tips. First, download and read the code is very necessary. Since this is a tutorial on the Swing, therefore, we are just as much as possible on some of the contents of the Swing, Swing has nothing to do with the content of the general will not be involved, for example, some algorithm. Secondly, to space restrictions, it will not be possible here will be part of the code is written in every End integrity of the whole, therefore, we also need to control integrity of the code. Finally, in order to make it easier for you to concentrate on Swing learning, we will also required in game development resources on the downloaded file, you can download after compiler operation, to see the results.
1. Top containers
What is the top containers? When we use graphical programming Java, where plans drawn? We need to provide a graphic containers, the containers are called top-level containers, and you can imagine it as a window. Top container is the foundation for graphical programming, and all graphical things will inevitably included in the top container. In Swing, we have the top three can be used in containers, they are:
JFrame: similar to the Windows operating system used to design window in the form of applications.
JDialog: JFrame and similar, but JDialog is used to design the dialog box.
JApplet: design can be used in embedded in the Web page Java applets.
If you need to use a window of Swing production processes, we should be the code looks like this:
Import javax.swing .*; Public class KyodaiUI (Extends JFrame …… )
2. Control
Control is an Application Program Interface of the basic elements, buttons, text boxes, such as the progress of these controls are. Controls (here we only discuss visualization Control) containers can be divided into control and non-control containers. From the literal meaning of understanding, containers can contain other controls that controls the special controls, for example, in Java JPanel controls on the type of vessel control, we can JPanel placed buttons, text boxes, and other non-container control , you can even further in the JPanel placed several JPanel Control (It is worth noting that the top container-type containers also controls every window in the application and there can be only one top containers controls, in other words , the top containers could not be included in the other controls).
Java containers in a lot of controls, in addition to the JPanel just mentioned, there are JTabbedPane, JScrollPane, a non-container control JButton, JLabel, such as JTextField. If you need to control a certain type of containers to add controls, you can use the add (Component comp) method to achieve, such as:
JPanel panel = new JPanel (); JButton button = new JButton (); Panel.add (button);
3. Layout
What is the layout? Java is the layout of controls are used to control the location of an interface management system. The use of other visual programming language Java in the initial contact interface design, always feel very uncomfortable Java interface design: there were no controls to provide WYSIWYG settings coordinate method! However, facts have proved that the layout of Java itself provide the same management system can be successfully fulfilled our needs, but also in cross-platform performance when there are more advantages.
The layout of commonly used are:
BorderLayout: interface will be divided into upper and lower middle, as well as about a regional management system, in BorderLayout layout, the most you can only put five controls, if more than five controls, the proposed distribution or use other systems it.
GridLayout: GridLayout user interface is the same cutting board for the distribution management system. If we are to design a similar built-in calculator in Windows software, GridLayout is undoubtedly the best option.
FlowLayout: FlowLayout layout with the above-mentioned two types of management systems do not, as in FlowLayout, you do not have to specify on which each control, you need only to control into FlowLayout, FlowLayout will, in accordance with you to add controls Controls placed the order, if the space is insufficient, will be automatically newline.
In the layout of this management system has several basic understanding, we have to design an interface to enter it. QQ in the careful observation of the game "Lianliankan" settings, we can be found, the entire interface is divided into three zones, is the top menu system, the area is the largest user games, in addition to a user Interactive areas, in each region by the number of control components.
So many controls, where we start with the beginning? The containers can be placed in the control of other controls, therefore, we have only to make sure the containers placed controls on it. Since it has been aware of the need to control the number of containers used, let us enter the next distribution management system. With GridLayout? Seems to be some reluctance by FlowLayout? There are better options? Right, I think you have thought of is BorderLayout bar, as shown in Figure 2.
Before hands, we must pay attention to is that the interface design must consider good size, is the main program interface regardless of the size or the size of each region, in the absence of good design appropriate size, with future changes will be very painful.
Below is the corresponding source:
Import java.awt .*; Import javax.swing .*; Public class KyodaiUI extends JFrame ( Public KyodaiUI () ( This.setSize (780, 500) / / set to form the size of 780 * 500 This.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); This.setResizable (false); / / size of the form can not be changed This.setTitle ( "Lianliankan"); / / Set Title JPanel toolBar = new JPanel (); ToolBar.setBackground (Color.white); ToolBar.setPreferredSize (new Dimension (780, 48)); JPanel actionPanel = new JPanel (); / / JPanel new type of control ActionPanel.setBackground (Color.yellow); / / Set the background color ActionPanel.setPreferredSize (new Dimension (160, 380)); / / size settings JPanel contentPanel = new JPanel (); ContentPanel.setBackground (Color.blue); ContentPanel.setPreferredSize (new Dimension (620, 380)); This.getContentPane (). Add (toolBar, BorderLayout.NORTH); This.getContentPane (). Add (actionPanel, BorderLayout.EAST); This.getContentPane (). Add (contentPanel, BorderLayout.CENTER); ) Public static void main (String [] args) throws HeadlessException ( KyodaiUI kyodaiUI = new KyodaiUI (); KyodaiUI.show (); ) )
Let us look at the above is how this process operates. First of all, this extends JFrame that is inherited from the JFrame, JFrame top container is the most basic controls. In fact, in the JDK, beginning with the letter J controls are Swing controls. And then set up a container attributes, including setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) is used to tell the Java Virtual Machine, when users click on the upper right corner of the form "off" button, the process of closing the window. If we do not do so, you will find that although you can be dispatched window closed, but did not withdraw from the process. In the next code, we added three top containers Panel containers. It should be noted that in the AWT, we can write directly to add (toolBar, BorderLayout.NORTH), and it must be in the Swing wrote getContentPane (). Add (toolBar, BorderLayout.NORTH), otherwise the process will be wrong.
Now we can look at the operation on the compiler, and I was not running the same as (see Figure 3)?
4. Borders
Although we use different Jianjingse to distinguish between different regions, but did not layered with beautiful borders will be many.
In Java, all J beginning of the Swing controls can be used for setBorder ways to set up their own borders. There are many types of borders, linear, convex, Waxia, air, and you can even free combination formed personal style. All Border javax.swing.BorderFactory must be provided in the use of the static method to create, for example:
Border border = BorderFactory.createBevelBorder (BevelBorder.LOWERED, New Color (45, 92, 162), New Color (43, 66, 97), New Color (45, 92, 162), New Color (84, 123, 200));
Now, we will toolBar.setBackground (Color.white) to toolBar.setBorder (border), the three-dimensional effect is not there have been?
Actual combat - write their own name
Now we have a functioning interface, although it do anything, but please Biehuang, Rome was not built in one day.
Let us now in the area to provide a menu "on the" menu, the procedures used to display information, can you do not want to let others know your name? Swing itself provides a ready JButton button control, we only need to create a new button: JButton about = new JButton ( ""); how this button into the menu area and not elsewhere? We can join the following code: toolBar.add (about); Yi, how push of a button does not respond? This is because you have not told the procedures to be done at the click of a button is what happened. Add the button to respond to the incident, first of all, need to use about.addActionListener (this) to tell procedures eavesdropping button pressed the incident, due ActionListener is a procedural interface Therefore, we stated in the category have to do a bit of local small Laws: public class KyodaiUI extends JFrame implements ActionListener {…} achieve ActionListener interface to tell the procedures I have to carry out the deal with the incident. Of course, we must add the final response to the incident code:
Public void actionPerformed (ActionEvent e) ( If (e.getSource () == about) ( JOptionPane.showMessageDialog (this, "My name", "on", JOptionPane.INFORMATION_MESSAGE); Return; ) )
Among them, e.getSource () that controls the current trigger events, as we often have procedures in a number of the above controls, these controls are likely to produce the event, we must use this method to find an issues Control.
Summary
Let us together look at the content of today: First, we know the top-level containers, know that the control is divided into control and non-container vessel control, but also noted that the use of frames, finally, we also deal with minor a touch of a button events.
When learning of the school and not between also said that, let me leave small operations to help consolidate what we have learned today: Add button above us in the middle of the menu bar is not handsome, please put Try the right or left.
Next: Java Swing with me in the game design (2)
Remember "plays an activist miner" as in the Wizard shuttle traffic in Hollywood in the Minicooper? Makewoerbage and Shali Sialon is driving its enemies under the nose removed 10 million worth of gold. However, if one can not now Minicooper appearances on the Mercedes-Benz in front of you, how would you treat it? It is the same ease of migration wizard? Today, let us point to 1.1 for这辆Minicooper parts on the assembly and let it run up.
Foreword
Starting from this issue, we provide you with complete source code of the game (click to download). Java cafe advocacy we both theory and practice, we will introduce series of key technologies and the realization of ideas, and friends, read the article with their own source code, like the side of a cup of coffee while reading newspapers, and this is never drops of aromatic Italy do.
Game layout
"Lianliankan" is a two-dimensional Zhanji games, it is necessary to design the chessboard of the game, should be GridLayout Mr Chong. Now let us look at a GridLayout to the constructor function:
GridLayout (): the default case, the layout of the region into the size of 1 * 1
GridLayout (int rows, int cols): designation of the regional distribution of horizontal and vertical grid of
GridLayout (int rows, int cols, int hgap, int vgap): Ditto, and also designated each lattice spacing between the horizontal and vertical spacing vgap hgap
Do not let the three million constructor function deterred you to the fact, as long as you like, can rest assured bold use of any one of which, if not carefully used "wrong", also after adjustment approach. Only need to pay attention to that, in addition GridLayout control, the default order is from the upper left to lower right were added.
Let us now to determine the number of games lattice. Lattice how many more appropriate? Too little will reduce the difficulty of the game, too much will cause visual impact. Therefore, we should, through a constant for the future even if changes are Jushouzhilao.
In Java, the constant need for the definition of public final static written in the form of the game if we stipulate that the board has eight in the horizontal grid, there are also eight vertical lattice, then we should take this definition:
Public final static int ROW = 8; Public final static int COLUMN = 8;
Then, we use the second constructor function GridLayout to create layout:
GridLayout gridLayout = new GridLayout (ROW, COLUMN);
Finally, we also need to play area (contentPanel) to the layout of the layout:
ContentPanel.setLayout (gridLayout);
If you compile and run a program at this time, you may be surprised: Interface how there had not been any change, which is not wrong? Although we designated the layout, but also did not add any controls, of course, to see changes. Let us together in the layout on the Add button bar:
For (int i = 0; i <ROW * COLUMN; i + +) ( JButton button = new JButton ( "Kyodai"); ContentPanel.add (button); )
Try to run a program, and I was not the same (see Figure 1)?
Using make a fuss about JButton
JButton is a button control, it is common in Swing are not ordinary longer controls, nevertheless, we still need to spend some effort to understand and use it, because when you can skillfully use JButton, you will find that other Swing Control is also so similar.
If you have written operating procedures used, you will find: the game is always a very full button, and it is very real inconvenience to the operation of the game, so we have to find ways to let out some air lattice. GridLayout layout of what is good, adding that the controls when not skip a certain lattice, Yanxiage how do?
In fact, this will not be difficult, since GridLayout from Skip, if we allow the addition of a lattice GridLayout layout of the controls and the integration background, so that the visual reach a consensus on the results. In addition, if people accidentally click on this lattice, the button still will be reversed and we have to try to not let the button is clicked, and this requires the use JButton setEnabled () method. Finally, can click on the button, and when they are clicked, we need to distinguish between what is out which button was clicked on.
In the last to achieve the "on" function, we used the e.getSource () method to determine your mouse, click on the source of the incident, however. That good name has been on the controls more effective. Here, the use of an array of buttons that is the best way to, first of all, let us amend the above code:
JButton [] = new JButton dots [ROW * COLUMN]; For (int i = 0; i <ROW * COLUMN; i + +) ( Dots [i] = new JButton ( "Kyodai"); Dots [i]. SetActionCommand ( "" + i); ContentPanel.add (dots [i]); Dots [i]. AddActionListener (this); )
Do not forget to write in the circle of dots on the [i] = new JButton ( "Kyodai"), although in the previous definition, the use of a group of dots, but it is only just told procedures we need to use some of JButton, but these JButton but still have not been initialized. At the same time, we not only use setActionCommand () for the development of the incident button name, also used the addActionListener () method for each button with the incident response handling.
On the incident response code, we can in the original actionPerformed () code inserted after the incident:
If (e.getSource () instanceof JButton) ( JButton button = (JButton) e.getSource (); Int offset = Integer.parseInt (button.getActionCommand ()); Int row, col; Row = Math.round (offset / COLUMN); Col = offset - row * COLUMN; JOptionPane.showMessageDialog (this, "ROW =" + + row, "COL =" + Col, "button", JOptionPane.INFORMATION_MESSAGE); )
In the above code, e.getSource () instanceof JButton used to determine whether the incident is JButton the type of control, and then the source will produce the event-type controls to mandatory conversion, re-use Integer.parseInt (button.getActionCommand ()) method to obtain the name of the incident into integer, as the code will make the trip and the integer reduction in the information.
Well, operational procedures, and then click each button to see whether there will be any of the dialog box as pictured?
Attention Oh, our next objective is to start from zero.
Swing in the use of picture
At present we have solved the problem of the user operation. To handsome interface, we need to use the picture to replace text. Have the time and patience of friends can do their own personalized picture, but should pay attention to each picture the same size, otherwise difficult Kanla. Think it can be easy to use packages downloaded directly in the picture.
In Swing, you can use setIcon (Image image) method to set up JButton picture, which is that the parameters of image we want to set the picture object, and this object can be a number of ways:
Use Toolkit class to be:
Image = Toolkit.getDefaultToolkit (). GetImage (url);
Use ImageIcon class getImage () method to obtain:
Image = new ImageIcon (getClass (). GetResource (filename)). GetImage ();
Here we use the first method. In order to facilitate future access to the Image object again, we can write this as a function:
Image getImage (String filename) ( URLClassLoader urlLoader = (URLClassLoader) this.getClass (). GetClassLoader (); URL url = null; Image image = null; Url = urlLoader.findResource (filename); Image = Toolkit.getDefaultToolkit (). GetImage (url); Return image; )
With this function, the picture later on to use more convenient, is not it?
Picture now have, then we would be in the source code package Map.Java map information in the form of performance using picture out. Because this section of the game is code algorithm code, it is no longer listed code, and here is broadly explain how specific do! In Map.Java, we used two-dimensional array map [] [] to preserve picture information, and we also use the one-dimensional images [] array to preserve a picture of each object, a map of each element are have a value, this value has not only shown that in the game interface buttons corresponding value, this button also shows that the use of images in the picture [] array of numbers, it is running pretty many interface.
Summary
Today, we introduced the Swing of JButton controls. For most Swing controls, the use of JButton can copy the past. Do not underestimate this JButton, when you can grasp it very well when you have the Swing on the foundation of the upgrade to a higher level. In addition, we also learned in Java loading image files are two methods. Finally, we will be part of the contents of the above two together and created a beautiful interface of the game. Although I am not here to write integrity of the code, but I believe that the reference to the source, through its own efforts, we can achieve our goals. If they can not solve the problems, you can contact me leftmoon@163.com Box
↑ Back
Loaading game design –
Abstract: Loaading game design –
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="274" height="86" align="center" valign="top"> </ td> <td width="410" valign="top"> Why do so many games to Loading of the accession rolling? Loading joined state is not to make the software more professional appearance, but the operating procedures in order to ensure that memory does not overflow. Usually computer / cell phone storage system is divided into: cup of cache, disk (or cell phone used in the storage of FLASH RAM, or other types of preservation can be durable storage systems), operating memory. We know that usually NOKIA S40 of the heap size is 200 KB size, and usually the accession process and three 128 * 128 images on the memory after the collapse, and to add voice and maps, on the procedures for computing memory is too short. Generally speaking, many in the running game just when all the one-time resources into the heap memory read this, we have procedures in the simulator to see the situation is very close to the brink of collapse, if we do not care to join a new picture, may be do not have enough computing memory.
How can we not solve the heap size matters? Phone is not able to change its heap size, we only have to find ways to control the use of heap memory. The most direct approach is: storage memory and computing the optimal use of memory, when the computing resources needed from the memory storage memory call, the need for new resources, they do not require the release of swaps. Below I explain our code with a section on how to make Loading is the state.
</ Td> </ tr> <tr> <td height="20" colspan="2">As we all know, Java is the built-in multi-thread, we can use two threads to resolve the issue of loading, a reading resources thread, a thread drawing resources. Code:
Import javax.microedition.midlet .*;
Import javax.microedition.lcdui .*;
/ **
* Loading demo
* @ Author gaogao
* * /
Class MainCanvas
Extends Canvas
Implements Runnable (
/ / State procedures
Static final int LOADING = 0;
Static final int GAMEING = 1;
/ / Procedures state Controller
LOADING = int state;
/ / Main thread
Thread thread = null;
/ / Loading is completed,
Boolean isLoaded = false;
/ / Internal category, the new open access resources threads
Class Loading
Implements Runnable (
/ / Thread,
Thread innerThread = null;
Public Loading () (
InnerThread = new Thread (this);
InnerThread.start ();
)
Int counter = 100;
Public void run () (
/ / Read simulation resources
/ / To the following things into the code can be read resources
While (counter> 0) (
Counter -;
Try (
Thread.sleep (20);
)
Catch (Exception ex) ()
)
/ / End loading
IsLoaded = true;
)
)
Loading loading = null;
Public MainCanvas () (
Loading = new Loading ();
Thread = new Thread (this);
Thread.start ();
)
Int loadingCounter = 0;
/ / Draw ..
Public void paint (Graphics g) (
G.setColor (0);
G.fillRect (0, 0, getWidth (), getHeight ());
Switch (state) (
Case LOADING: (
G.setColor (0XFFFFFF);
G.drawString ( "LOADING" + ">>>>>". substring (0, loadingCounter)
GetWidth ()>> 1, getHeight ()>> 1.
Graphics.HCENTER | Graphics.TOP);
LoadingCounter loadingCounter% + + = 5;
)
Break;
Case GAMEING: (
G.setColor (0XFFFFFF);
G.drawString ( "GAME", getWidth ()>> 1, getHeight ()>> 1.
Graphics.HCENTER | Graphics.TOP);
)
Break;
)
)
Public void run () (
While (true) (
Try (
Thread.sleep (100);
)
Catch (Exception ex) (
)
If (isLoaded) (
Loading = null;
State = GAMEING;
)
Repaint (0, 0, getWidth (), getHeight ());
ServiceRepaints ();
)
)
)
Public class Main
Extends MIDlet (
MainCanvas mc;
Public void startApp () (
If (mc == null) (
Mc = new MainCanvas ();
Display disp = Display.getDisplay (this);
Disp.setCurrent (mc);
)
)
Public void destroyApp (boolean bool) ()
Public void pauseApp () ()
)
</ Td> </ tr> </ table>
</ Td> </ tr> <tr>
↑ Back
Tuixiangzi game-source
Abstract: Tuixiangzi game-source
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="171" height="86" align="center" valign="top"> </ td> <td width="529" valign="top">
Downloading to the source, a total of 12 games clearance.
Games are played: you want to enter first grade, according to Enter, and then click the cursor keys Tuixiangzi. All boxes will be put on the target location you through.
I do not know which fans will be able to Swing of the game, thank you!
</ Td> </ tr> <tr> <td height="20" colspan="2">
</ Td> </ tr> </ table> </ td> </ tr> <tr>
↑ Back
Eat beans and a game-source
Abstract: eat beans and a game-source
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td height="64" align="center" valign="top"> </ td> </ tr> <tr> <td height="20">
Eat beans and a game source. .
</ Td> </ tr> </ table> </ td> </ tr> <tr>
↑ Back
Simple game Tuixiangzi
Abstract: The simple game Tuixiangzi
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="511" height="86" align="left" valign="top"> previously always longing to write games, but never write that the game is also a very difficult process.
The rewriting of Tuixiangzi, not the functions. Just realized: the right audience and the mobile boxes, including the detection of the wall when all the boxes arrive at their destination in time, it suggested that "Congratulations clearance" Players can use the keyboard "below" to the progress of control direction is the idea of the entire code: the game interface as a two-dimensional array, and then use a Boolean array boolean a [] [] to fill it. The players, true to the wall and boxes, destined for false. All elements of the interface are the target of a Node class, when a [] [Node.x Node.y] is true, on behalf of the players encountered box or wall, and then gave the achievement of the relevant algorithms..
Below is the code:
Import javax.swing .*;
Import java.awt .*;
Import java.awt.event .*;
Import java.util .*;
Import java.awt.geom .*;
</ Td> <td width="173" valign="top"> </ td> </ tr> </ table>
Public class PushBox (public static void main (String args []) (GameFrame frame = new GameFrame (); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.show (); JOptionPane.showMessageDialog (null, "red box on behalf of play home \ n purple box to the blue box, pushed through \ n keys control the direction \ n not to return to the previous step ");)) class GameFrame extends JFrame (static int num; public GameFrame () (setSize (400, 400) ; Container c = getContentPane (); GamePanel panel1 = new GamePanel (); c.add (panel1);)) class GamePanel_2 extends JPanel (public GamePanel_2 () (this.setBackground (Color.BLACK);)) class GamePanel extends JPanel implements KeyListener (int width = 400; int height = 400; Box b; Node man; Node box; Node [] target; int d = 1 / / moving step int sideX = 25; int sideY = 25; GameFrame frame ; ArrayList wallList; / / initialization interface elements public GamePanel () (this.setBackground (Color.WHITE), b = new Box (this, width / sideX, width / sideY); this.man = b.man; this . box = b.box; this.target = b.target; this.wallList = b.wallList; this.setFocusable (true); this.addKeyListener (this);) public void paintComponent (Graphics g) (super.paintComponent ( g); Graphics2D g2 = (Graphics2D) g / / background rendering the game, players and boxes. g2.setColor (Color.white); g2.fillRect (0, 0, width, height); g2.setColor (Color. RED); draw (g2, man); g2.setColor (Color.MAGENTA); draw (g2, box); draw (g2, b.box1); draw (g2, b.box2); draw (g2, b. box3); / / Drawing walls g2.setColor (Color.darkGray) for (int i = 0; i <wallList.size (); i + +) (Node n = (Node) wallList.get (i); draw (g2 , n);) / / mapping destination. g2.setColor (Color.blue) for (int i = 0; i <target.length; i + +) (g2.drawRect (target [i]. x * sideX, target [i]. y * sideY, sideX - 1, sideY - 1); Ellipse2D e = new Ellipse2D.Double (target [i]. x * sideX, target [i]. y * sideY, sideX - 1, sideY - 1 ); g2.draw (e);)) public void keyPressed (KeyEvent e) (int keycode = e.getKeyCode (); if (keycode == KeyEvent.VK_UP) (Box.direction = 1; / / set the orientation for first Mobile b.move again (0,-d);) else if (keycode == KeyEvent.VK_RIGHT) (Box.direction = 2; b.move (d 0);) else if (keycode == KeyEvent.VK_DOWN) (Box.direction = 3; b.move (0, d);) else if (keycode == KeyEvent.VK_LEFT) (Box.direction = 4; b.move (-d, 0);)) public void keyReleased ( KeyEvent e) () public void keyTyped (KeyEvent e) () public void draw (Graphics2D g, Node n) (g.fillRect (nx * sideX, ny * sideY, sideX - 1, sideY - 1);)) class Node (int x; int y; public Node (int x, int y) (this.x = x; this.y = y;)) (boolean end class Box = false; int maxX; int maxY; boolean [] [] a; / / regional entire game is a Boolean type of two-dimensional array Node man; Node [] target; / / storage destination Node box; Node box1; Node box2; Node box3; Node [] wall; / / storage wall Node [] b; / / b array storage boxes. GamePanel panel; / / When a push to the purpose of boxes, storage destination node list. ArrayList list = new ArrayList (); / / storage wall. ArrayList wallList = new ArrayList (); public static int left = 4; public static int up = 1; public static int right = 2; public static int down = 3; public static int direction = 0; / / BOX constructor, using Boolean Two-dimensional arrays filled games, while the definition players, boxes and destination. Public Box (GamePanel p, int maxX, int maxY) (panel = p; this.maxX = maxX; this.maxY = maxY; a new boolean = [] [maxX maxY]; for (int i = 0; i <maxX ; i + +) (for (int j = 0; j <maxY; j + +) (a [i] [j] = false;)) / / definition box, the initial audience and destination locations int x = 5; int y = 8; man = new Node (x, y); a [x] [y] = true; / / definition of the game's box location, and home to TRUE; b = new Node [4] = new box Node (10, 9); a [10] [9] = true; b [0] = box; box1 = new Node (6, 7); a [6] [7] = true; b [1] = box1 ; box2 = new Node (11, 8); a [11] [8] = true; b [2] = box2; box3 = new Node (8, 8); a [8] [8] = true; b [ 3] = box3; / / definition of the wall and destination. createWall (); target = new Node [4]; target [0] = new Node (7, 9); target [3] = new Node (6, 9) ; target [1] = new Node (7, 10); target [2] = new Node (6, 10);) public void move (int d1, int d2) (a [] [man.y man.x] = false; man.x + = d1; man.y + = d2; / / If the player encountered wall, it can not move forward, otherwise, promote boxes. if (a [man.y man.x] []) ( if (isOutofwall ()) (moveDisable (man, d1, d2);) else (for (int i = 0; i <b.length; i + +) (if (man.x == b [i]. x & & man . y = b [i]. y) (b [i]. d1 = x +; b [i]. d2 = y + / / use of a box IF judge whether the overlap, if overlapping, it can not go forward; if (a [b [i]. x] [b [i]. y]) (moveDisable (man, d1, d2); moveDisable (b [i], d1, d2);) else (/ / it must boxes true for the location of home, or moving a box after no longer mobile. a [b [i]. x] [b [i]. y] = true; / / If all pushing boxes in place, the end of the game / / In this procedures, methods to isArrive home in a box for the true future use. isArrive (b [i]);))))) panel.repaint (); if (end) (JOptionPane.showMessageDialog (null, "over"); System . exit (0);)) / / generate maps public void createWall () (for (int i = 5; i <12; i + +) (Node walls = new Node (i, 5); wallList.add (walls)
for (int i = 11; i <14; i + +) (Node walls = new Node (i, 6); wallList.add (walls);) wallList.add (new Node (13, 7)); wallList. add (new Node (13, 8)); wallList.add (new Node (13, 9)); wallList.add (new Node (12, 9)); wallList.add (new Node (12, 10)); for (int i = 12; i> 4; i -) (Node walls = new Node (i, 11); wallList.add (walls);) wallList.add (new Node (5, 10)); wallList. add (new Node (4, 10)); wallList.add (new Node (4, 9)); wallList.add (new Node (4, 8)); wallList.add (new Node (4, 8)); wallList.add (new Node (4, 7)); wallList.add (new Node (5, 7)); wallList.add (new Node (5, 6)); wallList.add (new Node (7, 7) ); wallList.add (new Node (8, 7)); wallList.add (new Node (9, 7)); wallList.add (new Node (8, 9)); wallList.add (new Node (8, 10)) / / will be home for the object of the walls true for (int i = 0; i <wallList.size (); i + +) (Node n = (Node) wallList.get (i) a [ny] [nx ] = true;)) / / hit the wall, the players can not advance public void moveDisable (Node n, int d1, int d2) (switch (direction) (case 4: nx -= d1; break; case 1: ny -= d2; break; case 2: nx -= d1; break; case 3: ny -= d2; break;)) / / determine whether the players across the border public boolean isOutofwall () (for (int i = 0; i <wallList.size (); i + +) (Node n = (Node) wallList.get (i) if (nx man.x == == & man.y ny) (return true;)) return false;) / / If all the boxes in place, then the game to an end public void isArrive (Node n) (for (int i = 0; i <target.length; i + +) (if ((target [i]. x == nx & target [ i]. y == ny)) (list.add (target [i]);) else if (target [i]. x == man.x & target [i]. y == man.y) (list . remove (target [i]);)) if (list.size () == target.length) (end = true;)))
</ Td> </ tr> <tr>
↑ Back
Shithead poker game-source
Abstract: source Shithead poker game
: 1539]
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="237" height="86" align="center" valign="top"> </ td> <td width="447" valign="top">
Shithead is a network version of the poker game, the game can be a person people can play in the LAN or Internet play. Game based on the type of MS Hearts, which includes similar functions. This game with JAVA development, and is open-source software. For more information please visit:
Http://home.pacific.net.au/ ~ cavenagh / SH /
First, the operation of the game: in order to activate
C: \ java> java SHinterface
äºŒã€æ¸¸æˆçš„ç›®æ ‡ï¼š
style=”mso-ansi-language: EN-US”>争å–ç¬¬ä¸€ä¸ªå‡ºå®Œä½ æ‰€æœ‰çš„æ‰‘å…‹ç‰Œã€‚ Second, the goal of the game:
style=”mso-ansi-language: EN-US”>End for the first out all your cards. style=”mso-ansi-language: EN-US”>游æˆè§„则大约是:
style=”mso-ansi-language: EN-US”>Rules of the game is about: style=”mso-ansi-language: EN-US”>å¦‚æžœä½ æ˜¯ç¬¬ä¸€ä¸ªå‡ºç‰Œï¼Œä½ å¯å‡ºä»»ä½•ä¸€å¼ ç‰Œï¼Œä½†å¦‚æžœå‡ºè¿‡ç¬¬ä¸€å¼ ç‰ŒåŽä½ å°±åªèƒ½å‡ºå¤§äºŽæˆ–ç‰äºŽæ¡Œé¢çš„牌。
style=”mso-ansi-language: EN-US”>If you are a card, you can any one card, but if ever first card you can only after a greater than or equal to the desktop licensing.
style=”mso-ansi-language: EN-US”>例如,如果上手出的是6, ä½ å¯ä»¥å‡ºä¸€å¼ æˆ–å‡ å¼ æ¯”6å¤§çš„ç‰Œï¼Œä½†ä½ ä¸èƒ½å‡ºæ¯”6å°çš„牌。
style=”mso-ansi-language: EN-US”>If, for example, is 6 to get started, you can produce one or a few large than 6 licensing, but you can not smaller than 6 licensing.
style=”mso-ansi-language: EN-US”>å¦‚æžœä½ æ²¡æœ‰ä»»ä½•ç‰Œå¯å‡º,ä½ å°±å¿…é¡»æŠŠæ¡Œé¢ä¸Šçš„牌全部收回,å¦å¤–牌2å’Œ10是特别的牌,有特别的规定.
style=”mso-ansi-language: EN-US”>If you do not have any licence can be a, you must be on the table licensing fully recovered, and 10 other unlicensed 2 is a special licence, there are special requirements. style=”mso-ansi-language: EN-US”>ä½ å¿…é¡»å…ˆå‡ºå®Œæ‰‹ä¸çš„牌,å†å‡ºæ¡Œé¢ä¸Šç¿»å¼€çš„牌,æœ€åŽæ‰æ˜¯æ²¡æœ‰ç¿»å¼€çš„牌.
style=”mso-ansi-language: EN-US”>End you must be out of the hands of licensing, opened again on the desktop licence, the final card is not opened. style=”MARGIN: 0cm 0cm 0pt; mso-list: l0 level1 lfo5; tab-stops: list 36.0pt”> Play is the open licensing and pressure below did not open licensing style=”MARGIN: 0cm 0cm 0pt; mso-list: l0 level1 lfo5; tab-stops: list 36.0pt”> Play the details style=”MARGIN: 0cm 0cm 0pt; mso-list: l0 level1 lfo5; tab-stops: list 36.0pt”> You need the licence style=”MARGIN: 0cm 0cm 0pt; mso-list: l0 level1 lfo5; tab-stops: list 36.0pt”> Information Box style=”MARGIN: 0cm 0cm 0pt; mso-list: l0 level1 lfo5; tab-stops: list 36.0pt”> You open the licensing and pressure below did not open licensing style=”MARGIN: 0cm 0cm 0pt; mso-list: l0 level1 lfo5; tab-stops: list 36.0pt”> The card game </ Td> </ tr> </ table>
Function TempSave (ElementID) (CommentsPersistDiv.setAttribute ( "CommentContent" document.getElementById (ElementID). Value); CommentsPersistDiv.save ( "CommentXMLStore");) function Restore (ElementID) (CommentsPersistDiv.load ( "CommentXMLStore"); document . getElementById (ElementID). CommentsPersistDiv.getAttribute value = ( "CommentContent");) </ td> </ tr> <tr>
↑ Back Abstract: I rewrite the Tanshichi MVC game (game-BigF original) : / / GreedSnake.java //———————————————— ———————- / ** Int timeInterval = 200; / / time interval, ms Int score = 0; / / scores / / UP and DOWN should be even Public SnakeModel (int maxX, int maxY) ( Reset (); Public void reset () ( / / Initial matirx, all-0 / / Initial the snake / / Create food Public void changeDirection (int newDirection) ( / ** / / In accordance with changes in the direction of the coordinate values / / If the new coordinates fell within the scope of effective, treatment / / Score rules, and the number of mobile change direction and speed of the two elements CreateFood food = () / / create a new food Public void run () ( If (! Paused) ( Private Node createFood () ( Return new Node (x, y); Public void speedUp () ( Public void speedDown () ( Public void changePauseState () ( Public String toString () ( Class Node ( Node (int x, int y) ( //———————————————— ——————— / ** Public SnakeControl (SnakeModel model) ( Public void keyPressed (KeyEvent e) ( / / Processed under any circumstances keys, buttons lead to restart the game Public void keyReleased (KeyEvent e) ( Public void keyTyped (KeyEvent e) ( //———————————————— ———————- / ** JFrame mainFrame; Public static final int canvasWidth = 200; Public static final int nodeWidth = 10; Public SnakeView (SnakeModel model, SnakeControl control) ( MainFrame = new JFrame ( "GreedSnake"); Container cp = mainFrame.getContentPane (); / / Create scores of the top of the show / / Create the middle of the game shows that the region / / Create underground with the help of column MainFrame.addKeyListener (control); Void repaint () ( / / Draw background / / Draw the snake / / Draw the food UpdateScore (); Private void drawNode (Graphics g, Node n) ( Public void updateScore () ( Public void update (Observable o, Object arg) ( Java, java, J2SE, j2se, J2EE, j2ee, J2ME, j2me, ejb, ejb3, JBOSS, jboss, spring, hibernate, jdo, struts, webwork, ajax, AJAX, mysql, MySQL, Oracle, Weblogic, Websphere, scjp, scjd Abstract: Araneid Spider Solitaire game source code : Spider Solitaire games Araneid Detailed reference works Home: http://pub.idr.gov.cn/dujid/projects/araneid Download the source code (or annex): Binary downloads: Please running decompress, and then the implementation of the classes directory start.bat Welcome discussion, please send an e-mail to verify or dujid@idr.gov.cn Java, java, J2SE, j2se, J2EE, j2ee, J2ME, j2me, ejb, ejb3, JBOSS, jboss, spring, hibernate, jdo, struts, webwork, ajax, AJAX, mysql, MySQL, Oracle, Weblogic, Websphere, scjp, scjd Araneid Spider Solitaire game Detailed reference works Home: http://pub.idr.gov.cn/dujid/projects/araneid Download the source code (or annex): Binary downloads: Please running decompress? Abstract: Based on the Nokia mobile phone game development step by step-[job is reposted] Based on the Nokia mobile phone game development-step by step
</ Td> </ tr> <tr> <td height="20" colspan="2">
I rewrite the Tanshichi MVC game (game-BigF original)
/ **
* Program Name: Tanshichi
* Original author: BigF
* Laws: algo
* Note: before I wrote this procedure in C, Java is used to write BigF see this, the authors found that while claiming to be a Java beginner,
* But obviously good quality of the preparation process, program structure is written very clearly, there are some subtle in places where it is written very succinctly, a rise of 1
* I carefully read this procedure, separate performance data and found a good, and I recently are learning MVC design pattern,
* Therefore try to change the structure of procedures to use to achieve MVC model, the small changes in the source code.
* I have also added some of its own procedures in the understanding of the Notes, we hope that the reading help.
* /
(Public class GreedSnake
Public static void main (String [] args) (
SnakeModel model = new SnakeModel (20, 30);
SnakeControl control = new SnakeControl (model);
SnakeView view = new SnakeView (model, control);
Model.addObserver (view);
(New Thread (model)). Start ();
)
)
/ / SnakeModel.java
Import javax.swing .*;
Import java.util.Arrays;
Import java.util.LinkedList;
Import java.util.Observable;
Import java.util.Random;
* Model of the game, will be responsible for all relevant data and running game
* /
Class SnakeModel extends Observable implements Runnable (
Boolean [] [] matrix; / / instructions on the location of the snake or no food
LinkedList nodeArray = new LinkedList (); / / snake -
Node food;
Int maxX;
Int maxY;
Int direction = 2; / / snake running in the direction
Boolean running = false; / / Operation
Double speedChangeRate = 0.75; / / each in the speed of change rate
Boolean paused = false; / / suspended signs
Int countMove = 0; / / eat food before the number of mobile
/ / RIGHT and LEFT should be odd
Public static final int UP = 2;
Public static final int DOWN = 4;
Public static final int LEFT = 1;
Public static final int RIGHT = 3;
This.maxX = maxX;
This.maxY = maxY;
)
= SnakeModel.UP direction; / / snake running in the direction
TimeInterval = 200; / / time interval, ms
Paused = false; / / suspended signs
Score = 0; / / scores
CountMove = 0; / / eat food before the number of mobile
Matrix = new boolean [maxX] [];
For (int i = 0; i <maxX; + + i) (
Matrix [i] = new boolean [maxY];
Arrays.fill (matrix [i], false);
)
/ / Initialization of the snake, if the horizontal position over 20, a length of 10, otherwise half of the horizontal position
Int initArrayLength maxX => 20? 10: maxX / 2;
NodeArray.clear ();
For (int i = 0; i <initArrayLength; + + i) (
Int x = maxX / 2 + i;
Int y = maxY / 2;
NodeArray.addLast (new Node (x, y));
Matrix [x] [y] = true;
)
CreateFood food = ();
Matrix [food.y food.x] [] = true;
)
/ / Can not change the direction of the same to the original direction or reverse
If (direction% 2! NewDirection% = 2) (
= NewDirection direction;
)
)
* Operate a
* @ Return
* /
Public boolean moveOn () (
Node n = (Node) nodeArray.getFirst ();
Int x = nx;
Int y = ny;
Switch (direction) (
Case UP:
Y -;
Break;
Case DOWN:
Y + +;
Break;
Case LEFT:
X -;
Break;
Case RIGHT:
X + +;
Break;
)
If ((0 <= & x x <maxX) & & (0 <= y & y <maxY)) (
If (matrix [x] [y]) (/ / If the new coordinates of the point on the things (or snake-food)
If (x == == food.x food.y & y) (/ / eat food, success
NodeArray.addFirst (food); / / gifts from the long snakeheads
Int scoreGet = (10000 - 200 * countMove) / timeInterval;
ScoreGet score + => 0? ScoreGet: 10;
CountMove = 0;
Matrix [food.y food.x] [] = true; / / set up food location
Return true;
) Else / / snake eat its own body of failure
Return false;
) Else (/ / If the new coordinates of the point of Nothing (of the snake), mobile snake -
NodeArray.addFirst (new Node (x, y));
Matrix [x] [y] = true;
N = (Node) nodeArray.removeLast ();
Matrix [nx] [ny] = false;
CountMove + +;
Return true;
)
)
Return false; / / touched sideline, failure
)
Running = true;
While (running) (
Try (
Thread.sleep (timeInterval);
) Catch (Exception e) (
Break;
)
If (moveOn ()) (
SetChanged (); / / Model View data has been updated notice
NotifyObservers ();
Else ()
JOptionPane.showMessageDialog (null,
"You failed."
"Game Over"
JOptionPane.INFORMATION_MESSAGE);
Break;
)
)
)
Running = false;
)
Int x = 0;
Int y = 0;
/ / Random access to an effective and snakes in the region of food and non-overlapping position
Do (
Random r = new Random ();
X = r.nextInt (maxX);
Y = r.nextInt (maxY);
) While (matrix [x] [y]);
)
TimeInterval *= speedChangeRate;
)
TimeInterval / = speedChangeRate;
)
Paused =! Paused;
)
String result = "";
For (int i = 0; i <nodeArray.size (); + + i) (
Node n = (Node) nodeArray.get (i);
Result + = "[" + + nx "," + + ny "]";
)
Return result;
)
)
Int x;
Int y;
This.x = x;
This.y = y;
)
)
/ / SnakeControl.java
Import java.awt.event.KeyEvent;
Import java.awt.event.KeyListener;
* MVC in Controler, responsible for receiving user operation, and to notify the user Model
* /
Public class SnakeControl implements KeyListener (
SnakeModel model;
This.model = model;
)
Int keyCode = e.getKeyCode ();
If (model.running) (/ / running, to deal with the button
Switch (keyCode) (
Case KeyEvent.VK_UP:
Model.changeDirection (SnakeModel.UP);
Break;
Case KeyEvent.VK_DOWN:
Model.changeDirection (SnakeModel.DOWN);
Break;
Case KeyEvent.VK_LEFT:
Model.changeDirection (SnakeModel.LEFT);
Break;
Case KeyEvent.VK_RIGHT:
Model.changeDirection (SnakeModel.RIGHT);
Break;
Case KeyEvent.VK_ADD:
Case KeyEvent.VK_PAGE_UP:
Model.speedUp ();
Break;
Case KeyEvent.VK_SUBTRACT:
Case KeyEvent.VK_PAGE_DOWN:
Model.speedDown ();
Break;
Case KeyEvent.VK_SPACE:
Case KeyEvent.VK_P:
Model.changePauseState ();
Break;
Default:
)
)
If (keyCode KeyEvent.VK_R == | |
KeyCode KeyEvent.VK_S == | |
KeyCode == KeyEvent.VK_ENTER) (
Model.reset ();
)
)
)
)
)
/ / SnakeView.java
Import javax.swing .*;
Import java.awt .*;
Import java.util.Iterator;
Import java.util.LinkedList;
Import java.util.Observable;
Import java.util.Observer;
* MVC model in the Viewer, is responsible only for the amount of data that can ignore the game and the control logic
* /
Public class SnakeView implements Observer (
SnakeControl control = null;
SnakeModel model = null;
Canvas paintCanvas;
JLabel labelScore;
Public static final int canvasHeight = 300;
Public static final int nodeHeight = 10;
This.model = model;
This.control = control;
LabelScore = new JLabel ( "Score:");
Cp.add (labelScore, BorderLayout.NORTH);
PaintCanvas = new Canvas ();
PaintCanvas.setSize (canvasWidth + 1, canvasHeight + 1);
PaintCanvas.addKeyListener (control);
Cp.add (paintCanvas, BorderLayout.CENTER);
JPanel panelButtom = new JPanel ();
PanelButtom.setLayout (new BorderLayout ());
JLabel labelHelp;
LabelHelp = new JLabel ( "PageUp, PageDown for speed", JLabel.CENTER);
PanelButtom.add (labelHelp, BorderLayout.NORTH);
LabelHelp = new JLabel ( "ENTER or R or S for start", JLabel.CENTER);
PanelButtom.add (labelHelp, BorderLayout.CENTER);
LabelHelp = new JLabel ( "SPACE or P for pause," JLabel.CENTER);
PanelButtom.add (labelHelp, BorderLayout.SOUTH);
Cp.add (panelButtom, BorderLayout.SOUTH);
MainFrame.pack ();
MainFrame.setResizable (false);
MainFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
MainFrame.setVisible (true);
)
Graphics g = paintCanvas.getGraphics ();
G.setColor (Color.WHITE);
G.fillRect (0, 0, canvasWidth, canvasHeight);
G.setColor (Color.BLACK);
LinkedList na = model.nodeArray;
Iterator it na.iterator = ();
While (it.hasNext ()) (
Node n = (Node) it.next ();
DrawNode (g, n);
)
G.setColor (Color.RED);
Node n = model.food;
DrawNode (g, n);
)
G.fillRect (nx * nodeWidth,
Ny * nodeHeight,
NodeWidth - 1,
NodeHeight - 1);
)
String s = "Score:" + model.score;
LabelScore.setText (s);
)
Repaint ();
)
)
↑ Back Araneid Spider Solitaire game source code
Http://pub.idr.gov.cn/dujid/projects/araneid/download/araneid-1.1.0-src.zip
Http://pub.idr.gov.cn/dujid/projects/araneid/download/araneid-1.1.0.zip
Http://pub.idr.gov.cn/dujid/projects/araneid/download/araneid-1.1.0-src.zip
Http://pub.idr.gov.cn/dujid/projects/araneid/download/araneid-1.1.0.zip
↑ Back Based on the Nokia mobile phone game development step by step-[job is reposted]
Author: wayne Source: yesky
First, game development strategy
1 game action (Action) use
MIDP the Canvas class programmers to deal with certain key events, either as a specific incident of a low-keying code of the game either as abstract movements. FullCanvas Nokia is the full-screen canvas (FullCanvas) category, it is inherited from the Canvas class.
Round game in the system or do not need more than four direction keys (Upper and Lower, left, right) of the game, the best use of the keyboard code directly to control the game action. Action games can be used abstract examples include the international chess games and quizzes and puzzle games, which are using the direction keys to scroll the screen or move.
Game action should only be the need for rapid response in the use of the game. This is because the choice of equipment may mapping of the game moves quickly to requests for action of the game does not apply. And, if requested ramp of a game or the direction keys of this game is a fast-paced action games, then hand the game to a mobile gaming needs of the role of one hand the need to perform other tasks, such as shooting, opened the door, and so on, then on the need to use the keyboard code directly. Reason is that the MIDP does not inclined action of the game, and game action mapping is designed for the use of a hand.
When using the keyboard code directly of the incident, must pay special attention to application portability.
Between different devices in the layout of the keyboard is very different (see Figure 1, are two different phone keyboard layout). Developers can allow users to define their own keys in the game the way to solve the problem. This can be in the game or the game before the start of the "choice" in the pages completed.
Keyboard code and game action in the same application procedures should never mix.
Figure 1, different mobile phone keyboard layout
2 Description of the game action
A MIDlet application by calling the Canvas method to detect what code mapped to the keyboard applications running game in the abstract movement:
Public static int getGameAction (int keyCode);
Canvas class-action games abstract definition: UP, DOWN, LEFT, RIGHT, FIRE, and so on.
Game Developers should know MIDP 1.0 specification in a problem. This class defines the code into the keyboard to move the game, also defines the action to the keyboard into the game code approach.
Public int getGameAction (int keyCode)
Public int getKeyCode (int gameAction)
Methods getKeyCode (int gameAction) may lead to some problems, which only returned to action games based on the code of a keyboard, even if MIDP 1.0 allows more than one keyboard code to achieve. Nokia in the mobile phone, a number of individual keyboard mapping to the same code of the game action, such as "UP button" and the "2-button" has been mapped to upward moves of the game. This method can only return to one of them; return to the specific value is realized. However, if the method getGameAction (int KeyCode) the use of "UP button" and the "2-button" keyboard code as a parameter, this method will return to correct the upward movement of the game. Below look at a bad example to deepen our impression:
/ / Bad example, do not do so:
(Class TetrisCanvas extends Canvas
Int leftKey, rightKey, downKey, rotateKey;
Void init () (
/ / FOLLOWING MUST NOT BE DONE
LeftKey = getKeyCode (LEFT);
RightKey = getKeyCode (RIGHT);
DownKey = getKeyCode (DOWN);
RotateKey = getKeyCode (FIRE);
)
Public void keyPressed (int keyCode) (
If (keyCode == leftKey) (
MoveBlockLeft ();
) Else if (keyCode = rightKey) (
…
)
)
)
Below is a better solution:
(Class TetrisCanvas extends Canvas
Void init () (
)
Public void keyPressed (int keyCode) (
Int action = getGameAction (keyCode);
Switch (action)
(
Case Canvas.LEFT:
MoveBlockLeft ();
Break;
Case Canvas.RIGHT:
MoveBlockRight ();
Break;
)
)
)
This example is the MIDP 1.0 specification example, the use of getKeyCode (int gameAction) of the code dealing with the keyboard, only to return a value. If so, other possible keymap MIDlet can not be used. For example, there will be in the Nokia 7650, Nokia 7650 there are five keys and a joystick, as well as ordinary keyboard layout, and above example will return joystick rather than the value of the value of the keyboard. This is a handling of the event has nothing to do with the equipment the way, and it is a bad approach. A better solution is to keyPressed () method used getGameAction (int KeyCode). Normally, applications should be avoided getKeyCode (int gameAction) method and always use getGameAction (int KeyCode).
3 shell game and game action
Nokia mobile phone models support of the new shell game action might affect the game. Nokia first shell game can use the phone is Nokia 3510i (see Figure 2). If the phone shell game support, and equipment and there will be a game menu Settings dialog box that allows users to set up shell game on the button corresponding action of the game. Users must install the button mapping, the use of otherwise ordinary keyboard layout design of the game can not run.
Figure 2, Nokia 3510i (left) original shell (right) shell game
4 button at the same time
Many Nokia phones (such as Nokia 6310 i, 3410,7210) does not support multi-button press at the same time (that is, if you hold down the Up button, then the MIDlet will not know whether you you press Fire button). Although Nokia 7650 supports multi-button press at the same time (for example, at the same time holding down the "1" and "3" keys), but physical button on the joystick is not at the same time, according to the left and upward by, so it is impossible to have in the game of the oblique campaign, and it is upward, downward, press the left or right when the record is not a "click".
5 keys: avoid hard coding your own text string
Avoid the hard-coded text and in your MIDlet code associated with the keyboard. Canvas classes provide a return linked to each keyboard code name of the text:
Public static String getKeyName (int keyCode);
Nokia is the equipment problem is this method always returns a string English, rather than depending on the user's choice of language. Nokia equipment in the future, this might be a string of the language based on user choice. If your objective is to develop portable game, then it must be remembered getKeyName in different Nokia MIDP devices return different values.
Use full-screen canvas 6 (FullCanvas) function keys
Based on a full-screen canvas (FullCanvas) game screen function keys can only be used to screen out from the game to a different state of the screen. FullCanvas category with the Nokia user interface and application programming interface to provide a clear full-screen graphics for regional mapping, can be used for many types of games.
Inherited from Nokia user interface application programming interface FullCanvas category of the game will not screen keyboard function keys to the code (ie KEY_SOFTKEY1, KEY_SOFTKEY2, KEY_SOFTKEY3) used for game-related action, unless it is for the game to return to the menu screen .
If a MIDlet application needs to use function keys order, then you must use the default MIDP Canvas class, especially if you need to use the MIDlet label when the button. When you use the FullCanvas, you should not provide your own function keys labels.
7 international MIDlet
You may need to put your MIDlet international - for example, for different regions and languages. MIDP system attributes "microedition.locale" definition of the current regional equipment. Its value can be used System.getProperty. Method achieved. MIDP norms in the system to allow the use of an empty attribute value. However, in the Nokia MIDP implementation of the value of the space is not allowed. CLDC system attributes "microedition.encoding" defines the default character encoding equipment. Its value can be obtained using methods System.getProperty.
To learn more about the localization of MIDlet can see "Writing World Aware J2ME Applications" http://wireless.java.sun.com/midp/ttips/worldaware/ the Resource Kit. MIDP also present in the absence of a standard mechanism to deal with Resource Kit. This document the use of a simple way to user interface text separated from the main program. It Resource category (2, 9) being processed.
Join the international characteristics of a MIDlet very important, but it may increase the size of your MIDlet. If MIDlet size for a particular MIDP devices, is a problem, you may wish to have several different versions of the compiler MIDlet. Each version can be one or more regional, language localization.
8 equipment features: voice, vibration and lighting
If you use Nokia user interface application programming interface type or DeviceControl Sound (vibration, lights), you should provide a Options or Settings menu and set up an editor, to allow end-users start or cancel such settings.
However, if you use Nokia user interface application programming interface type or DeviceControl Sound (vibration and lighting) and by setting parameters JAD <> you to the installation of the game to Games menu (see 1, 11), the menu has been Games the settings allow end-users start or cancel these characteristics. Therefore application is not necessary to create their own such a characteristic. In addition to Nokia UI API technical documentation, you can also reference "Nokia UI API Programmer 's Guide", it can offer a lot of useful information.
Irrelevance of equipment 9
Nokia MIDP devices may screen size, keyboard layout and the availability of API, and so different. In order to create a portable game, in the design of the game, these differences should be taken into account.
Application systems should be asked to screen size, and to avoid drawing screen content when the hard-coded coordinates. Canvas can be used like getHeight and getWidth method to achieve this objective.
Nokia MIDP different equipment in the application programming interface great changes, developers should check the equipment to the development of platform application programming interface. It can be done, vibration, is a good example.
Try (
Class.forName ( "com.nokia.mid.ui.DeviceControl");
)
Catch (ClassNotFoundException e) (
/ / Can't use vibration because the API
/ / Is not supported in the device
)
Use MIDP Canvas inherited from the default category of the game the screen FullCanvas replace vendor-specific category, which would help improve the portability of your MIDlet However, it can not achieve the full screen.
10 Optimization
MIDP equipment memory is very limited, the use of memory to be extra cautious. The game is a very important limitation is the limited heap memory (heap memory): In order to save heap memory, object reference no longer need to be set to "null", in order that they may be targets of garbage - collection (garbage-collected) . Color screen cell phones need more memory to deal with the application of bitmaps, with a larger screen-depth and relevant internal data structure. Thus, although an application may be prepared to use a black-and-white screen cell phones, but cell phone use in color, it may consume more dynamic memory: the Nokia 7210, it shows a picture than Nokia 6310i 16 times more memory.
Developers should be applied in the design process, to take into account this factor, it should be loaded at the same time the picture of the number dropped to the lowest level. For example, the flashing screen image of the game should be able to create graphical images prior to garbage collection (all to the image by setting targets for the application of "null").
11 installation
Default under MIDlet Nokia equipment was installed under the Applications menu. If the equipment is the Games menu, MIDlet can also set the MIDlet. Jad documents in the Nokia-MIDlet-Category: Game parameters to install this menu.
Second, the steps to achieve the game
The chart below shows the MIDlet is a game in the successful installation and operation of the state after the user interface changes in the typical process. We would like to through a player's perspective on the development of mobile gaming process.
Figure 3 user interface state chart
Started the game 1
MIDlet users start, the game will show specific flashing screen. FullCanvas flashing screen is an example. It can be used to display a company logo or using animation in the presentation of the game. In addition to all the outside End keys keyboard events (MIDlet available) can be Skip flashing screen and display the main menu. It should also be used to set up a time limit, can automatically after a certain period of time to set aside flashing screen from the game screen.
GameMIDlet category is the basic game; MIDlet deal with it and deal with the life cycle of the game show. The following code is flashing screen and the framework of MIDlet games.
/ / Skeleton for the base class of game
Import javax.microedition.midlet .*;
Import javax.microedition.lcdui .*;
Public class GameMIDlet extends MIDlet (
Private Display display = null;
/ / Splash screen that starts the application
Private SplashFullCanvas splash;
Public GameMIDlet () (
Splash = new SplashFullCanvas (this);
)
Protected void startApp () (throws MIDletStateChangeException
If (display == null) (
Display = Display.getDisplay (this);
)
/ / Splash screen to the display
SetDisplayable (splash);
)
Protected void pauseApp () (
)
Protected void destroyApp (boolean p0)
(Throws MIDletStateChangeException
)
Public void setDisplayable (Displayable dl) (
Display.setCurrent (dl);
)
)
/ / Skeleton for the splash screen in Nokia Java Game
Import javax.microedition.lcdui .*;
Import java.util.Timer;
Import java.util.TimerTask;
Import com.nokia.mid.ui .*;
Public class SplashFullCanvas extends FullCanvas (
Private GameMIDlet parent = null;
Private MainMenu menu = null;
Private Timer timer = null;
Public SplashFullCanvas (GameMIDlet parent) (
This.parent = parent;
Menu = new MainMenu (
Resources.getString (Resources.ID_GAME_NAME)
List.IMPLICIT, parent);
StartTimer ();
)
Protected void paint (Graphics g) (
/ / Do the splash screen here
)
Protected void keyPressed (int keyCode) (
Timer.cancel ();
Timer = null;
/ / All key events received set the main menu to the screen
Parent.setDisplayable (menu);
)
/ / Timer for the splash screen. Main menu is set to the display
/ / 5 seconds after.
Private void startTimer () (
TimerTask task = new TimerTask () (
Public void run () (
Parent.setDisplayable (menu);
)
);
Timer = new Timer ();
Timer.schedule (task, 5000);
)
)
2 Main Menu (MainMenu) screen
Game is the main menu contains options specific to the inherent directories ( "Continue" and "New game", "Options", "High scores," "Instructions", "About" and "Exit game"). "Continue" Only in the game will be suspended for the time being displayed. When the "Continue" Show time, it must be a directory list of elements. Heading to the main menu is the name of the game. The following code is the framework of the main menu.
/ / Skeleton for the main menu
Import javax.microedition.lcdui .*;
Public class MainMenu extends List implements CommandListener (
Private GameMIDlet parent = null;
Private GameFullCanvas game = null;
Public MainMenu (String p0, int p1, p2 String [], [] p3 Image,
GameMIDlet parent) (
Super (p0, p1, p2, and p3);
Init (parent);
)
Public MainMenu (String p0, int p1, GameMIDlet parent) (
Super (p0, p1);
Init (parent);
)
Public void init (GameMIDlet parent) (
This.parent = parent;
This.setCommandListener (this);
/ / If game paused then "Continue" should be available in
/ / Selection list
If (game! = Null & game.isPaused ()) (
If (! (This.getString (0). Equals (
New String (Resources.getString (
(Resources.ID_GAME_CONTINUE )))))
This.insert (0,
Resources.getString (Resources.ID_GAME_CONTINUE)
Null);
)
This.setSelectedIndex (0, true);
)
Else (
/ / These must be with or without icons
This.append (Resources.getString (Resources.ID_GAME_NEW), null);
This.append (Resources.getString (Resources.ID_GAME_OPTIONS), null);
This.append (Resources.getString (
Resources.ID_GAME_HIGHSCORES), null);
This.append (Resources.getString (
Resources.ID_GAME_INSTRUCTIONS), null);
This.append (Resources.getString (Resources.ID_GAME_ABOUT), null);
This.append (Resources.getString (Resources.ID_GAME_EXIT), null);
)
)
Public void commandAction (Command p0, Displayable p1) (
List lis = (List) p1;
String selected =
Lis.getString (lis.getSelectedIndex ());
If (selected.equals (Resources.getString (Resources.ID_GAME_NEW))) (
Game = new GameFullCanvas (parent, this);
Parent.setDisplayable (game);
)
Else if (selected.equals (
Resources.getString (Resources.ID_GAME_OPTIONS))) (
Parent.setDisplayable (
New OptionList (Resources.getString (Resources.ID_GAME_OPTIONS)
List.IMPLICIT,
Parent, and this));
)
Else if (selected.equals (
Resources.getString (Resources.ID_GAME_HIGHSCORES))) (
Parent.setDisplayable (new HighScore (parent, and this));
)
Else if (selected.equals (
Resources.getString (Resources.ID_GAME_INSTRUCTIONS))) (
Parent.setDisplayable (
New Instructions (
Resources.getString (Resources.ID_GAME_INSTRUCTIONS), the parent, and this));
)
Else if (selected.equals (
Resources.getString (Resou