Minesweeper (Java edition)

Source: Internet
Author: User
Tags gety stub

First of all, let's talk about mine rules.

1. The number indicates that there are several mines in the eight directions of this digit location adjacency

2. Right-click once to mark this location as a mine (plug in a small flag), and then click once to mark?

3. Left mouse button click a location

If the number in this position is 1-8, the display

If the number is 0 (that is, blank) automatically extends eight directions until the number (1-8) is met

If it's a mine, the game fails.

4. When all the numbers on the map are clicked, the game wins.

The first is the Mineclient class, initializing the mines, having the refresh thread, drawing, etc.

Package Com.xynu.mine;import Java.awt.color;import java.awt.font;import java.awt.graphics;import java.awt.Image; Import Java.awt.toolkit;import Java.awt.event.actionevent;import Java.awt.event.actionlistener;import Java.util.arraylist;import Javax.swing.jframe;import Javax.swing.jmenu;import Javax.swing.JMenuBar;import Javax.swing.jmenuitem;import Javax.swing.jpanel;import Javax.swing.jseparator;public class MineClient extends JFrame {/** * */private static final long Serialversionuid = 1l;//screen width private int screenwidth;//screen height private int screenheight;//diagram Slice width private int imgwidth = 20;//picture height private int imgheight = 20;//map line number private int rowNum = 0;//map column number private int colnum = 0; Total number of mines private int minenum=99;//timer private int timer=0;//game time private int time=0;//number of non-minesweeper private int restmine;// Not the number of thunder. private int notmine;private Mypanel mypanel;//current game state private String gamestate = "start";//First Click Private Boolean Firstclick = true;private JMenuBar menubar;private jmenu menu;private jmenuitem lowlevel;priVate jmenuitem midlevel;private jmenuitem heightlevel;private jmenuitem restart;private Toolkit tk= Toolkit.getdefaulttoolkit ();p rivate Image icon=tk.getimage ("image/icon.jpg");//Map Collection Private arraylist<bomb> Bomblist = new arraylist<bomb> ();p ublic mineclient (int screenwidth,int screenheight,int mineNum) { this.screenheight=screenheight;this.screenwidth=screenwidth;this.minenum=minenum;//Initialize the menu bar initmenu (); SetTitle (" Seticonimage (icon); SetSize (ScreenWidth, screenheight); Setlocationrelativeto (null); setdefaultcloseoperation (jframe.exit_on_close); setvisible (true); Initlist (); mypanel = new Mypanel (); Mypanel.setbackground (color.black); add (mypanel);//mouse event Mypanel.addmouselistener (new Mymouselistener (this)); New Updatethread (). Start (); /* * Initialize the menu bar */private void Initmenu () {menu=new jmenu ("parameter setting"), Menubar=new JMenuBar (), Lowlevel=new JMenuItem ("Primary (10 lei)") Midlevel=new JMenuItem ("intermediate (44 lei)"), Heightlevel=new JMenuItem ("Advanced (99 Lei)"), Restart=new jmenuitem ("restart"); Lowlevel.addactionlistener (NewActionListener () {public void actionperformed (ActionEvent e) {//TODO auto-generated method Stubdispose (); new mineclient (225,305,10);}}); Midlevel.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {//TODO auto-generated Method Stubdispose (); new Mineclient (380,460,44);}}); Heightlevel.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {//TODO auto-generated Method Stubdispose (); new Mineclient (660,460,99);}}); Restart.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {//TODO auto-generated Method Stubdispose (); new Mineclient (Screenwidth,screenheight,minenum);}}); Menu.add (restart); Menu.add (new Jseparator ()); Menu.add (lowlevel); Menu.add (midlevel); Menu.add (Heightlevel); Menubar.add (menu); Setjmenubar (MenuBar);} public Boolean Isfirstclick () {return firstclick;} public void Setfirstclick (Boolean firstclick) {This.firstclick = Firstclick;} public int getimgwidth () {return imgwidth;} public void SetimgwiDTH (int imgwidth) {this.imgwidth = ImgWidth;} public int getimgheight () {return imgheight;} public void setimgheight (int imgheight) {this.imgheight = ImgHeight;} Public Mypanel Getmypanel () {return mypanel;} public void Setmypanel (Mypanel mypanel) {this.mypanel = Mypanel;} Public String Getgamestate () {return gamestate;} public void Setgamestate (String gamestate) {this.gamestate = gamestate;} Public arraylist<bomb> getbomblist () {return bomblist;} public int Getrownum () {return rowNum;} public void Setrownum (int rowNum) {this.rownum = RowNum;} public int Getcolnum () {return colnum;} public void Setcolnum (int colnum) {this.colnum = Colnum;} public int Getminenum () {return minenum;} Create map private void Initlist () {for (int i = imgwidth; I < This.getwidth ()-2 * imgwidth; i + = ImgWidth) {for (int j = ImgWidth; J < This.getheight ()-6 * imgwidth; J + = imgheight) {rowNum = rowNum > i/imgwidth? rownum:i/imgwidth;colnum = colnum > j/imgwidth? colnum:j /imgwidth; Bomb Bomb =New Bomb (I, J, K, this); Bomblist.add (Bomb);}} public static void Main (string[] args) {new mineclient (225,305,10);} Custom Panelpublic class Mypanel extends JPanel {/** * */private static final long serialversionuid = 1l;public void Paint ( Graphics g) {super.paintcomponent (g); restmine=minenum;notmine=0;//Draw mine number for (Bomb bomb:bomblist) {Bomb.draw (g); if ( Bomb.getwhat () ==11) restmine--;if (Bomb.getwhat () >=0&&bomb.getwhat () <=8) notMine++;} Game Failed if (Gamestate.equals ("Lose")) {for (Bomb bomb:bomblist) {if (bomb.gethide () = = 9) {bomb.setwhat (Bomb.gethide ());} }font font = new Font ("Microsoft Jas", Font.Bold), G.setfont (font), G.setcolor (new Color (255, 0, 255)), g.drawstring ("GAME over!! ", This.getwidth ()/2-80,this.getheight ()/2);} Draw current game time and number of mines drawtimeandminenum (g);//Win the game if (!gamestate.equals ("Lose") &¬mine+minenum==colnum*rownum ) {gamestate= "Win"; Toolkit Tk=toolkit.getdefaulttoolkit (); Image img=tk.getimage ("image/win.jpg"); G.drawimage (img, 0, 0, This.getwidth ( ), This.getheiGht (), this); Font font1 = new Font ("Chinese Xingkai", Font.Bold, +), G.setfont (font1); G.setcolor (New Color (248,)); g.DrawString ("You WIN!!! ", This.getwidth ()/2-100, 30);}} private void Drawtimeandminenum (Graphics g) {font font = new Font ("Microsoft Jas", Font.Bold), G.setfont (font); G.setcolor ( Color.orange); g.DrawString ("Elapsed:" +time+ "seconds", 0, This.getheight () -20); g.DrawString ("Not Mine:" +restmine+ "," This.getwidth () -100, This.getheight ()-20);}} The screen refreshes every 100ms at the public class Updatethread extends Thread {public void run () {while (true) {repaint (); if (!firstclick) { Timer+=100;if (timer==1000) {timer=0;time++;}} try {thread.sleep;} catch (Interruptedexception e) {e.printstacktrace ();}}}}

Then the bomb package class.

Explanation of two variables. 、

What indicates that the current mine (not necessarily mine) is drawn

Hide represents the real content of the current mine (not necessarily a landmine)

Explain two ways

Public Rectangle Getrec () {return new Rectangle (x, Y, W, h);}
Returns the current mine's rectangle, the specific function I will say in the Mymouselistener class

Draw (Graphics g)

The draw method is essentially a panel drawing


Package Com.xynu.mine;import Java.awt.graphics;import Java.awt.image;import java.awt.rectangle;import Java.awt.toolkit;public class Bomb {private int x;private int y;private int what;private int hide = 0;private int w = 19;p rivate int h = 19;private mineclient mc;private Toolkit tk = Toolkit.getdefaulttoolkit ();p rivate Image bomb = Tk.getimage ( "Image/bomb.jpg");p rivate image bomb0 = Tk.getimage ("image/bomb0.jpg");p rivate image zerobomb = Tk.getimage ("image/0. JPG ");p rivate image onebomb = Tk.getimage (" image/1.jpg ");p rivate image twobomb = Tk.getimage (" image/2.jpg ");p rivate Image Threebomb = Tk.getimage ("image/3.jpg");p rivate image fourbomb = Tk.getimage ("image/4.jpg");p rivate Image Fivebomb = Tk.getimage ("image/5.jpg");p rivate image sixbomb = Tk.getimage ("image/6.jpg");p rivate Image Severnbomb = Tk.getimage ( "Image/7.jpg");p rivate image eightbomb = Tk.getimage ("image/8.jpg");p rivate image flag = Tk.getimage ("image/flag.jpg") ;p rivate Image flag2 = tk.getimage ("image/flag2.jpg");p rivate ImAge bg = tk.getimage ("image/s.jpg");p ublic Bomb () {super ();//TODO auto-generated constructor stub}public Bomb (int x, int Y, int what, Mineclient MC) {super (); this.x = X;this.y = Y;this.what = WHAT;THIS.MC = MC;} public int GetX () {return x;} public void SetX (int x) {this.x = x;} public int GetY () {return y;} public void sety (int y) {this.y = y;} public int Getwhat () {return to what;} public void Setwhat (int.) {this.what = what;} public int gethide () {return hide;} public void sethide (int hide) {this.hide = hide;} Draw mine Digital public void Draw (Graphics g) {switch ("what") {case 0:g.drawimage (Zerobomb, X, Y, W, H, MC); Break;case 1:g.drawimage (Onebomb, X, Y, W, H, MC); Break;case 2:g.drawimage (Twobomb, X, Y, W, H, MC); Break;case 3:g.drawimage (Threebomb, X, Y, W, h , MC); Break;case 4:g.drawimage (Fourbomb, X, Y, W, H, MC); Break;case 5:g.drawimage (Fivebomb, X, Y, W, H, MC); Break;case 6:g . DrawImage (Sixbomb, X, Y, W, H, MC), Break;case 7:g.drawimage (Severnbomb, X, Y, W, H, MC); Break;case 8:g.drawimage (Eightbomb, X, Y, W, H, MC); Break;case 9:g.drawimage (Bomb, X, Y, W, H, MC) Break;case 10:g.drawimage (bomb0, X, Y, W, H, MC); break;c  ASE 11:g.drawimage (flag, X, Y, W, H, MC), Break;case 12:g.drawimage (Flag2, X, Y, W, H, MC); Break;case 13:g.drawimage (BG, X, Y, W, H, MC); break;}} Public Rectangle Getrec () {return new Rectangle (x, Y, W, h);}}
Mymouselistener Class (Custom mouse events)

The hardest part is in here.

1. When you start playing the game, make sure the first click is not mine.

2. Click on the number 0 (blank) to automatically extend

Solve:

Before we solve the problem, we must first know which mine the mouse clicked on.

<span style= "White-space:pre" ></span>int x = E.getx (); int y = E.gety (); Rectangle rec = new Rectangle (x, Y, 1, 1); for (Bomb bomb:bomblist) {if (Rec.intersects (Bomb.getrec ())) {//= mouse Rectangle and mine rectangle intersect}}

To explain, we can get the current mouse coordinates by GETX (), Gety () method and then put the width and height of the mouse to think 1 new a Rectangle object

Then the intersects method provided by the API to determine whether two rectangles intersect, that is, the location of the mouse click on the mine

1. To ensure that the first click does not reach the mine, we initialize the map in the mousepressed (MouseEvent e) method, putting the current mouse

The location of the click is set to mine, and the current position is restored by default when the mine is randomly initially completed

2. This should be the hardest thing to do. Of course, if you've learned the search in algorithms, it's so easy.

Both DFS and BFS are OK. From the current position, deep search in its eight directions until it encounters a number ending the current recursion

Feel these two more difficult other have doubts can leave a message together to solve ~ ~

Package Com.xynu.mine;import Java.awt.rectangle;import Java.awt.event.mouseadapter;import Java.awt.event.mouseevent;import Java.util.arraylist;import Java.util.random;public class MyMouseListener extends Mouseadapter {private mineclient mc;private int colnum;private int Rownum;private boolean isfirstclick;private ArrayList <Bomb> bomblist = new arraylist<bomb> (); boolean[] Vis;p ublic Mymouselistener () {super ();//TODO Auto-generated Constructor stub}public Mymouselistener (Mineclient MC) {super (); THIS.MC = Mc;colnum = Mc.getcolnum (); RowNum = Mc.getrownum (); vis = new Boolean[colnum * rownum];bomblist = Mc.getbomblist (); this.isfirstclick= Mc.isfirstclick ();} /* * Mouse Panasonic Event * If Panasonic is the left mouse button then display the current location of the mine * if Panasonic's right mouse button then mark the current position * @see java.awt.event.mouseadapter#mousereleased (java.awt.even t.mouseevent) */public void mousereleased (MouseEvent e) {if (Mc.getgamestate (). Equals ("Lose")) {return;} int x = E.GETX (); int y = E.gety (); Rectangle rec = new Rectangle (x, Y, 1, 1); if (E.getbutton () = = MousEevent.button1) {for (Bomb bomb:bomblist) {if (Rec.intersects (Bomb.getrec ())) {if (bomb.gethide () = = 9) {Mc.setgamestate ("Lose");} else {if (bomb.gethide () = = 0) {increasepoint (Bomblist.indexof (Bomb));} Bomb.setwhat (Bomb.gethide ());}}} if (E.getbutton () = = Mouseevent.button3) {for (Bomb bomb:bomblist) {if (Rec.intersects (Bomb.getrec ())) {if (bomb.getwhat ()!=bomb.gethide ()) {if (Bomb.getwhat () ==13) {bomb.setwhat (11);} else if (Bomb.getwhat () ==11) {bomb.setwhat (12);} else if (Bomb.getwhat () ==12) {bomb.setwhat (13);}}}}}  Automatically expands the area until you meet the number private void Increasepoint (int index) {if (Vis[index]) return;vis[index] = True;boolean Edgeu = False, edged = False;if ((index + 1)% (colnum)! = 0) Edgeu = true;if (index% (colnum)! = 0) edged = true;if (Judgelimit (index-1) &am p;& edged) {Bomb Bomb = Bomblist.get (index-1); Setvis (Bomb, index-1);} if (judgelimit (index + 1) && Edgeu) {Bomb Bomb = bomblist.get (index + 1); Setvis (Bomb, index + 1);} if (Judgelimit (Index-colnum)) {Bomb Bomb = Bomblist.get (Index-colnum); Setvis (bomb, Index-colnum);} if (judgelimit (index + colnum)) {Bomb Bomb = bomblist.get (index + colnum); Setvis (Bomb, index + colnum);} if (Judgelimit (Index-colnum + 1) && Edgeu) {Bomb Bomb = bomblist.get (index-colnum + 1); Setvis (Bomb, Index-co Lnum + 1);} if (Judgelimit (index-colnum-1) && edged) {Bomb Bomb = Bomblist.get (index-colnum-1); Setvis (Bomb, Index-co LNUM-1);} if (judgelimit (index + colnum + 1) && Edgeu) {Bomb Bomb = bomblist.get (index + colnum + 1); Setvis (Bomb, index + CO Lnum + 1);} if (judgelimit (index + colNum-1) && edged) {Bomb Bomb = bomblist.get (index + colNum-1); Setvis (Bomb, index + CO lNum-1);}} Judgment Boundary Private Boolean judgelimit (int i) {if (i >= 0 && i < bomblist.size ()) return True;return false;} Show a location public void Setvis (Bomb Bomb, int index) {if (bomb.getwhat () = = Bomb.gethide () && bomb.getwhat ()! = 0) retur N;if (bomb.gethide () >= 0 && bomb.gethide () <= 8 && BOMB.GEthide ()! = 9) {bomb.setwhat (Bomb.gethide ()); if (bomb.getwhat () = = 0) increasepoint (index);} else {Increasepoint (index) ;}} /* * Press the left mouse button to start initializing the map * @see java.awt.event.mouseadapter#mousepressed (java.awt.event.MouseEvent) */@Overridepublic void mousepressed (MouseEvent e) {if (Mc.getgamestate (). Equals ("Lose")) {return;} if (E.getbutton () = = Mouseevent.button1) {if (Isfirstclick) {Isfirstclick = False;mc.setfirstclick (false); InitBomb (e); Checkbomb ();}}} private void Checkbomb () {for (Bomb bomb:bomblist) {int x = Bomblist.indexof (Bomb);//edgeu edged boundary state value Boolean EDGEU = Fal  SE, edged = false;if ((x + 1)% (colnum)! = 0) Edgeu = true;if (x% (colnum)! = 0) edged = true;if (Bomb.gethide ()! = 9) {if (Judge (X-1) && edged) Bomb.sethide (bomb.gethide () + 1), if (judge (x + 1) && Edgeu) bomb.sethide (Bomb.gethi  De () + 1), if (judge (X-colnum)) Bomb.sethide (Bomb.gethide () + 1), if (judge (x + colnum)) Bomb.sethide (Bomb.gethide () + 1); if (Judge (X-colnum + 1) && Edgeu) bomb.sethide (bomb.gethIDE () + 1), if (judge (x-colnum-1) && edged) Bomb.sethide (bomb.gethide () + 1), if (judge (x + colnum + 1) &&amp ; EDGEU) Bomb.sethide (bomb.gethide () + 1), if (judge (x + colNum-1) && edged) Bomb.sethide (bomb.gethide () + 1);}}} Determine if a location is a mine private Boolean judge (int x) {if (x >= 0 && x < bomblist.size ()) {if (Bomblist.get (x)). Gethide () = = 9) return true;} return false;} /* * Initialize mine */private void Initbomb (MouseEvent e) {int x = E.GETX (); int y = E.gety (); Rectangle rec = new Rectangle (x, Y, 1, 1); Bomb bombtemp=new Bomb (); int what=0;//in order to avoid the first click of the mine is not the first to let it set as a mine, the initialization of the mine is completed after the restore as-is (Bomb bomb:bomblist) {if ( Rec.intersects (Bomb.getrec ())) {what=bomb.gethide (); Bombtemp=bomb;bomb.sethide (9); break;}} Initialize the map with random numbers r = new Random (), for (int i = 0; i < mc.getminenum (); i++) {while (true) {int index = R.nextint (b Omblist.size ()); if (Bomblist.get (index). Gethide ()! = 9) {bomblist.get (index). Sethide (9); break;}}} Bombtemp.sethide (what);}}
Or your own minesweeper, fun, haha.

If there is a problem can leave a message oh ~ together to solve

All code + pictures

Click to open link



Minesweeper (Java edition)

Related Article

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.