# MatLab Minesweeper

### Objective and Motivation

The goal of this project is to create, from MatLab, a randomly generated working game of minesweeper.

The motivation for this project came from an old desire to create a game that actually works. MatLab has provided a new outlet to attempt to reach this goal. I choose minesweeper because it presented an obvious opprotunity to use matrices for which MatLab is designed.

### Description

This project basically invovles three steps.

1. Creating a randomly generated minesweeper matrix
2. Creating the minsweeper board for interaction
3. Putting the two components toghether to create game interaction

Extras:

- High Scores

- Difficulty levels/ size of the board

### Code

Updated code: File:MatLab Minesweeper.zip

If you are unable to access the above code try here.

Above is the finished code. Open the function MinesweeperGUI.m and click run to begin the game.

### Minesweeper – How it works

Minesweeper is a logic game found on many computers. Basically it is a hunt for mines. The player clicks on a board. Either a number, blank or mine square appears. The number squares tell the player how many mines are adjacent to the number square. The player must then flag all of the mines to win the game.

### Creating the Code

#### Random Matrix

The first step in creating the code was building the matrix generator. The basic premise for matrix creation is a certain number of mines are selected. The program flags these mines and clears the remainder of the board. It then comes back and generates the numbers around each mine.

My initial plan was to generate a random matrix and then set any cells above a determined number as a mine. Below I used .1 as the cutoff point. Those numbers below the cutoff point are made into zeros.

``` A = random('norm',-1,1,size,size);
```
``` if A(y1,x1)>=.1
A(y1,x1)=(9);
else
A(y1,x1)=(0);
end
```

The problem with this idea was that the random matrix would not return a set number of mines. On some occasions the board would be full of mines, on others there would be few or no mines. I needed a board that created a set number of mines.

The next idea was to randomly generate the coordinates for a predetermined number of mines. I created a code to do this. I soon found that sometimes two or more mines would be created in the same spot. To correct this issue I had the program count the number of mines placed so far. If that number was incorrect it would generate another coordinate.

```   ran_x = abs(ceil(random('norm',0,size,1,1)));
ran_y = abs(ceil(random('norm',0,size,1,1)));
```

note: "size" is the size of the board

The next step was to create the non-mine squares. Initially I created a code that went square by square and counted the number of mines around each individual square. I realized that this task took awhile, so I developed a faster way. In the final code the program goes to each mine square and adds one to the value of all adjacent squares. This creates a complete minesweeper board.

#### The Board

The next step I followed was to create a cell array to store all the data for each square. During the game I needed to monitor the state of the square (clicked, flagged, etc.), the image for the square and the square’s value (number or mine). I created images (all 32x32 pixels) for numbers one through eight, a blank square, a mine square, a un-clicked square and a flagged square.

To create this cell array I resaved the data from the mine matrix and used a case structure to add images to the cell.

#### Initial Board Display

In the beginning of the game the board starts off completely covered. In order to create this image I placed multiple images of un-clicked squares in a figure. I soon learned to use the ‘’hold on’’ function to allow all the images to appear together.

#### Game Play

The game was contained within a while loop. I learned how to gain input from the mouse. If the mouse was clicked within the board then the square below the mouse click displayed its image. If the square was a mine than the while loop was exited. If the square was a blank then the eight squares around were also displayed.

Below is the code for a black square hit. The if structure determines if the current square being examined is on the board or if it is the original square.

``` for change_x=-1:1
for change_y=-1:1
if change_x^2+change_y^2~=0 & x+change_x>=1 & x+change_x<=size & y+change_y>=1 & y+change_y<=size
spot_now=board{y+change_y,x+change_x};
image_now=spot_now{1,2};
image_creation(image_now,x+change_x,y+change_y,size);
board{y+change_y,x+change_x}{1,1}=1;
end
end
end
```

If the right mouse button is clicked then the program flags/un-flags the square depending on the current state (Cstate) of the square. If a mine square is flagged than the exit value decreases (when it reaches zero the while loop terminates) and correct_flag increases. correct_flag is used to determain in the end if the player has won or lost.

```           if Cstate==0
image_creation(aflag,x,y,size);
board{y,x}{1,1}=2;
if Cnumber==9
correct_flag=correct_flag+1;
exit=exit-1;
end
end
if Cstate==2
image_creation(aempty,x,y,size);
correct_flag=correct_flag-1;
exit=exit+1;
board{y,x}{1,1}=0;
end
```

#### Ending the Game

Once the while loop terminates all the squares are revealed. And the program displays number of clicks and whether you have won or lost.

#### GUI

Once I had created the above working minesweeper game I decided to make it slightly more interesting by creating a Graphic User Interface (GUI). This GUI would allow me to –have user input of mine count and board size and at the end display win/lose and clicks in a nice display window.

In order to create the GUI I used MatLab’s GUIDE tool. This allowed me to drag and place the text and input boxes that I needed.

The starting window displays rules and allows the player to input the size of the board and the number of mines. If the size was over thirty than an error box appeared. If the number of mines exceeded the size limitations of the board then another error appeared. Below is the code used to display an error for incorrect size input.

``` user_entry = str2double(get(hObject,'string'));
if isnan(user_entry) | user_entry<1 | user_entry>30 | ceil(user_entry)~=user_entry
errordlg('You must enter a positive intiger value less than 30 and greater than zero','Bad Input','modal')
set(hObject,'String','1')
uicontrol(hObject)
return
end
```

GUI is stored in something called handles. Each object within the GUI has specific handle properties such as location , color, etc.. ‘’hObject’’ in the above is simply getting the data for this particular object from the handle.

Once the ready button is pushed, the minesweeper program runs. Following its completion the EndGUI.m function boots up.

The EndGUI function used input from the minesweeper game to determine whether the player has won and how many clicks he/she has made. It then displays these values. Finally it asks whether you wish to play again. If yes if clicked than the program calls itself thus repeating; if no is clicked the windows close.

### Issues

A number of issues have already been outlined above. Besides these I encountered a few more snares:

Pictures - Originally I did not make the pictures square, so when they were displayed gaps appeared. I redrew the pictures.

EndGUI - After figuring out how to program the GUI, I encountered the difficulty of transferring data between GUI functions. Eventually Professor Cheever showed me the built in variable called varargin which works to move variables.

### Time Line

The following represent the due dates:

November

20 - Create matrix generator, research user interface

22 - Create user interface, begin game interaction

30 - Complete Game

December

4 - Debug game

6 - Presentation done

8 - Present

10 - Complete write-up

Just MatLab