A case of tank wars based on Java

Source: Internet
Author: User
Tags explode getcolor

Declaration of originality

The source of this post is http://blog.csdn.net/zhujunxxxxx/article/details/40460931 if reproduced please indicate the source. This article author original, email [email protected], if you have any questions, please contact the author

PrefaceHaven't touched Java for a long time, today suddenly found out the sophomore period wrote a tank war game source code, and then run a bit, unexpectedly still so cordial, suddenly thought of the former sophomore time of the point of time. OK, no more nonsense, give a picture first.
This is the entire interface of the game, the interface is full of Java painting, not very good-looking. If you want to lot better to make a picture version of the principle of the game is to start creating instances of N enemies, multithreading in the interface to move (moving using the rewrite paint function to achieve), and then randomly move and fire bullets. There is the use of simple collision detection method to achieve the bullet hit others and encountered obstacles double buffering technology, eliminating strobe
Tank class is the main object of this game, can be divided into three kinds of tanks, one is their own tanks, one is a common tank, and the other is the boss tank (blood Damage is large), but is a class to achieve
Import java.awt.*;import java.awt.event.*;import java.util.*;p ublic class Tank {public static final int xspeed = 5;public static final int yspeed = 5;public static final int WIDTH = 30;public static final int HEIGHT = 30; tankclient tc;private int x, y;//tank coordinates, i.e. position private int oldx, oldy;//used to hold the coordinates of the previous step, the private Boolean bl=false to adjust the direction when hitting the wall, bu= False, Br=false, BD = false;//direction of the flag variable enum Direction {L, LU, U, RU, R, RD, D, LD, stop};//direction enumeration private Direction dir = Dire Ction. stop;//our tank, initial direction private Direction Ptdir = direction.d;//enemy tank initial direction, down private int step = R.nextint (+) + 3;private Boolean is Super=false;public Boolean issuper () {return issuper;} public void Setsuper (Boolean issuper) {this.issuper = Issuper;} private static Random R = new Random ()///random number generator Private Boolean good;//distinguished good or bad variable private boolean boss;public boolean Isboss () { return boss;} public Boolean Isgood () {return good;} public void Setgood (Boolean good) {This.good = good;} Private Bloodbar bb=new Bloodbar ();//blood bar//tank health variable private int LIFE=100;PUBlic int Getlife () {return life;} public void Setlife (int.) {this.life = life;} Tank Life and Death Variable private Boolean live=true;public boolean islive () {return live;} public void Setlive (Boolean live) {this.live = live;} Tank construction method Public Tank (int x, int y,boolean good) {this.x = X;this.y = Y;THIS.OLDX = X;this.oldy = Y;this.good=good;} public Tank (int x, int. Y,boolean good,direction dir, tankclient tc) {This (x, y,good); this.dir=dir;this.tc = TC;} public Tank (int x, int. Y,boolean Good,boolean boss, Direction dir, tankclient tc) {This (x, Y,good); this.dir=dir;this.boss= BOSS;THIS.TC = TC;} The method of drawing a tank public void draw (Graphics g) {if (!live) Return;//tank dead is not redrawn color c = g.getcolor (); if (good)//Set color by good or bad { G.setcolor (Color.cyan);} else if (boss) {G.setcolor (color.red);} else {g.setcolor (color.blue);} G.filloval (x, Y, WIDTH, HEIGHT), G.setcolor (c), if (good) bb.draw (g);//Our tank has a blood bar if (boss) Bb.draw (g);//boss has a blood bar switch ( Ptdir) {//through azimuth, draw the barrel position case L:g.drawline (x + tank.width/2, y + tank.height/2, x, y + tank.height/2); Break;case lu:g.DrawLine (x + tank.width/2, y + tank.height/2, x, y), Break;case u:g.drawline (x + tank.width/2, y + tank.height/2, x + Tank. WIDTH/2, y); break;case ru:g.drawline (x + tank.width/2, y + tank.height/2, x + tank.width, y); break;case R:g.drawLine (x + T Ank. WIDTH/2, y + tank.height/2, x + tank.width, y + tank.height/2); break;case rd:g.drawline (x + tank.width/2, y + Tank.HEIGHT/ 2, x + tank.width, y + tank.height); break;case d:g.drawline (x + tank.width/2, y + tank.height/2, x + tank.width/2, y + Tan) k.height); Break;case ld:g.drawline (x + tank.width/2, y + tank.height/2, x, y + tank.height); break;} Move ();//redraw the movement of the}//tank when redrawing, moving void Move () {this.oldx = X;this.oldy = Y;switch (dir) {case l:x-= xspeed; Break;case lu:x = Xspeed;y = yspeed;break;case U:y-= yspeed;break;case ru:x + = xspeed;y-yspeed;break;case R:x + = XSP Eed;break;case rd:x + = xspeed;y + yspeed;break;case d:y + yspeed;break;case ld:x-= xspeed;y + = YSPEED;break;case STOP:b Reak;} if (this.dir! = direction.stop) {//barrel position is fixedPosition, and the direction of action consistent this.ptdir = This.dir;} Determine if the tank is out of bounds, then stop if the boundary is encountered if (x < 0) x = 0;if (y < x) y = 30;if (× + tank.width > tankclient.game_width) x = Tankclient.gam E_width-tank.width;if (y + tank.height > tankclient.game_height) y = tankclient.game_height-tank.height;//villain tank's random movement , and the time the bullet was sent if (!good&&!boss) {direction[] dirs = Direction.values (); if (step = = 0) {step = R.nextint (+) + 3;int rn = R.nextint (dirs.length);d ir = Dirs[rn];} Step--;if (R.nextint (>) This.fire ();}  Boss Tank Attack Method if (!good&&boss) {direction[] dirs = Direction.values (); if (step = = 0) {step = R.nextint (+) + 3;int rn = R.nextint (dirs.length);d ir = Dirs[rn];} Step--;if (R.nextint (>) This.fire ();}} Keys are set when the key is pressed to determine the orientation position of public void keypressed (KeyEvent e) {int key = E.getkeycode (); switch (key) {case Keyevent.vk_caps_ LOCK:this.setSuper (!this.issuper ()); case KeyEvent.VK_F2:if (!this.live) {this.live = True;this.life = 100;} Case KeyEvent.VK_CONTROL:fire (); Break;case KeyEvent.VK_LEFT:bL = True;break;case KeyEvent.VK_UP:bU = true;break;case KeyEvent.VK_RIGHT:bR = true;break;case KeyEvent.VK_DOWN:bD = true;break;} Locatedirection ();//The direction of the direction}//tank is determined after each keystroke, by the flag set after the key to determine void Locatedirection () {if (BL &&!bu &&!br &&!bd) dir = Direction.l;else if (BL && bU &&!br &&!bd) dir = Direction.lu;else if (!BL & amp;& BU &&!br &&!bd) dir = Direction.u;else if (!bl && bU && bR &&!bd) dir = Direction.ru;else if (!bl &&!bu && bR &&!bd) dir = Direction.r;else if (!bl &&!bu &  & BR && bd) dir = Direction.rd;else if (!bl &&!bu &&!br && bd) dir = Direction.d;else if (BL &&!bu &&!br && bD) dir = Direction.ld;else if (!bl &&!bu &&!br &&amp ;!bd) dir = direction.stop;} When the key is lifted up, the keys are restored, and the direction is judged public void keyreleased (KeyEvent e) {int key = E.getkeycode (); switch (key) {case Keyevent.vk_ LEFT:BL = FalSe;break;case KeyEvent.VK_UP:bU = false;break;case KeyEvent.VK_RIGHT:bR = False;break;case KeyEvent.VK_DOWN:bD = false; Break;case KeyEvent.VK_A:superFire (); break;} Locatedirection ();} Send a bullet to the missiles to add bullets public missile fire () {if (!live) return null;int x = this.x + TANK.WIDTH/2-missile.width/2;in T y = this.y + TANK.HEIGHT/2-MISSILE.HEIGHT/2; Missile m;if (Good&&this.issuper ())//Judging is not a super cannonball {m = new missile (x, Y,good, ptdir,this.tc,true);} else {m = new missile (x, Y,good, ptdir,this.tc);} Tc.missiles.add (m); return m;} Superfire How to send bullets to each direction public missile fire (Direction Dir) {if (!live) return null;int x = this.x + TANK.WIDTH/2-missile.wi Dth/2;int y = this.y + TANK.HEIGHT/2-MISSILE.HEIGHT/2; Missile m = new missile (x, Y,good, DIR,THIS.TC); Tc.missiles.add (m); return m;} private void Superfire () {direction[] dirs = Direction.values (); for (int. i=0;i<8;i++) {//tc.missiles.add (Fire (dirs[i ]); Fire (Dirs[i]);}} The public Rectangle GetRect () {return new Rectangle (x, Y, WIDTH, HEIGHT);} The method of stopping when colliding with tanks and walls private void stay () {x = Oldx;y = OldY;} The method of judging if the tank collided with the wall public boolean collideswithwall (Wall W) {if (this.live && this.getrect (). intersects (W.getrect ( )) {This.stay (); return true;} return false;} A method to determine if a tank collided with a tank public boolean collideswithtanks (java.util.list<tank> tanks) {for (int i=0; i<tanks.size (); I + +) {Tank T = tanks.get (i); if (this = t) {if (this.live && t.islive () && This.getrect (). intersects (T.getre CT ())) {This.stay (); T.stay (); return true;}}} return false;} The inner class of the blood bar is private classes Bloodbar {public void Draw (Graphics g) {Color c = g.getcolor (); G.setcolor (color.orange); g.drawrect (x, y-10, width, ten); int w = width * life/100; g.fillrect (x, Y-10, W, ten); G.setcolor (c);}} Methods of eating blood clots public boolean eat (Blood b) {if (this.live && b.islive () && This.getrect (). intersects (B.getrect ()) {This.life = 100;b.setlive (false); return true;} return false;}}

There are a lot of operating methods inside the tank, and there is a blood bar.
Bullet class is divided into enemy bullets and our bullets, with moving speed and other properties, with collision detection and other functions.
Import Java.awt.*;import Java.util.list;public class missile {public static final int xspeed = 10;//bullet speed variable public static F inal int yspeed = 10;public static int WIDTH = 10;//bullet size public static int HEIGHT = 10;int x, y;private tankclient TC; Tank.direction dir;//Directional Variable Private Boolean issuper;private boolean live = true;//Bullet's life and Death Variable public boolean islive () {return Liv e;} Private Boolean good;//The good or bad of a tank variable public boolean Isgood () {return good;} The two construction methods of missile public missile (int x, int y, tank.direction dir) {this.x = X;this.y = Y;this.dir = dir;} Public missile (int x, int. Y,boolean Good, tank.direction dir, tankclient tc) {This (x, Y, dir); this.tc = Tc;this.good=good; }public Missile (int x, int y,boolean good, tank.direction dir, tankclient Tc,boolean issuper) {This (x, Y, dir); this.tc = t C;this.issuper=issuper;this.good=good;} Method of drawing bullets public void Draw (Graphics g) {if (!live) {tc.missiles.remove (this); return;} Color C = G.getcolor (), if (good&&issuper)//is the super Shell becomes larger {g.setcolor (color.yellow); G.filloval (X-5, Y-5, 20, 20);} else if (good&&!issuper) {g.setcolor (Color.yellow); G.filloval (x, Y, WIDTH, HEIGHT);} else {g.setcolor (color.red); G.filloval (x, Y, WIDTH, HEIGHT);} G.setcolor (c); move ();//When you draw a bullet, you move the}//bullet, and the direction of the tank is related to the private void move () {switch (dir) {//through the azimuth to determine the speed case l:x-= xspeed; Break;case lu:x = Xspeed;y = yspeed;break;case U:y-= yspeed;break;case ru:x + = xspeed;y-yspeed;break;case R:x + = XSP Eed;break;case rd:x + = xspeed;y + yspeed;break;case d:y + yspeed;break;case ld:x-= xspeed;y + = YSPEED;break;case STOP:b Reak;} The bullet crosses the border and dies. if (x < 0 | | Y < 0 | | x > Tankclient.game_width | | y > Tankclient.game_height) {live = False;tc.missi Les.remove (this);}} Public Rectangle GetRect () {return new Rectangle (x, Y, WIDTH, HEIGHT);} Bullets collide with bullets and bullets are good or bad public boolean hitmissile (missile m) {if (this.live && this.getrect (). intersects (M.getrect ()) && m.islive () && This.good!=m.isgood ()) {This.live=false;m.live=false;return true;} return false;} public Boolean HitmisSiles (list<missile> missiles) {for (int i=0; i<missiles.size (); i++) {if (Hitmissile (Missiles.get (i))) {// Called the Hitmissile Method Missiles.remove (Missiles.get (i)); return true;}} return false;} public boolean Hittank (Tank t) {if (this.live && this.getrect (). intersects (T.getrect ()) && t.islive () & amp;& This.good!=t.isgood ()) {if (T.isgood ())//self-struck minus blood {t.setlife (T.getlife () -20); if (T.getlife () <=0) T.setlive (false);} else if (T.isboss ())//boss is hit {if (This.issuper)//hit by super Shell {T.setlife (T.getlife () -33); if (T.getlife () <=0) t.setlive (false);} else {T.setlife (T.getlife ()-5), if (T.getlife () <=0) t.setlive (false);}} else//bad person directly dead t.setlive (false);//t.setlive (false); this.live = false; Explode e = new Explode (x, y, TC); Tc.explodes.add (e); return true;} return false;} A bullet collided with a tank, and the bullet points good or bad (the way to hit the enemy tank) public boolean hittanks (list<tank> tanks) {for (int i=0; i<tanks.size (); i++) {if ( Hittank (Tanks.get (i))) {//called the Hittank method Tanks.remove (Tanks.get (i)); return true;}} return false;} The way the bullet collided with the wall public BooleaN Hitwall (Wall W) {if (this.live && this.getrect (). intersects (W.getrect ())) {this.live = False;return true;} return false;}}

Main program class main class is to implement the function of the display interface, the object in memory to draw out, to achieve the effect of animation.
Import Java.awt.*;import java.awt.event.*;import Java.util.list;import Java.util.arraylist;import Org.omg.corba.public_member;public class Tankclient extends frame{public static int game_width = 800;public static int GA Me_height = 600; Tank Mytank = new Tank (300,true,tank.direction.stop, this); Tank Bosstank = new Tank (50,false,true,tank.direction.d,this); List<missile> missiles=new arraylist<missile> ()///loading container list<explode> explodes = new ArrayList< Explode> ();//explosive container list<tank> tanks = new arraylist<tank> ();//container for enemy tanks Blood B = new Blood ();//Instantiate a clot// Instantiate two walls Wall w1=new Wall (+, 20,150, this); Wall w2=new Wall (max, N, 20,150, this);//double buffering technology, eliminate strobe image offscreenimage = null;public void Update (Graphics g) {if (OFFSCR Eenimage = = null) {Offscreenimage = This.createimage (Game_width, game_height);} Graphics Goffscreen = Offscreenimage.getgraphics (); Color C = Goffscreen.getcolor (); Goffscreen.setcolor (Color.gray); goffscreen.fillrect (0, 0, Game_width, Game_height); Goffscreen.setcolor (c);p aint (goffscreen); G.drawimage (offscreenimage, 0, 0, null);} public void Paint (Graphics g)//will automatically call this method {g.DrawString ("Tanks count:" + tanks.size (), ten, +); g.DrawString ("Explodes cou NT: "+ explodes.size (), g.DrawString (" Missiles count: "+ missiles.size (), ten, +); g.DrawString (" Tank Life: "+ Mytank.getlife (), (tanks.size () <= 0) {for (int i=0; i<5; i++) {tanks.add (new Tank (+ 40* (i+1), False , TANK.DIRECTION.D, this));}} Draw all the bullets inside the container for (int i=0;i<missiles.size (); i++) {missile m=missiles.get (i); m.hittanks (tanks);// The method of adding bullets to the tank M.hittank (Mytank); M.hittank (Bosstank); M.hitwall (W1); M.hitwall (W2); M.hitmissiles (missiles);// Call the Bullet method M.draw (g);} Draw all the explosions inside the container for (int i=0; i<explodes.size (); i++) {Explode e = explodes.get (i); E.draw (g);//e.explodehittanks ( tanks);//e.explodehittank (Bosstank);} Draw all the tanks inside the container for (int i=0; i<tanks.size (); i++) {Tank t = tanks.get (i); T.collideswithwall (W1); T.collideswithwall ( W2); T.collideswithtanKS (tanks); T.draw (g);} B.draw (g);//blood clots draw out bosstank.draw (g); Bosstank.collideswithwall (W1); Bosstank.collideswithwall (W2); Bosstank.collideswithtanks (tanks);//Our tank is drawn and added method Mytank.draw (g); Mytank.eat (b); Mytank.collideswithwall (W1); Mytank.collideswithwall (W2);//Draw a wall to W1.draw (g); W2.draw (g);} Method of initializing the game window public void Lauchframe () {//Initialize tank, add into container for (int i=0;i<10;i++) {Tanks.add (new Tank (50+40*), i+1 , tank.direction.d,this));} This.setlocation (+); this.setsize (game_width,game_height); This.settitle ("zz Tankwar"); This.addwindowlistener (New Windowadapter () {public void windowclosing (WindowEvent e) {system.exit (0);}}); This.setbackground (Color.green); this.setresizable (false); This.addkeylistener (new Keymonitor ()); This.setVisible ( true); new Thread (New Paintthread ()). Start (); Private class Paintthread implements Runnable{public void Run () {while (true) {repaint (); Try{thread.sleep (50);} catch (Interruptedexception e) {e.printstacktrace ();}}}} Private class Keymonitor extends Keyadapter {//keyboard listening public void Keyreleased (KeyEvent e) {mytank.keyreleased (e);} public void keypressed (KeyEvent e) {mytank.keypressed (e);}} public static void Main (string[] args) {tankclient t=new tankclient (); T.lauchframe ();}}


Summary In fact, Tank war this game is very simple, as long as you understand some basic data structure and collision detection, as well as redraw the method can create their own tank war, to their childhood a gorgeous metamorphosis.

A case of tank wars based on Java

Contact Us

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

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

A Free Trial That Lets You Build Big!

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

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

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