How to use C # to create a graphics code tutorial for minesweeper Games

Source: Internet
Author: User
This article mainly introduces the elaboration from the zero-beginning---in C # to make Minesweeper game, very practical value, the need for friends can refer to the next

The reason to learn C # is actually quite simple, because has been very interested in the game, looked under the more popular game engine Unity's main development language is C #, so decided to start from C #, learn the object-oriented programming method.

Before basically do is embedded development, do embedded for a long time, basically only C language, C language process-oriented features in embedded programming this resource is extremely restricted, but this way in the face of large-scale software development is difficult to do. Programming mode is actually a habit of thinking, after a long time, want to change is really a difficult process ...

Speaking of C #, in fact, in college when learning a semester, said ashamed at that time did not take it as an object-oriented language (in fact, it is not know what object-oriented), and C language also a little grammatical differences, all the usage of all into the grammar is different, said also magic, this method can also be programmed. At the end of the semester, I handed in a mine-clearance game developed with WinForm, which ended my C # study and never touched C # after that.

Now regain C #, in order to avoid unnecessary distractions, and not learn directly on unity, but still learning in VS, but this time chose to compare the new WPF, rather than WinForm, as a learning, the first task or the same as the previous one to do a minesweeper game.

Written in front of the first: This article mainly share the next procedure analysis process, the specific implementation method is not the focus of this article, to achieve the problem of friends can comment on the area of the message request source code or ask ^_^.

First, analysis

1. Game Analysis

That goes to the point, how to complete the game. Ignore the details of the part (such as timing, show the remaining number of mines, menu bar, etc.) do not say, the main body of the game: the mine area.

In the game did not start, the mine area to look at actually only one thing, that is the square ...

Ignoring the effects of light and shadow (yes, I missed it again ...) ), all squares have the same color, and all respond to the same event, that is, the left and right buttons. Left-click to open the box, right-click the box to mark, identified as a mine. Further analysis, the blocks have different types. Some blocks open after the opening of a large block around. Some of the blocks below are mines, which are gameover at the point of opening. There are also numbers below the blocks, which represent the number of mines around. (Sure enough, I ignored the mouse two keys at the same time by automatically opening the surrounding grid and the second right-click to display the question mark function ...) But in fact, it will be found that the function will actually increase is also very simple).

So, first to summarize the core of the implementation of the minesweeper game:

    1. Blocks will respond to mouse events (left button press, left click, right button press, mouse move, mouse out).

    2. When the block is opened, there are three kinds of effects (bombs, numbers, empty), which will automatically expand all surrounding blocks when empty.

    3. Blocks can only be opened once, and then no longer respond to key events.

    4. The game wins when the number of blocks in the flag is equal to the number of mines, and each block containing the mines is flagged.

    5. When the block containing the mines is opened, the game fails.

2. Implement Technical Analysis

After analysis, is not found that the game of minesweeper is actually very simple, the realization of the technology is not difficult, all static no animation exists.

The block behaves like a button that can only be pressed once (in fact, I was directly inheriting the button control when I was in college).

But this time in order to be able to use more C # related things I used a more cumbersome way to customize the controls.

The box has three kinds of forms, for the particularity, but obviously also has the generality, therefore in the design time, I drew out the button generality, has designed an abstract base class cube. There are three types of blocks, but because I am lazy, I merge two of them (blanks and numbers) into the Numcube class, which contains the mines for the Bombcube class, and these two classes inherit the cube respectively.

The implementation of Cube:

The cube class has the following fields:


ImageSource Cubenormalpicimagesource Cubeonpicimagesource Cubedownpicimagesource CubeDisablePicImageSource Cubeflagpic

These 5 fields are used to set the picture that the cube displays in each state (normal, mouse on, left button pressed, disabled, tagged)


Bool Isenablebool Isflag

These are both fields that mark whether the cube is enabled and flag


Image Cubeimagehighimage Cubeimagelow

These 2 are two image controls that are used to display the image, and the reason for the 2 picture is that the flag image is designed as a picture superimposed on the cube.

Let's focus on the following 2 things:


Displaycubemouseevent

In the design, this is two interfaces, respectively, to handle mouse events and block expansion. Unlike directly in the internal implementation of the interface directly, the two interface design as the Cube property is to be able to dynamically modify the implementation of the two interfaces, not every modification needs to modify the code within the cube, and can be implemented each different cube uses different code and does not need to use overrides, This approach is also called "policy mode" in design mode.

Cube has only one method, that is open, but this method is actually a display interface proxy implementation.


public void Open ()   {     if (displaycube! = null)     {  displaycube.open (this);}     }

Displaycube.open (this) introduced itself because the Open method uses the cube's own parameters and methods.

Bombcube inherits from Cube

Only one field was added:


ImageSource Bombpic

Used to store mine pictures.

Numcube inherits from Cube


Int Bombnum

It is used to record how many Bombcube are around the block, and when it is 0, the Numcube is the block that appears empty.

Added a component lable to display the digital text.

The realization of interface

Each cube is designed for each of the implementation of an interface, using this way, if you need to change the later animation display, it is only necessary to implement an animation interface, assigned to the corresponding cube can be.

Second, the realization

Control inheritance:

When WPF makes control inheritance, it is important to note that inherited controls cannot have XAML.

In the inheritance, you need to include the following statement in XAML:


< Mytypes:cube x:class= "minesweeper. Usercontrol.numcube "xmlns="/http/schemas.microsoft.com/w infx/2006/xaml/presentation "xmlns:x="/HTTP/ schemas.microsoft.com/w Infx/2006/xaml "xmlns:mc="/http/schemas.openxmlformats.org/markup-compatibility/2006 " Xmlns:d= "/http schemas.microsoft.com/e xpression/blend/2008" mc:ignorable= "D" xmlns:mytypes= "Clr-namespace: Minesweeper. UserControl "d:designheight=" "d:designwidth=" >

Cube Mouse Event Implementation:

Mouse events are essentially transformations of the cube picture in various events, such as mouse-over events


public void Mouseleavecube (object sender, MouseEventArgs e)   {       Bombcube bombcube = sender as Bombcube;      if (bombcube.isenable)      {  isclicking = false;  BombCube.cubeImageLow.Source =  bombcube.cubenormalpic;      }   }

The generation algorithm for mine location is implemented:

One important aspect of the game is that the location of each mine should be different. It is easy to think of the location of mines that should be generated with random numbers. This requires a random generation of n different coordinates. The implementation of this program is to create a list<int>, and then use random numbers to randomly generate a number between 0-sizex * sizeY-1, check whether the list contains the number, if not included, add to the list, until the list has n elements stop.


List<int> bombindexlist=new list<int> ();      Random ran = new random ();      Do      {int bombindex = ran. Next (0,sizex * sizeY-1); if (! Bombindexlist.contains (Bombindex)) {  bombindexlist.add (bombindex);} else {   continue;}     } while ( Bombindexlist.count < bombnum); indexlist = Bombindexlist;

Then according to the generated list to determine whether the coordinates should be numcube or bombcube


for (int y = 0, y < Sizey; y++)     {for (int x = 0; x < sizex;x++) {  //cube property set  if (Bombindexlist.exists ((i NT temp) = TEMP = = x + y * CubeX))  {   cubexmatrix[x, y] =bombcubelist[bombindex++];  }  else  {   Numcubelist[numindex]. Text = "";   Cubexmatrix[x, y] =numcubelist[numindex++];  }  Cubexmatrix[x, Y]. Isflag =false;  Cubexmatrix[x, Y]. Margin =new Thickness (x *, Y *, 0, 0);  Cubexmatrix[x, Y]. Isenable = true;  Setcubebombnum (Cubexmatrix,cubex, Cubey);  BombGrid.Children.Add (cubexmatrix[x, y]);          }     }

How to make a blank cube open will open the surrounding cube:

Because this opening is a bit like recursion and needs to be contagious (even if opens a blank cube, it should also open the surrounding cube), so be sure to have the information about the cube around you when you execute the event (that is, you can get the surrounding controls).

There are two ways to get around the cube:

1. Save the location of the cube itself and get the location of all the cubes

2. Save the information of the surrounding cube

I used the second way, the cubelist in the cube class was used to hold the information about the cube around. Locate the surrounding cube through cubelist and trigger their left-click event.


public void MouseLeftButtonUp (object sender, MouseButtonEventArgs e) {  Numcube numcube = sender as Numcube;  if (numcube.isenable && Numcube.isflag = = False)  {    //finish on the control by clicking on the    if (isclicking)    {      Isclicking = false;      Numcube.isenable = false;      if (numcube.bombnum! = 0)        Numcube.text = convert.tostring (numcube.bombnum);      else      {        foreach (Cube cubetemp in numcube.cubelist)        {          MouseButtonEventArgs args = new MouseButtonEventArgs (mouse.primarydevice, 0, mousebutton.left);          Args. RoutedEvent = cube.mouseleftbuttondownevent;          Cubetemp.raiseevent (args);          Args. RoutedEvent = cube.mouseleftbuttonupevent;          Cubetemp.raiseevent (args);}}}}  

Some tips:

1. You can put some picture changes in the set of attributes, such as disable pictures.


public bool isenable{  get {return isenable;}  Set   {     isenable = value;    if (isenable)    {      if (cubenormalpic! = null)        Cubeimagelow.source = cubenormalpic;    }    else    {      if (cubedisablepic! = null)        Cubeimagelow.source = Cubedisablepic;}}  }

2.WPF creating a control is slow, in order to increase the speed of the game (after modifying the width or number of mines), you should pre-create the control and put the control in list or arr to save it as required.

To the production of the mine-clearance game is not difficult technical difficulties, only need to understand some of the WPF common events, controls, Xalm related knowledge can make a minesweeper game. The relevant source code is not sent here, the need for friends can comment to find me, this game made me to the basic object-oriented approach to the understanding has a great promotion, next time you should be able to do in unity game haha.

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.