In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
In this issue, the editor will bring you about how to achieve the Nian Beast Battle Game in Java. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.
Preface
The Spring Festival is coming, I am used to seeing all kinds of Mini Game at the front end, it is really well done, very exquisite. But I also want to make a little contribution to the back-end programmers and make a java version of the Battle of the New year.
This game, plus writing articles, fishing time at work and free time to go home, probably took more than three days.
Java wrote that it was really painful to play, with all kinds of status bits, all kinds of pictures and logical judgments, my head was about to explode. And certainly does not have the front end exquisite, the effect is general, occasionally will have the stutter, everybody just wants to have fun, casually applauds the audience. The process is greater than the result.
Source code gitee address
First, the introduction of how to play
When you enter the initial interface, you will see a Lunar New year beast in the middle, and then a small tiger, that is, our player. Click "Space" to start the game:
Tap the space and you will enter the game. From top to bottom are:
The amount of blood of the animal in the year [NIAN'S HP]
The moving Nian Beast
The lowermost tiger [player]
Players use the [←] [→] key to move the direction of the tiger and use the [S] key to fire shells:
When Nian Beast is hit, fireworks appear in the background:
Every time you hit the middle-aged beast three times, the Nian beast will drop the bomb:
If the player is hit, then directly [game over], use the [space] key to start over:
When you hit the middle-aged animal 10 times, its health will be reduced by one, and the New year will randomly drop different kinds of firecrackers, currently 11, players can move the key to get:
When the player successfully receives the shell and hits the Nian Beast again, the type of background fireworks will be changed. Originally, I wanted to change the bullet, but then I couldn't fix it. I played for a long time and wanted to take a picture, but I didn't succeed for a long time. I lost my mindset, that is, the following fireworks:
When Nian Beast is defeated, the words "Happy New year" will appear:
The above is all the way to play, in fact, there can be more expansion, java to write this thing is really too painful.
Second, code introduction
The effect is not very good, but it is always good to learn code implementation. Let me briefly talk about how to achieve it.
2.1 Program entry [Frame]
Using Frame as the basis and entrance of the interface, you can set the size, title, display location and so on. The most important thing is to add a panel on the basis of again, which is the implementation of our game:
Public static void main (String [] args) {/ / 1. Create the window object Frame frame = new Frame ("Battle of the year"); / / set the form size to 900x800 frame.setSize (900,800); / / set the form to center format frame.setLocationRelativeTo (null); / / set the form immutable frame.setResizable (false); / / add a panel frame.add (new GamePanel ()) to the form. / / set form visible frame.setVisible (true); / / Click in the window to close frame.addWindowListener (new WindowAdapter () {@ Override public void windowClosing (WindowEvent arg0) {System.exit (0);}});} 2.2 Constructor [GamePanel]
The first step is to define an empty parameter construction. You need to add focus events, listen for keyboard events, start page refresh with a timer, and then create a timer:
Public GamePanel () {/ / get focus event this.setFocusable (true); / / add keyboard listening event this.addKeyListener (this); / / start timer timer.start ();} 2.3 Game Logic implementation [GamePanel]
In the startup class, we add a GamePanel to the Frame to show all the content of the later game, including the page, game logic and so on.
The code is more complex, I only say the key points, all the code in the gitee link at the beginning of the whole article, interested to get their own.
Class GamePanel extends JPanel implements KeyListener, ActionListener
As shown above, GamePannel inherits JPanel and implements both KeyListener and ActionListener.
JPanel
This is the basic container provided by jdk for drawing using java. The panel does not add color to anything other than its own background. However, you can easily add borders to them and customize their painting in other ways.
KeyListener
This interface is used to listen for keyboard events and provides the following methods:
Public interface KeyListener extends EventListener {/ * call * / public void keyTyped (KeyEvent e) when the key is typed; / * call * / public void keyPressed (KeyEvent e) when the key is pressed; / * call public void keyReleased (KeyEvent e) when the key is released;}
I used keyPressed and keyReleased in this article.
KeyPressed is mainly used to complete the keyboard operation of the movement, and shooting functions. Whenever we have a keystroke operation, we will be monitored by it and produce corresponding events.
There is a pit here: if you judge the keys here one by one, such as if (left button) else if (design), then when you press both keys at the same time, they will be invalidated.
The solution is as follows:
Define a global Set to store events for each keystroke.
Static Set keys = new HashSet ()
When pressing the key, add:
/ * description: keyboard press unreleased * * @ param e * @ return: void * @ author: weirx * @ time: 14:02 * / @ SneakyThrows@Overridepublic void keyPressed (KeyEvent e) on 2022-1-10 {/ / add button press event to set InitProcessor.keys.add (e.getKeyCode ()); / / iterate through the execution button event multiKeys ();}
In executing a traversal method, constantly performing business logic judgments:
Public void multiKeys () {for (Integer key: InitProcessor.keys) {int keyCode = key / / Spacebar if (keyCode = = KeyEvent.VK_SPACE) {} / left else if (keyCode = = KeyEvent.VK_LEFT) {} / / shooting else if (keyCode = = KeyEvent.VK_S) {}
Then when we release the button, release the key of the set in the following way:
/ * description: release button * @ param e * @ return: void * @ author: weirx * @ time: 15:39 * / @ Overridepublic void keyReleased (KeyEvent e) {/ / button release on 2022-1-11, the event will be removed from InitProcessor.keys.remove (e.getKeyCode ());}
Action listener [ActionListener]
This is the engine in which the whole picture can be presented dynamically. We use timers to monitor action events and make logical judgments on data.
The interfaces are as follows:
Public interface ActionListener extends EventListener {/ * when the event occurs * / public void actionPerformed (ActionEvent e);}
Timer definition:
/ * * timer * / private Timer timer = new Timer (15, this)
The code of the API actionPerformed is shown as follows:
/ * description: timer callback position * @ param e * @ return: void * @ author: weirx * @ time: 15:38 * / @ Override public void actionPerformed (ActionEvent e) {/ / current year if (InitProcessor.LEFT.equals (InitProcessor.moveDirection)) {/ / is hit Reversing if (InitProcessor.hit) {InitProcessor.moveDirection = InitProcessor.RIGHT } / / decide to move to the boundary if (InitProcessor.nian_x > 30) {InitProcessor.nian_x-= InitProcessor.moveSpeed * 2;} else {InitProcessor.moveDirection = InitProcessor.RIGHT; InitProcessor.nian_x + = InitProcessor.moveSpeed * 2 }} else {/ / is hit, change direction if (InitProcessor.hit) {InitProcessor.moveDirection = InitProcessor.LEFT } / / how the animal moves to the left in the current year / / judge the movement to the border if (InitProcessor.nian_x < 640) {InitProcessor.nian_x + = InitProcessor.moveSpeed * 2;} else {InitProcessor.moveDirection = InitProcessor.LEFT; InitProcessor.nian_x-= InitProcessor.moveSpeed * 2 }} / / set the display time of fireworks. The timer is refreshed 50 times, which is inaccurate, but at least you can clearly feel the existence of if (InitProcessor.hitShow = = 50) {InitProcessor.hit = false; InitProcessor.hitShow = 0;} / / increase the number of displays InitProcessor.hitShow++. / / refresh page repaint (); timer.start (); / / start timer}
So far, the keystroke event and timer event have been completed, and it can be said that all the logical judgments are implemented above. Let's focus on how the image appears.
Basic image display [JComponent]
We don't seem to see this component before, so where is it? Look at the following class diagram:
As shown above, GamePanel inherits JPanel, while JPanel inherits JComponent. JComponent has a method that we need to rewrite, which is how we implement image display, which provides the ability to draw UI. We can rewrite it. Part of the code is as follows:
/ * description: drawing page * * @ param g * @ return: void * @ author: weirx * @ time: 13:40 * / @ Overrideprotected void paintComponent (Graphics g) {/ / screen removal effect super.paintComponent (g) on 2022-1-10; / / if (! InitProcessor.isStared) {background.paintIcon (this, gjord0); InitProcessor.nian.paintIcon (this, g, 250,130) InitProcessor.tiger.paintIcon (this, g, 220,470); / / draw the home page / / set the game text g.setColor (Color.ORANGE); g.setFont (new Font ("Young Circle", Font.BOLD, 50); g.drawString ("Battle of the year", 325,550); / / set start prompt g.setColor (Color.GREEN) G.setFont (new Font ("Young Circle", Font.BOLD, 30); g.drawString ("Press the [space] key to start the game", 300,620); g.drawString ("press the [←] [→] key to move", 300,660); g.drawString ("press the [S] key to fire shells", 300700) } else if (isGameOver) {/ / output gameover InitProcessor.gameOver.paintIcon (this, g, 10,10); / / set start prompt g.setColor (Color.GREEN); g.setFont (new Font ("Young Circle", Font.BOLD, 20); g.drawString ("Press the space to start the game again", 340,600);}}
The key point is to use Graphics to draw text, background, color, and so on.
The picture needs to be painted using the ImageIcon class. I encapsulated the initialization part of ImageIcon, so it is not shown above. The general use is as follows:
ImageIcon nian = new ImageIcon (PATH_PREFIX + "nian.png"); nian.paintIcon (this, g, 250,130); 2.4Blood of the game [InitProcessor]
Why is it blood? Because this class is an initialization class implemented by myself, the content is to concatenate the key points of the whole game, like the blood of the body.
By writing this game, I found that the most critical point is [state], it can be said that all the page animation display is in a state, whether it is the movement of bullets, the movement of Nien Beast, including the switching of fireworks pictures, as well as the coordinates of various pictures and so on.
So I specifically abstracted this class for initialization of various states, and some of the code is as follows:
/ * * @ description: initialize processor * @ author:weirx * @ date:2022/1/11 10:15 * @ version:3.0 * / public class InitProcessor {/ * whether the game starts. Default is false * / public static Boolean isStared = false; / * whether the game is paused, and default is false * / public static Boolean isStopped = false / * Abscissa of fireworks * / public static int youWillBeKill_x = 0; / * ordinate of fireworks * / public static int youWillBeKill_y = nian_y + 200; / * * display shells * / public static Boolean showYouWillBeKill = false; public static Boolean isGameOver = false / * Image path * / public final static String PATH_PREFIX = "src/main/java/com/wjbgn/nianfight/pic/"; public static ImageIcon nian = new ImageIcon (PATH_PREFIX + "nian.png"); public static ImageIcon tiger = new ImageIcon (PATH_PREFIX + "tiger\ tiger2.png"); public static ImageIcon heart = new ImageIcon (PATH_PREFIX + "blood\ heart.png") / * fireworks container * / public static List fireworksDOS = initFireworks (); / * * flower container * / public static List flowersDOS = initFlowers (); / * * initialize firecrackers * / private static List initFlowers () {List list = new ArrayList (); list.add (new FlowersDO (1, PATH_PREFIX + "flowers\ flower1.png")) List.add (new FlowersDO (2, PATH_PREFIX + "fireworks\ flower2.png"); list.add (new FlowersDO (3, PATH_PREFIX + "fireworks\ flower3.png")); list.add (new FlowersDO (4, PATH_PREFIX + "fireworks\ flower4.png"); list.add (new FlowersDO (5, PATH_PREFIX + "fireworks\ flower5.png")) List.add (new FlowersDO (6, PATH_PREFIX + "fireworks\ flower6.png"); list.add (new FlowersDO (7, PATH_PREFIX + "fireworks\ flower7.png")); list.add (new FlowersDO (8, PATH_PREFIX + "fireworks\ flower8.png"); list.add (new FlowersDO (9, PATH_PREFIX + "fireworks\ flower9.png")) List.add (new FlowersDO (10, PATH_PREFIX + "fireworks\ flower10.png"); list.add (new FlowersDO (11, PATH_PREFIX + "fireworks\ flower11.png")); return list } / * description: initialize fireworks species * * @ return: void * @ author: weirx * @ time: 10:58 * / public static List initFireworks () on 2022-1-11 {List list = new ArrayList (); list.add (new FireworksDO (1, PATH_PREFIX + "fireworks\ fireworks1.png")) List.add (new FireworksDO (2, PATH_PREFIX + "fireworks\ fireworks2.png"); list.add (new FireworksDO (3, PATH_PREFIX + "fireworks\ fireworks3.png")); list.add (new FireworksDO (4, PATH_PREFIX + "fireworks\ fireworks4.png"); list.add (new FireworksDO (5, PATH_PREFIX + "fireworks\ fireworks5.png")) List.add (new FireworksDO (6, PATH_PREFIX + "fireworks\ fireworks6.png"); list.add (new FireworksDO (7, PATH_PREFIX + "fireworks\ fireworks7.png")); list.add (new FireworksDO (8, PATH_PREFIX + "fireworks\ fireworks8.png"); list.add (new FireworksDO (9, PATH_PREFIX + "fireworks\ fireworks9.png")) List.add (new FireworksDO (10, PATH_PREFIX + "fireworks\ fireworks10.png"); list.add (new FireworksDO (11, PATH_PREFIX + "fireworks\ fireworks11.png")); return list } / * description: initialization method, which is used to restart the game * * @ return: void * @ author: weirx * @ time: 10:39 * / public static void init on 2022-1-11 () {isStared = false; isStopped = false; attack = false; nian_x = 325; nian_y = 50 Tiger_x = 325; tiger_y = 660; bullet_x = tiger_x + 20; bullet_y = tiger_y-20; moveSpeed = 1; moveDirection = LEFT; hit = false; hitCount = 0; hitShow = 0; nianBlood = 10; success = false; keys = new HashSet (); fireworks_x = 0 Fireworks_y = nian_y + 200; showFireworks = false; currentFireworks = null; takeFireworks = false; currentFlowers = null; youWillBeKill = 0; youWillBeKill_x = 0; youWillBeKill_y = nian_y + 200; showYouWillBeKill = false; isGameOver = false;}} 2.5 entity classes [FireworksDO] [FlowersDO]
These are two entity classes, defined firecrackers and fireworks respectively, for initialization. The code is as follows:
Import javax.swing.*;import static com.wjbgn.nianfight.nianshou.InitProcessor.PATH_PREFIX;/** * @ description: flower container * @ author:weirx * @ date:2022/1/11 11:05 * @ version:3.0 * / public class FlowersDO {private Integer id; private String path; private ImageIcon flower; public ImageIcon getFlower () {return flower;} public void setFlower (ImageIcon flower) {this.flower = flower } public Integer getId () {return id;} public void setId (Integer id) {this.id = id;} public String getPath () {return path;} public void setPath (String path) {this.path = path;} public FlowersDO (Integer id, String path) {this.id = id; this.path = path This.flower = new ImageIcon (PATH_PREFIX + "flowers\ flower" + id + ".png");}} / * * @ description: fireworks entity class * @ author:weirx * @ date:2022/1/11 11:01 * @ version:3.0 * / public class FireworksDO {/ * id * / private Integer id; / * Image path * / private String path Public ImageIcon getFirework () {return firework;} public void setFirework (ImageIcon firework) {this.firework = firework;} private ImageIcon firework; public Integer getId () {return id;} public void setId (Integer id) {this.id = id;} public String getPath () {return path;} public void setPath (String path) {this.path = path } public FireworksDO (Integer id, String path) {this.id = id; this.path = path; this.firework = new ImageIcon (PATH_PREFIX + "fireworks\ fireworks" + id + ".png")
A large number of picture materials are used in the game. I found two good websites on the Internet, one is the png picture website, which is free, and the other is free to cut pictures, which is easy to use and share with you.
Free png pictures website: www.cleanpng.com/
Free screenshot URL (simple version of direct Wechat follow): www.uupoop.com/
The materials I use are all in the pic directory of the project:
III. Summary
I have been writing java for several years, but I have never developed code using the content under the javax.swing and java.awt packages. In the current environment with user experience as the premise, the comprehensive coding experience and game running experience is really not very friendly and not in line with the environmental background. But it is also a good learning process.
Problem summary
At present, there are still some bug in the whole game. Please find out and debug it later if you have time. Record it here:
Bullets are sometimes not fired directly in front of the tiger and deviate from the actual coordinates: I speculate that the cause of this problem comes from the synchronization of shared variables between threads. The initial Abscissa of the bullet depends on the current Abscissa of the tiger, which is not well synchronized.
The problem of stutter caused by keystroke switching and two buttons at the same time: the solution of pressing two keys at the same time may not be the optimal solution, and it needs to be optimized later.
The monster drops bombs and firecrackers have a deviation with the movement of the year: the initial Abscissa of the bomb and firecracker is the current Abscissa of the year, and a variable is required to record the position of the current year, which is used as the initial Abscissa of the bomb and firecracker.
The above is the editor for you to share the Java how to achieve the Nian Beast Battle Game, if you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.