0% found this document useful (0 votes)
41 views51 pages

Mine Sweeper Game

Minesweepergame using c++ mini project reference

Uploaded by

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

Mine Sweeper Game

Minesweepergame using c++ mini project reference

Uploaded by

britolal2007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

A MINI PROJECT REPORT

MINESWEEPER CONSOLE-BASED GAME

BACHELOR OF ARTIFICIAL INTELLIGENCE AND MACHINE


LEARNING

Submitted By
AKASH S
(Reg. No. 2428C0006)

Under the Guidance of


Dr.M.Lalithambigai
M Sc.,M.Phil.,M.Sc(App Psyc).,Ph.D., HOD,
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING

OCTOBER 2024

1
CERTIFICATE

2
CERTIFICATE

This is to certify that the Mini Project entitled “MINESWEEPER CONSOLE-BASED


GAME” is the bonafide record of Mini Project work done by AKASH S, Register No:
2428C0006 of I BSc Artificial Intelligence and Machine Learning during the academic year
2024-2025 of his study in the Department of Artificial Intelligence and Machine Learning, Sri
Krishna Adithya College of Arts and Science, Coimbatore.

SIGNATURE OF THE GUIDE

SIGNATURE OF THE HOD PROJECT HEAD

DEAN-RESEARCH SIGNATURE OF THE PRINCIPAL

Submitted for the Mini Project Viva-Voce Examination held on ___________

EXAMINER

3
DECLARATION

4
DECLARATION

I, AKASH S hereby declare that the Mini Project work, entitled


“MINESWEEPER CONSOLE-BASED GAME”, submitted to the Sri Krishna Adithya
College of Arts and Science, in partial fulfilment of the requirements for the award of the Degree
of BACHELOR OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING, is a
record of original research work done by me during the period 2024-2025. This Mini Project is
the original work carried out by me and it is not a part of any other Mini Project/Project work.

Place: Coimbatore Signature of the Candidate

Date: ( AKASH.S)

5
ACKNOWLEDGEMENT

6
ACKNOWLEDGEMENT
I first and foremost thank the almighty for having bestowed his blessings on me to
complete the mini project.

I am indebted to our beloved Principal Dr.S.Palaniammal.,M.Sc.,M.Phil.,Ph.D., Sri


Krishna Adithya College of Arts and Science, Coimbatore for her support and encouragement.

I wish to express my gratitude to the respected


Dr.K.Chitra.,M.Sc.,MBA.,M.Phil.,Ph.D., Dean-Research, Sri Krishna Adithya College of Arts
and Science, Coimbatore for supporting me to complete this mini project work.

I have a deep sense of gratitude to the respected Dr.K.Geetha,MSc.,M.Phil.,Ph.D., Dean


of Computer Science and Dr.M.Lalithambigai M Sc.,M.Phil.,M.Sc(App Psyc).,Ph.D.,
Department of Artificial Intelligence and Machine Learning Head, Sri Krishna Adithya College
of Arts and Science, Coimbatore for her encouragement and support for the successful
completion of this mini project.

I would like to convey my sincere gratitude to Ms.G.J. Keerthi., M.Sc., Assistant


Professor, Department of Artificial Intelligence and Machine Learning, Sri Krishna Adithya
College of Arts and Science, Coimbatore for her encouragement and support for the successful
completion of this mini project.

I thank my project guide Dr.M.Lalithambigai M Sc.,M.Phil.,M.Sc(App Psyc).,Ph.D.,


HOD, Department of Artificial Intelligence and Machine Learning, Sri Krishna Adithya College
of Arts and Science, Coimbatore for his/her timely advice and guidelines which assisted me in
completing the mini project work successfully.

My sincere thanks and gratitude to all the faculty members of Department of Artificial
Intelligence and Machine Learning, Sri Krishna Adithya College of Arts and Science,
Coimbatore for their encouragement and support for the successful completion of this mini
project.

My special thanks to my Parents, Friends and Well-wishers for their moral support
throughout the mini project work period.

AKASH.S

7
TABLE OF CONTENT

8
CHAPTER PARTICULARS PAGE NO

Certificate 3

Declaration 5

Acknowledgement 7

Synopsis 12

1 Introduction

1.1 About the Project 14

2 Review of Literature

2.1 Existing System 17

2.2 Limitation 17

3 System Study

3.1 Proposed System 20

3.2 Advantages of Proposed System 21

4 System Analysis

4.1 Module Description 23

4.2 DFD Diagrams 25

4.3 Requirements Specification 27

5 System Design

5.1 Input Design 30

9
5.2 Output Design 30

5.3 Database Design 31

5.4 Form Design 32

6 Conclusion and Future Enhancements

6.1 Conclusion 35

6.2 Future Enhancements 35

7 Appendix

7.1 Sample Coding 37

7.2 Sample Output 49

7.3 Bibliography 51

10
SYNOPSIS

11
SYNOPSIS

The Minesweeper Console Based Game project is a classic single-player logic puzzle
game that challenges players to clear a grid of hidden mines without triggering (detonating) any.
The primary objective is to uncover all safe cells while skillfully avoiding mines, necessitating a
combination of strategic planning and logical deduction. This project aims to develop a
streamlined mini version of Minesweeper, focusing on creating an intuitive text-based user
interface that is both engaging and easy to navigate. By emphasizing user experience and
accessibility, the game seeks to attract a diverse audience of players, from novices to seasoned
gamers.

The Minesweeper game is an engaging and interactive text-based implementation that


challenges players to navigate a grid filled with hidden mines. Players must select cells on the
grid, revealing either a safe spot or a mine. Each cell reveals a number indicating the count of
adjacent mines, enabling players to deduce safe moves strategically. The game introduces
multiple difficulty levels, including Easy, Medium, Hard, Shuffle and a customizable mode,
allowing players to tailor their experience based on their skill level and preferences. This
adaptability enhances the replayability of the game, making each session unique and challenging.
The game records various player statistics, such as grid size, the number of mines, game
outcomes (win/loss), and the selected game mode. These metrics are saved in a CSV file for later
analysis, enabling players to monitor their performance and track their progress over time.

12
INTRODUCTION

13
1.1 ABOUT THE PROJECT

The Minesweeper game project is a digital adaptation of the classic logic-based game that
has captivated players since its inception on early computer systems. The objective is simple:
reveal all non-mine cells while avoiding those containing mines. When a player selects a
non-mine cell, it displays the count of neighboring cells that contain mines, requiring players to
use logic and deduction to determine which cells are safe to select next. This project delivers a
console-based version of the game using Python.

To enhance player engagement and accommodate various skill levels, the game includes
multiple difficulty modes: Easy, Medium, Hard, Shuffle and Custom. Each mode adjusts the
complexity of the grid and the number of mines, allowing players to choose a setting that best
fits their abilities and preferences. In the Easy mode, for instance, players might encounter a
smaller grid with fewer mines, making it ideal for newcomers. In contrast, the Hard mode
presents a more challenging experience with a larger grid and a higher mine density, suitable for
experienced players seeking a test of their skills. The Shuffle model randomly selects the game
mode option with predefined configurations for added excitement and variety. The Custom mode
further empowers players to create their unique challenges by selecting grid dimensions and
mine counts, fostering a personalized gaming experience. This adaptability ensures that the game
remains fresh and exciting, encouraging players to return and try different configurations.

The gameplay is centered around a grid of squares, each of which can either conceal a
mine or be empty. If a player uncovers a square containing a mine, the game ends in failure. To
assist players in avoiding mines, each uncovered square displays a number indicating how many
adjacent squares contain mines. This numerical clue system is pivotal, as it encourages players to
think critically about their next moves, weighing the risks associated with uncovering certain
cells. This design emphasizes strategic thinking and logical deduction, as players receive
numerical clues about the number of mines in neighboring cells, making each decision critical to
their success.

Furthermore, the project includes a results recording system that saves game statistics in a
CSV file. This functionality allows players to analyze their performance and identify trends over

14
time, enhancing the competitive aspect of the game and motivating players to refine their skills.
By reviewing these specific details, players can better understand their gameplay patterns and
make informed adjustments for future games.

15
REVIEW OF LITERATURE

16
2.1 EXISTING SYSTEM

The existing Minesweeper game has been a staple in casual gaming, typically featuring
three predefined difficulty levels: easy, medium, and hard. Each level is designed with specific
grid sizes and mine counts, enabling players of varying skill levels to participate. For instance,
the easy level may feature a small grid with fewer mines, while the hard level challenges players
with larger grids filled with a higher concentration of mines. This tiered approach enables
newcomers to get comfortable with the game while still offering a substantial challenge for
seasoned players.

Gameplay mechanics are straightforward, employing left-click actions to uncover cells


and right-click actions to flag suspected mines. These intuitive controls ensure that players can
easily navigate the game without needing extensive instructions. Additionally, the existing
system incorporates a timer and score-tracking mechanism, which not only enhances the
competitive aspect of the game but also motivates players to improve their performance with
each playthrough. This gamification aspect serves to heighten the excitement and engagement, as
players can compare their scores against others or aim to beat their personal best times.

Moreover, the existing Minesweeper system often includes various visual themes,
allowing for aesthetic customization. This feature not only enhances the visual appeal of the
game but also provides options for accessibility. For instance, high-contrast modes and sound
cues cater to players with different needs, ensuring that everyone can enjoy the game experience.
While the existing system has many strengths, it does face limitations that may affect player
satisfaction and engagement over time, necessitating consideration for improvements in a
proposed system.

2.2 LIMITATION

Despite the strengths of the existing Minesweeper system, it has several limitations that
may hinder the overall player experience. One significant drawback is the reliance on predefined
difficulty levels, which can restrict players seeking a more customized gaming experience. Many
seasoned players may find the available options too simplistic or repetitive, leading to a decline

17
in engagement over time. Furthermore, the fixed grid sizes and mine counts can result in
predictable gameplay, which may fail to challenge experienced players adequately.

Another limitation lies in the accessibility of the graphical interface. While visual themes
can enhance the gaming experience, they may also create barriers for players with visual
impairments or those unfamiliar with traditional gaming controls. The standard point-and-click
mechanics can be challenging for some users, particularly those who require adaptive
technologies. Additionally, the existing system may lack features like sound descriptions or
keyboard shortcuts, further alienating certain player demographics. This lack of inclusivity can
detract from the overall appeal of the game.

Furthermore, the complexity of the gameplay instructions can overwhelm new users.
Although the existing system provides basic guidance, the learning curve associated with
understanding how to effectively flag mines and navigate the grid can deter new players from
fully engaging with the game. This complexity may lead to frustration and, ultimately, drive
away potential players before they can appreciate the game's depth. To enhance user experience,
simplifying the instructions and streamlining gameplay mechanics would be beneficial for
attracting and retaining players. Addressing these limitations is essential to enhance player
satisfaction and ensure that Minesweeper remains a compelling and engaging experience for a
diverse audience.

18
SYSTEM STUDY

19
3.1 PROPOSED SYSTEM
The proposed Minesweeper system aims to create a lightweight, console-based version
that emphasizes simplicity and accessibility. By focusing on a text-based interface, this new
version eliminates the complexities associated with graphical elements, making it easier for all
players, including those with limited gaming experience, to engage with the game. The
console-based format allows for quicker loading times and reduced resource consumption,
enhancing the gaming experience across a variety of devices, from modern computers to older
systems.

In this proposed system, multiple difficulty levels are introduced, including Easy,
Medium, Hard, Random Shuffle, and Custom mode. This variety allows players to choose their
preferred grid sizes and mine counts, tailoring the gameplay to their skill levels and personal
preferences. For instance, in Custom mode, players can create unique challenges that keep the
game fresh and exciting. This flexibility not only caters to a broader audience but also
encourages players to explore new challenges, making each playthrough a unique experience that
can reignite their interest in the game.

Furthermore, the proposed system employs a simple command structure for player
interaction, allowing them to reveal cells, select difficulty levels, and restart the game with ease.
This streamlined approach reduces the learning curve, enabling players to dive straight into the
action without being bogged down by complicated menus or instructions. Additionally, the
compatibility with any operating system that supports Python ensures that the game is widely
accessible, inviting players from diverse backgrounds and experiences to participate. This
emphasis on user-friendliness promotes a sense of accomplishment, encouraging players to
engage repeatedly.

Lastly, the proposed system enhances replayability and community engagement. This
focus on social interaction creates a more vibrant gaming environment, encouraging players to
return to the game to improve their scores or try new challenges. Ultimately, the proposed
Minesweeper system aims to enrich the overall gaming experience, ensuring it remains relevant
and enjoyable for a wide range of players.

20
3.2 ADVANTAGES OF PROPOSED SYSTEM
The proposed Minesweeper system offers numerous advantages, starting with its
customizable gameplay experience. By allowing players to select their difficulty levels and grid
sizes, the game can cater to both novice and expert players, ensuring that everyone can find a
challenge that suits their abilities. This personalization enhances player satisfaction and
encourages prolonged engagement, as players can continually adapt the game to maintain a sense
of challenge. The introduction of a Random Shuffle mode adds an exciting element of
unpredictability, keeping players engaged and interested over time.

Another key advantage of the proposed system is its focus on simplicity and accessibility.
The console-based design eliminates barriers presented by graphical interfaces, making it easier
for players with visual impairments or those unfamiliar with traditional gaming mechanics to
enjoy the game. The straightforward command structure allows players to focus on strategy and
gameplay rather than navigating complex menus. By ensuring that the game is inclusive, the
proposed system opens the door for a wider audience, inviting individuals who may have felt
excluded from traditional Minesweeper versions to participate.

Lastly, the proposed system enhances replayability by continually offering new


challenges and experiences. The ability to customize the gameplay ensures that players can
explore different strategies and approaches with each session, preventing the game from
becoming stale. This adaptability promotes continuous engagement, encouraging players to
return frequently to test their skills against various configurations. Moreover, the ability to create
custom game setups and share them with others fosters creativity and collaboration, enriching the
gaming experience and encouraging players to return for more.

Overall, the proposed Minesweeper system aims to elevate the gaming experience,
making it not only more enjoyable but also more accessible and community-oriented for a
diverse player base.

21
SYSTEM ANALYSIS

22
4.1 MODULE DESCRIPTION
The Minesweeper game module is a lightweight, console-based implementation of the
classic Minesweeper game, designed for simplicity and accessibility. It consists of multiple
interconnected modules, each responsible for distinct functionalities that enhance the gaming
experience. These modules collaboratively manage game setup, user interactions, and outcome
tracking. This section provides an overview of each module, detailing their specific roles and
contributions to gameplay. Each module is designed to ensure players can enjoy a seamless and
engaging Minesweeper experience.

1. Game Board Module:

The Game Board Module is essential for establishing the foundational game
environment. It is responsible for creating a grid of specified dimensions that acts as the playing
field. This module initializes the game board by randomly placing a designated number of mines
across the grid, ensuring that each game session is unique and unpredictable. The module also
tracks the state of each tile on the board, categorizing them as hidden or revealed. As players
interact with the game, this module handles updates to the tile states based on user actions, such
as revealing a tile or flagging a mine, ensuring real-time feedback and engagement.

2. Game State Management Module:

The Game State Management Module oversees the game's overall status and determines
its outcome. The game concludes when a player either reveals a mine, resulting in a loss, or
successfully uncovers all safe cells, indicating a win. This module tracks the current state of the
game and provides players with clear, informative messages regarding the outcome, whether
they have won or lost. Additionally, it offers players the option to restart the game, allowing for
continuous play and engagement without the need to reset the entire application.

3. Level Configuration Module:

The Level Configuration Module is designed to offer players a variety of difficulty levels
to enhance gameplay. The EASY level features a small grid with a few bombs, catering to
beginners or those looking for quick gameplay sessions. The MEDIUM level presents a balanced

23
challenge with a moderate number of bombs on a medium-sized grid. For experienced players
seeking a more intense experience, the HARD level offers a large grid filled with numerous
bombs. Furthermore, a CUSTOM mode enables players to set their own parameters, tailoring the
game to their preferences. The SHUFFLE option introduces a random game mode with
predefined configurations, adding excitement and variety to the gameplay experience.

4. Game Logic Module:

The Game Logic Module is critical for ensuring that the game operates according to the
established rules and requirements. It manages the placement of mines on the board, adhering to
the difficulty level set by the player. This module calculates and updates the number displayed on
each tile based on the number of adjacent mines, providing players with essential information to
strategize their moves. It also implements logic for revealing a tile, and if the tile is empty, it
recursively reveals all adjacent empty tiles, enhancing the gameplay experience. Additionally,
this module checks for win conditions and handles game-over scenarios, ensuring that the game
flows smoothly and consistently.

5. Text-based User Interface (TUI) Module:

The Text-based User Interface (TUI) or Console Based Module provides the visual
representation of the Minesweeper grid within a terminal or console window. This interface is
designed to be user-friendly and intuitive, displaying the game board as a grid of cells, each
represented by a character (e.g., "B" for mine cells). The TUI Module is responsible for showing
the current state of the game, including the results of each round, such as win or loss
notifications. Users interact with the game by typing commands to specify cell coordinates (e.g.,
row,column), making the gameplay interactive and engaging.

6. Utility Module:

The Utility Module serves as a collection of helper functions that streamline various
functionalities within the game. It includes features for clearing the console, enhancing the visual
display of the game, and formatting output for improved user experience. This module also
manages player input by repeatedly prompting for valid choices until appropriate inputs are

24
received. Input validation is a crucial aspect of this module, ensuring that players cannot select
invalid cells or perform illegal actions, thus maintaining the integrity of the game.

7. Game Status Recording Module:

The Game Status Recording Module, specifically the Database Module, is tasked with
logging the outcome of each game session into a CSV file. This module handles all operations
related to recording statistics for each Minesweeper game played. It captures essential details
such as the game outcome (Win/Loss), player name, grid size, and mine count, storing them in a
structured format for tracking player performance over time. This feature not only allows players
to monitor their progress but also enhances the overall gaming experience by providing insights
into their gameplay history.

4.2 DFD DIAGRAMS


Data Flow Diagram Components

Processes:

● Display Main Menu: This process displays the main menu options for the player to
choose from different game modes.
● Set Game Mode: Based on the player’s choice, it determines the grid size and the
number of mines.
● Initialize Game: This process creates the game grid and randomly places mines while
setting the values for each cell based on adjacent mines.
● Play Game: This is the main game loop where the player makes moves, and the game
logic checks for wins or losses.
● Record Game Result: At the end of the game, whether won or lost, this process logs the
player's statistics into the CSV file for future reference and also displays the final
revealed grid to the player.

25
Data Stores:

● Game Statistics CSV: Stores game results (player name, grid size, mines, result, game
mode).

External Entities:

● Player: Interacts with the game, providing inputs such as name, game mode choice and
moves during the play and receiving outputs.

Data Flows:

● The player starts by entering their name and selecting a game mode.
● Based on the chosen mode, the grid is set up with mines and values.
● As the player makes moves, the game checks for valid inputs and updates the grid.
● if the player hits a mine, the game reveals all cells and records a loss. If they win, the
game also reveals all cells and records a win.
● Game results, including player name, grid size, number of mines, and result (win/loss),
are stored in a CSV file for tracking player statistics.

26
4.3 REQUIREMENTS SPECIFICATION
Software Requirements

● Programming Language:
○ Python (Version 3.x) is used for its simplicity and versatility.
● Text Editor/IDE:
○ Any Python-supported IDE, such as PyCharm, VSCode, or Jupyter
Notebook, can be utilized for development.

27
● Operating System:
○ The game is compatible with Windows, macOS, or Linux, ensuring broad
accessibility.
● Libraries:
○ The game will utilize libraries such as “random" and “csv” for essential
functionalities.

Hardware Requirements

● Processor:
○ A minimum of an Intel i3 or equivalent is required for smooth gameplay.
● RAM:
○ At least 4 GB of RAM is needed to ensure efficient performance during
play.
● Storage:
○ A minimum of 100 MB of free space is necessary for installation and
updates.

28
SYSTEM DESIGN

29
5.1 INPUT DESIGN
The input design outlines the various inputs that players can provide to interact with the
Minesweeper game effectively. It encompasses key elements such as player identification, game
mode selection, and validation processes to ensure a seamless gaming experience.

Player Name: A string input to capture the player's name. It serves as a key identifier in the
game statistics.

Game Mode Selection: A menu-driven input allowing players to choose between different game
modes:

● Easy (5x5 grid, 5 mines)


● Medium (8x8 grid, 12 mines)
● Hard (12x12 grid, 30 mines)
● Shuffle (Random mode from Easy, Medium, or Hard)
● Custom (User-defined grid size and number of mines)

Coordinates (Row and Column) Selection: Players enter two numbers (e.g., 1 1) to select a cell
in the grid.

Validation: Input must be validated for:

● Player name (not empty)


● Game mode selection (must be a valid option)
● Valid grid size (minimum of 2)
● Valid number of mines (greater than 0 and less than total cells in the grid)
● Row and column indices (within valid range based on grid size)

5.2 OUTPUT DESIGN


Output design focuses on the information and feedback generated by the game in
response to player actions. It includes visual representations of the game state, game statistics,
and messages that enhance player engagement and provide clarity on game outcomes.

30
Game Outputs:

● Minesweeper Grid: A visual representation of the grid displayed in the console after
each move, showing:
○ Revealed cells (numbers indicating adjacent mines or empty spaces)
○ Hidden cells as empty spaces until revealed
○ Game status messages (e.g., "Game Over!", "You Win!")

Game Statistics:

● After the game, results are recorded in a CSV file with the following columns:
○ Player Name
○ Grid Size
○ Number of Mines
○ Result (Win or Lost)
○ Game Mode

Instructions and Messages:

● Clear instructions on how to play the game.


● Error messages for invalid inputs.
● Displays messages for winning or losing the game.

5.3 DATABASE DESIGN


The database design details the structure and organization of game statistics stored in a
CSV file. This design ensures that vital data is captured accurately for analysis and future
reference, allowing for insights into player performance and preferences in the Minesweeper
game.

CSV File Structure:

The game statistics are stored in a CSV file named “game_stats.csv”. The structure
includes the following columns:

31
Column Name Data Type Description

Player Name String The name of the player who played the game.

Grid Size Integer The size of the grid, represented as the number of
rows/columns (e.g., 5).

Mines Integer The number of mines that were placed on the grid.

Result String Indicates whether the player won or lost the game (e.g.,
"Win" or "Lose").

Game Mode String The mode in which the game was played (Easy, Medium,
Hard, Shuffle, Custom).

5.4 FORM DESIGN


In a console-based game like Minesweeper, user interaction is primarily conducted
through text-based input and output.

Text Input for Player Name:

The game prompts the player to enter their name. This input is essential for personalizing
the gaming experience and is captured via a simple text prompt.

Game Mode Selection:

Players are presented with a menu-driven interface to choose the game mode. The
available options are displayed as a numbered list, making it easy for players to select their
preferred mode by entering the corresponding number.

32
Coordinate Selection:

After the game mode is selected, players are prompted to enter the coordinates of the cell
they wish to reveal. The input format is clearly specified to avoid confusion.

Validation Feedback:

Each input is validated in real time, with error messages displayed immediately if the
input is invalid. For instance, if a player attempts to enter a non-numeric value for coordinates,
the game responds with: “Invalid input! Please enter numbers for row and column.”

Game Status Updates:

Throughout the game, the console displays the updated Minesweeper grid after each
move.

Final Output:

After the game concludes, the console displays the revealed grid, showcasing the final
state of the game. This grid visualizes the outcome of the player’s moves, highlighting the
locations of revealed cells, adjacent mines, and any remaining hidden cells. Alongside the grid, a
message indicates whether the player won or lost, providing clear feedback on their performance.

33
CONCLUSION AND FUTURE ENHANCEMENTS

34
6.1 CONCLUSION
The Minesweeper game project successfully delivers an engaging and immersive
gameplay experience that captures the essence of the classic Minesweeper game. Through the
implementation of accurate mine placement and robust cell revealing mechanics, players can
navigate the game grid with a sense of strategy and anticipation. The inclusion of well-defined
winning conditions ensures that players have clear objectives, enhancing the overall satisfaction
of successfully completing a game. The game's design allows players to choose from various
difficulty levels, accommodating both novices and seasoned players alike, while also offering
customization options that tailor the gameplay to individual preferences. This flexibility fosters
an enjoyable and personalized experience, encouraging players to return for multiple sessions.

Furthermore, the seamless integration of core features such as effective mine detection,
neighboring cell reveal logic, and clearly defined game-over conditions demonstrates the
project’s technical proficiency and attention to detail. This Minesweeper project serves not only
as an engaging game but also as an excellent exercise in game development using Python,
providing valuable insights into coding practices, game logic design, and user experience
considerations.

6.2 FUTURE ENHANCEMENTS


To elevate the Minesweeper game experience, several exciting enhancements are planned
for future development. First, Leaderboard Integration will be introduced to track player
performance and high scores, fostering a competitive environment among players. By allowing
users to compare their scores and achievements, this feature will motivate them to improve their
skills and aim for top positions on the leaderboard. Additionally, a Timed Mode will be
introduced, adding an extra layer of difficulty by challenging players to complete the game
within a specified time limit. This mode will test players' quick thinking and decision-making
skills under pressure, making the gameplay more thrilling. These enhancements are designed to
elevate the gameplay, boost user engagement, and create a more competitive and interactive
environment for all players. By focusing on these elements, the Minesweeper experience will
become more dynamic and enjoyable, ensuring greater engagement and replayability for players
of all skill levels.

35
APPENDIX

36
7.1 SAMPLE CODING
The following snippet demonstrates the core logic for the Minesweeper game.

SNIPPET:

import random

import os

import csv

# Path to the CSV file

CSV_FILE = "game_stats.csv"

# Initialize the CSV file with headers if it doesn't exist

if not os.path.exists(CSV_FILE):

with open(CSV_FILE, mode='w', newline='') as file:

writer = csv.writer(file)

writer.writerow(["Player Name", "Grid Size", "Mines", "Result", "Game Mode"])

# Function to record the game result in the CSV file

def record_game_result(player_name, grid_size, mines, result, game_mode):

with open(CSV_FILE, mode='a', newline='') as file:

writer = csv.writer(file)

writer.writerow([player_name, grid_size, mines, result, game_mode])

37
# Function to clear the console

def clear_console():

os.system("clear") # Use "cls" if running on Windows

# Function to print the Minesweeper grid layout with a formatted border

def print_mines_layout(grid, revealed):

print("\n\t\t\t 🔍💣 MINESWEEPER 💣🔍\n")


n = len(grid)

# Print column numbers at the top with a fixed width for alignment

col_header = " " # Initial spacing for row labels

for i in range(n):

col_header += f" {i + 1:<3}" # Column numbers with fixed width of 3 spaces

print(col_header)

# Print the top border line

top_border = " " # Initial spacing for row labels

for col in range(n):

top_border += "______"

print(top_border)

38
# Print the rows with their contents

for r in range(n):

# Print the top empty line for each row

row_empty = " "

for col in range(n):

row_empty += "| " # Empty line before each row's content

print(row_empty + "|")

# Print row number and the cell values, with fixed spacing for grid values

row_content = f" {r + 1:<2} " # Left align row number with a width of 2

for col in range(n):

if revealed[r][col]:

cell_value = str(grid[r][col]) if grid[r][col] != 0 else "0" # Display empty space for 0

row_content += f"| {cell_value:<2} " # Center-align the cell value with fixed width

else:

row_content += "| " # Empty cell space if not revealed

print(row_content + "|")

# Print the bottom border for each row

row_border = " "

for col in range(n):

row_border += "|_____"

print(row_border + '|')

39
# Function to randomly place mines on the grid

def set_mines(grid, num_mines):

n = len(grid)

count = 0

while count < num_mines:

row = random.randint(0, n - 1)

col = random.randint(0, n - 1)

if grid[row][col] != 'B':

grid[row][col] = 'B'

count += 1

# Function to set the numbers on the grid based on mine locations

def set_values(grid):

n = len(grid)

for r in range(n):

for c in range(n):

if grid[r][c] == 'B':

continue

40
# Count mines in adjacent cells

count = 0

for i in range(max(0, r - 1), min(n, r + 2)):

for j in range(max(0, c - 1), min(n, c + 2)):

if grid[i][j] == 'B':

count += 1

# Assign count to cell, but cap the value at 2

grid[r][c] = min(count, 2)

# Function to reveal all cells when the game is over

def reveal_all(grid, revealed):

for r in range(len(grid)):

for c in range(len(grid)):

revealed[r][c] = True

# Recursive function to reveal zero-valued cells and their neighbors

def reveal_neighbours(grid, revealed, r, c):

if revealed[r][c] or grid[r][c] == 'B':

return

revealed[r][c] = True

41
if grid[r][c] == 0:

for i in range(max(0, r - 1), min(len(grid), r + 2)):

for j in range(max(0, c - 1), min(len(grid), c + 2)):

reveal_neighbours(grid, revealed, i, j)

# Function to check if the game is won

def check_winner(grid, revealed):

for r in range(len(grid)):

for c in range(len(grid)):

if grid[r][c] != 'B' and not revealed[r][c]:

return False

return True

# Function to initialize and set up the game grid

def initialize_game(grid_size, mines_no):

# Initialize the grid and revealed state

# Create an empty grid with initial values of 0

grid = []

for _ in range(grid_size):

row = [0] * grid_size # Create a row with n zeros

42
grid.append(row)

# Create an empty revealed grid with initial values of False

revealed = []

for _ in range(grid_size):

row = [False] * grid_size # Create a row with n False values

revealed.append(row)

# Place mines and set values

set_mines(grid, mines_no)

set_values(grid)

return grid, revealed

# Function to display the main menu and get user's choice

def display_main_menu():

while True:

clear_console()

print("\n🎉 Welcome to the Minesweeper Challenge! 💣😃")


print("\n🗂️ Choose a game mode:")

print("1. 🌿 Easy")

print("2. 🌼 Medium")

print("3. 🌋 Hard")

43
print("4. 🎲 Shuffle (Random mode)")
print("5. 🛠️ Custom")

print("6. ❌ Exit")

# Get user choice for game mode

choice = input("\n 🔢 Enter the number of the mode you want to play: ")
if choice in ['1', '2', '3', '4', '5', '6']:

return choice

else:

print("\n ⚠️ Invalid choice! Please enter a valid option. ⚠️")

# Function to set the game mode based on user's choice

def set_game_mode(choice):

if choice == '1':

return 5, 5, "Easy" # Return mode as well

elif choice == '2':

return 8, 8, "Medium" # Return mode as well

elif choice == '3':

return 12, 12, "Hard" # Return mode as well

44
elif choice == '4':

# Shuffle mode - randomly select from Easy, Medium, or Hard

grid_size, mines_no = random.choice([(5, 5), (8, 8), (12, 12)])

print(f"\n 🎲 Shuffle mode selected: Grid size {grid_size}, Mines {mines_no}")


return grid_size, mines_no, "Shuffle" # Return mode as well

elif choice == '5':

while True:

grid_size = int(input("\n 🔢 Enter the grid size (minimum 2): "))


# Validate grid size

if grid_size < 2:

print("\n ⚠️ Grid size must be at least 2.")


continue # Prompt for grid size again

while True:

mines_no = int(input("\n 💣 Enter the number of mines: "))


# Validate number of mines

if mines_no <= 0 or mines_no >= grid_size * grid_size:

print("\n ⚠️ Invalid number of mines! Please enter a positive number less than total
cells.")

else:

45
# If both inputs are valid, return the values

return grid_size, mines_no, "Custom" # Return mode as well

elif choice == '6':

exit()

# Main function to run the game

def main():

player_name = input("\n ✨ Please share your name ✨: ")


while True:

choice = display_main_menu()

if choice == '6':

clear_console()

print("\n 👋 Thanks for defusing mines with us! Until next time, goodbye! 🎉⛏️\n")
break

# Set the grid size and number of mines based on mode

grid_size, mines_no, game_mode = set_game_mode(choice)

# Initialize game grid and revealed state

grid, revealed = initialize_game(grid_size, mines_no)

46
print("\n 📝 Instructions: \nEnter row and column number to select a cell (e.g., '1 1').")
game_over = False

# Game loop

while not game_over:

print_mines_layout(grid, revealed)

inp = input("\n 🔍 Enter row and column number (e.g., '1 1'): ").split()
# Check if the input has exactly 2 numbers

if len(inp) != 2:

clear_console()

print("\n ⚠️ Invalid input! Please enter two numbers separated by a space.")


continue

# Check if both inputs are integers

if inp[0].isdigit() and inp[1].isdigit():

row, col = int(inp[0]) - 1, int(inp[1]) - 1

else:

clear_console()

print("\n ⚠️ Invalid input! Please enter valid numbers.")


continue

47
# Check if row and column are within the valid range

if row < 0 or row >= grid_size or col < 0 or col >= grid_size:

clear_console()

print("\n ⚠️ Invalid input! Please enter numbers within the grid.")


continue

# Check if the user hit a mine

if grid[row][col] == 'B':

revealed[row][col] = True

reveal_all(grid, revealed)

print_mines_layout(grid, revealed)

record_game_result(player_name, grid_size, mines_no, "Lost", game_mode)

print("\n 💥 Oops! You stepped on a mine! 💣💥 Game Over!")


game_over = True

else:

reveal_neighbours(grid, revealed, row, col)

# Check for a win only if the game is not over

if check_winner(grid, revealed):

reveal_all(grid, revealed)

print_mines_layout(grid, revealed)

record_game_result(player_name, grid_size, mines_no, "Win", game_mode)

print("\n 🎉 🏆 Well done! You've safely cleared the minefield! 💣✅😎")


48
game_over = True

# Ask if the user wants to play again or exit

while True:

play_again = input("\n 🔄 Want to challenge yourself again? (Y/N) 🎮: ").lower()


if play_again == 'y':

break

elif play_again == 'n':

clear_console()

print("\n 🙌 Great game! Thank you for playing. See you soon! 👋😊\n")
return

else:

print("\n ⚠️ Invalid input. Please enter 'Y' or 'N'.")


if __name__ == '__main__':

main()

7.2 SAMPLE OUTPUT


The sample output showcases the Minesweeper game grid, game setup panel, custom
config panel, game play screen displaying revealed cells, and game-over or victory messages
based on player actions.

49
Game Setup Screen:

Game Play Screen:

50
Custom Config Screen:

Game Status - Database:

7.3 BIBLIOGRAPHY
● https://iq.opengenus.org/minesweeper-strategy/
● https://www.coolmathgames.com/blog/how-to-play-minesweeper

51

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy