Mine Sweeper Game
Mine Sweeper Game
Submitted By
AKASH S
(Reg. No. 2428C0006)
OCTOBER 2024
1
CERTIFICATE
2
CERTIFICATE
EXAMINER
3
DECLARATION
4
DECLARATION
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.
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
2 Review of Literature
2.2 Limitation 17
3 System Study
4 System Analysis
5 System Design
9
5.2 Output Design 30
6.1 Conclusion 35
7 Appendix
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
Coordinates (Row and Column) Selection: Players enter two numbers (e.g., 1 1) to select a cell
in the grid.
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
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).
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.
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.”
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.
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
CSV_FILE = "game_stats.csv"
if not os.path.exists(CSV_FILE):
writer = csv.writer(file)
writer = csv.writer(file)
37
# Function to clear the console
def clear_console():
# Print column numbers at the top with a fixed width for alignment
for i in range(n):
print(col_header)
top_border += "______"
print(top_border)
38
# Print the rows with their contents
for r in range(n):
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
if revealed[r][col]:
row_content += f"| {cell_value:<2} " # Center-align the cell value with fixed width
else:
print(row_content + "|")
row_border += "|_____"
print(row_border + '|')
39
# Function to randomly place mines on the grid
n = len(grid)
count = 0
row = random.randint(0, n - 1)
col = random.randint(0, n - 1)
if grid[row][col] != 'B':
grid[row][col] = 'B'
count += 1
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
if grid[i][j] == 'B':
count += 1
grid[r][c] = min(count, 2)
for r in range(len(grid)):
for c in range(len(grid)):
revealed[r][c] = True
return
revealed[r][c] = True
41
if grid[r][c] == 0:
reveal_neighbours(grid, revealed, i, j)
for r in range(len(grid)):
for c in range(len(grid)):
return False
return True
grid = []
for _ in range(grid_size):
42
grid.append(row)
revealed = []
for _ in range(grid_size):
revealed.append(row)
set_mines(grid, mines_no)
set_values(grid)
def display_main_menu():
while True:
clear_console()
print("1. 🌿 Easy")
print("2. 🌼 Medium")
print("3. 🌋 Hard")
43
print("4. 🎲 Shuffle (Random mode)")
print("5. 🛠️ Custom")
print("6. ❌ Exit")
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:
def set_game_mode(choice):
if choice == '1':
44
elif choice == '4':
while True:
if grid_size < 2:
while True:
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
exit()
def main():
choice = display_main_menu()
if choice == '6':
clear_console()
print("\n 👋 Thanks for defusing mines with us! Until next time, goodbye! 🎉⛏️\n")
break
46
print("\n 📝 Instructions: \nEnter row and column number to select a cell (e.g., '1 1').")
game_over = False
# Game loop
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()
else:
clear_console()
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()
if grid[row][col] == 'B':
revealed[row][col] = True
reveal_all(grid, revealed)
print_mines_layout(grid, revealed)
else:
if check_winner(grid, revealed):
reveal_all(grid, revealed)
print_mines_layout(grid, revealed)
while True:
break
clear_console()
print("\n 🙌 Great game! Thank you for playing. See you soon! 👋😊\n")
return
else:
main()
49
Game Setup Screen:
50
Custom Config Screen:
7.3 BIBLIOGRAPHY
● https://iq.opengenus.org/minesweeper-strategy/
● https://www.coolmathgames.com/blog/how-to-play-minesweeper
51