0% found this document useful (0 votes)
28 views8 pages

Minesweeper Game Start Form Code

This document contains code for a minesweeper game implemented using C# and Windows Forms. It includes classes for the start form, game board form, mine grid, and shared data. The start form initializes the game settings and passes control to the game board form. The mine grid class handles random mine placement and counting adjacent mines. Shared data stores game state like the grid, flag count, and revealed tiles.

Uploaded by

lloyddagoc
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views8 pages

Minesweeper Game Start Form Code

This document contains code for a minesweeper game implemented using C# and Windows Forms. It includes classes for the start form, game board form, mine grid, and shared data. The start form initializes the game settings and passes control to the game board form. The mine grid class handles random mine placement and counting adjacent mines. Shared data stores game state like the grid, flag count, and revealed tiles.

Uploaded by

lloyddagoc
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Start Form

using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];

namespace Minesweeper_WindowsForms
{

public partial class startForm : Form


{
public startForm()
{
InitializeComponent();

private void Form1_Load(object sender, EventArgs e)


{

private void playButton_Click(object sender, EventArgs e)


{
char level = 'e'; // this is the default level which is the easy mode
if ([Link] == true) level = 'h'; // if hard mode is clicked
else if ([Link] == true) level = 'm'; // if medium mode is clicked

[Link] = new MinesweeperGrid(level); // depending level which is clicked


[Link] = false; // the first click hasn't happened yet
[Link] = 0; // number of tiles per level
[Link] = [Link]; // in how many flags
is remaining after marking the tiles

Form window = new GameBoard();


[Link] = this;
[Link]();
[Link]();
}

private void label1_Click(object sender, EventArgs e)


{

private void easyRB_CheckedChanged(object sender, EventArgs e)


{

private void label2_Click(object sender, EventArgs e)


{

private void mediumRB_CheckedChanged(object sender, EventArgs e)


{

}
}
}

GameBoard Form
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];

namespace Minesweeper_WindowsForms
{

public partial class startForm : Form


{
public startForm()
{
InitializeComponent();

private void Form1_Load(object sender, EventArgs e)


{

}
private void playButton_Click(object sender, EventArgs e)
{
char level = 'e'; // this is the default level which is the easy mode
if ([Link] == true) level = 'h'; // if hard mode is clicked
else if ([Link] == true) level = 'm'; // if medium mode is clicked

[Link] = new MinesweeperGrid(level); // depending level which is clicked


[Link] = false; // the first click hasn't happened yet
[Link] = 0; // number of tiles per level
[Link] = [Link]; // in how many flags
is remaining after marking the tiles

Form window = new GameBoard();


[Link] = this;
[Link]();
[Link]();
}

private void label1_Click(object sender, EventArgs e)


{

private void easyRB_CheckedChanged(object sender, EventArgs e)


{

private void label2_Click(object sender, EventArgs e)


{

private void mediumRB_CheckedChanged(object sender, EventArgs e)


{

}
}
}

[Link]

using System;
using [Link];
using [Link];
using [Link];
using [Link];

namespace Minesweeper_WindowsForms
{
class MinesweeperGrid
{
int numberOfMines;
int[,] grid;
Tuple<int, int>[] locationsOfMines;

#region constructors

public MinesweeperGrid()
{
// the default values
[Link] = 10;
grid = new int[9, 9];
locationsOfMines = new Tuple<int, int>[10];
}

/// <summary>
///
/// </summary>
/// <param name="level"> 'e' for easy, 'm' for medium and 'h' for hard </param>
public MinesweeperGrid(char level )
{
if (level == 'h' || level == 'H')
{
[Link] = 99;
[Link] = new int[16, 30];
locationsOfMines = new Tuple<int, int>[99];
}
else if (level == 'm' || level == 'M')
{
[Link] = 40;
[Link] = new int[16, 16];
locationsOfMines = new Tuple<int, int>[40];
}
else
{
[Link] = 10;
[Link] = new int[9, 9];
locationsOfMines = new Tuple<int, int>[10];
}
}

#endregion

#region Properties

public int NumberOfMines


{
get { return numberOfMines; }

}
public int[,] Grid
{
get { return grid ; }

public Tuple<int, int>[] LocationsOfMines


{
get { return locationsOfMines; }
}

#endregion

/// <summary>
/// this method distributes the mines randomly over the grid with -1 value
/// and making sure the grid[startX, startY] is not one of them.
/// It also calcuates the number of adjacent mines for every
/// tile in the grid to set its value to.
/// </summary>
/// <param name="startX">the row index of first tile to be clicked </param>
/// <param name="startY">the coulmn index of first tile to be clicked </param>
/// <returns>the return is 2D matrix with values of th grid</returns>
public int [,] distributeMines(int startX, int startY)
{
int mines = numberOfMines;
Random rand = new Random();
int r = [Link](0);
int c = [Link](1);
int i, j;

///distributing Mines randomly///


while (mines>0)
{
i = [Link](0,r); // random row
j = [Link](0,c); //random coulmn

// check if it is not a mine already


if ( !(startX ==i && startY ==j) && grid[i,j] !=-1)
{
grid[i, j] = -1; // this tile represents a mine now
mines--;
locationsOfMines[mines] = new Tuple<int, int>(i, j);
}

/// counting the adjacent mines ///


int sum;
for (i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
//if it is a mine skip
if (grid[i, j] == -1)
continue;

sum = 0;
// making a 3x3 window to calculate
for(int a= -1; a < 2; a++)
for (int b = -1; b < 2; b++)
{
if (i + a >= 0 && i + a < r //to check boundaries
&& j + b >= 0 && j + b < c
&& grid[i + a, j + b] == -1)

sum++;

grid[i, j] = sum;

}
return grid;
}

}
}

[Link]

using System;
using [Link];
using [Link];
using [Link];
using [Link];

namespace Minesweeper_WindowsForms
{
class SharedData
{
public static MinesweeperGrid mGrid;
public static bool startFlag;
public static int numberOfRevealedTiles;
public static int numberOfRemainingFlags;
}
}

[Link]
using System;
using [Link];
using [Link];
using [Link];
using [Link];

namespace Minesweeper_WindowsForms
{
static class Program
{
[STAThread]
static void Main()
{
[Link]();
[Link](false);
[Link](new startForm());
}
}
}

Common questions

Powered by AI

Object-oriented programming is used extensively in the Minesweeper game through classes and objects to encapsulate game logic and data management. Classes such as 'MinesweeperGrid' manage the specifics of the board configuration, mine locations, and grid initialization . 'SharedData' serves as a static class to share state variables across different forms, including the initialized grid and counters for revealed tiles and remaining flags . These structures allow for data encapsulation, separation of concerns, and easier maintenance and scalability of the game code.

The difficulty level in the Minesweeper game is determined by the user's selection from radio buttons indicating easy, medium, or hard modes. Upon starting the game, the 'playButton_Click' method checks which radio button is selected. If no button is selected, the default is 'easy' mode ('e'). The differences in configurations are based on the number of mines and grid size for each level: easy mode features 10 mines on a 9x9 grid , medium mode has 40 mines on a 16x16 grid, and hard mode has 99 mines on a 16x30 grid .

The Minesweeper code employs event handlers linked to radio buttons representing different difficulty levels to trigger different behaviors when selections change. Specifically, each radio button (easyRB, mediumRB, hardRB) has a CheckedChanged event where the respective flags (level for easy, medium, or hard) are adjusted to reflect the user's choice. These event handlers ensure that the correct initialization parameters, such as the number of mines and grid size, are set upon game start when the play button is clicked .

The Minesweeper program determines the number of adjacent mines for each tile using a nested loop structure that examines a 3x3 window centered around the tile in question. For each tile that is not a mine, the 'distributeMines' method sums up the number of mines found within this window by checking each adjacent tile for the presence of a mine, indicated by a value of -1 . The sum of mines in these adjacent positions is then assigned to the tile, indicating how many mines surround it, thereby guiding the player in gameplay strategy .

The Minesweeper program ensures that the start tile is not a mine by checking that the first clicked tile's coordinates do not match the randomly selected mine placement coordinates during the distribution process . The method 'distributeMines' places mines randomly across the grid using random row and column indices, ensuring these indices do not match the start tile and that no cell already contains a mine . Through a loop, the method decrements the number of mines remaining to be placed until all are distributed, and non-mine tiles are updated with the count of adjacent mines for player guidance .

The easy difficulty level's settings, featuring a 9x9 grid with 10 mines, aim to provide an introductory experience for players, striking a balance between challenge and accessibility . This configuration allows for less dense mine placement, reducing the likelihood of frequent game-ending mistakes and encouraging beginners to develop skills in identifying safe zones and strategically using flags. The relatively low number of mines simplifies the grid, facilitating a learning environment for players to grasp fundamental gameplay mechanics, such as interpreting adjacent numbered tiles .

The game initializes the number of flags available to the player through the 'numberOfRemainingFlags' variable, which is initially set to the total number of mines for the selected difficulty level . As the player marks tiles with flags, this count is expected to be managed by decrementing when a flag is placed and incrementing when flags are removed, ensuring it reflects the number of remaining mines that need to be flagged .

The 'SharedData' class plays a crucial role in the Minesweeper game by acting as a repository for shared state variables across different game forms, such as 'mGrid', 'startFlag', 'numberOfRevealedTiles', and 'numberOfRemainingFlags' . This static class enables easy access and modification of these variables without needing to pass them around explicitly, simplifying data management. However, the use of a static class can lead to tight coupling between different parts of the program, increasing the risk of unintended side effects if state changes are not carefully controlled. Additionally, it limits flexibility in terms of reusing code in different contexts or iterating multiple game sessions independently .

The use of the Tuple data structure to represent the locations of mines, with each Tuple containing row and column indices, provides a simple and direct way to handle pairs of integers, ensuring that mine positions are easily accessible and iterable . However, Tuples can become less readable and harder to manage if additional metadata or functionalities related to mines are needed. Alternatives include defining a custom struct or class, which could store additional information with clearer property names, enhance readability, and provide methods to manipulate or query mine positions, but at the cost of added complexity .

The 'InitializeComponent' method in the Minesweeper program's form classes is called within the constructor of the form to set up the user interface components, initialize control properties, and handle layout settings necessary for the form's display and functionality . This method is auto-generated and typically managed by the development environment to link design-time UI configurations with runtime behavior, ensuring that all form elements are properly instantiated and configured before the form is presented to the user .

You might also like