Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Modular Implementation of Console-Based Minesweeper in C

Tech May 17 1

Project Architecture

To achieve high maintainability and scalability, the game logic is divided into separate compilation units. A header file defines interfaces and constants, while source files handle implementation details. Padding the board arrays by two units (one on each side) prevents boundary check errors when calculating neighboring cell values.

1. Header Configuraton

Define the board dimensions and mine count using preprocessor macros. This allows for easy adjustment of grid size without modifying core logic.

#ifndef GAME_H
#define GAME_H

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define BOARD_SIZE 9
#define TOTAL_MINES 10
#define ARRAY_WIDTH (BOARD_SIZE + 2)
#define ARRAY_HEIGHT (BOARD_SIZE + 2)

// Function Declarations
void init_board(char board[ARRAY_HEIGHT][ARRAY_WIDTH], int rows, int cols, char val);
void show_board(const char board[ARRAY_HEIGHT][ARRAY_WIDTH], int rows, int cols);
void place_mines(char mines[ARRAY_HEIGHT][ARRAY_WIDTH], int rows, int cols);
void play_game(char mines[ARRAY_HEIGHT][ARRAY_WIDTH], char display[ARRAY_HEIGHT][ARRAY_WIDTH], int rows, int cols);
int count_neighbors(char mines[ARRAY_HEIGHT][ARRAY_WIDTH], int x, int y);
void expand_area(char mines[ARRAY_HEIGHT][ARRAY_WIDTH], char display[ARRAY_HEIGHT][ARRAY_WIDTH], int x, int y, int* cleared_count);

#endif

2. Initialization and Display

The initialization routine fills the board with a specific character to mark safe or hidden states. The display function iterates through the array to render the current state to the user console.

void init_board(char board[ARRAY_HEIGHT][ARRAY_WIDTH], int rows, int cols, char val)
{
    for (int r = 0; r < rows; r++)
    {
        for (int c = 0; c < cols; c++)
        {
            board[r][c] = val;
        }
    }
}

void show_board(const char board[ARRAY_HEIGHT][ARRAY_WIDTH], int rows, int cols)
{
    printf("\n--- Minefield Status ---\n");
    // Print column headers
    for (int i = 0; i <= cols; i++) printf("%d ", i);
    printf("\n");
    
    // Print rows
    for (int i = 1; i <= rows; i++)
    {
        printf("%d ", i);
        for (int j = 1; j <= cols; j++)
        {
            printf("%c ", board[i][j]);
        }
        printf("\n");
    }
    printf("------------------------\n");
}

3. Random Mine Placement

Mines are distributed randomly using the standard library random number generator. A loop continues until the required number of mines is placed, ensuring no duplicates overwrite existing placements.

void place_mines(char mines[ARRAY_HEIGHT][ARRAY_WIDTH], int rows, int cols)
{
    int count = TOTAL_MINES;
    while (count > 0)
    {
        int x = rand() % rows + 1;
        int y = rand() % cols + 1;
        if (mines[x][y] == '0')
        {
            mines[x][y] = '1';
            count--;
        }
    }
}

4. Game Logic and Neighbor Counting

The core logic involves validating user input against board boundaries and checking previous exploration status. If a clicked cell contains a mine, the game ends immediately. Otherwise, it calculates adjacent mines.

int count_neighbors(char mines[ARRAY_HEIGHT][ARRAY_WIDTH], int x, int y)
{
    int sum = 0;
    sum += mines[x - 1][y];     top
    sum += mines[x - 1][y - 1]; top-left
    sum += mines[x][y - 1];     left
    sum += mines[x + 1][y - 1]; bottom-left
    sum += mines[x + 1][y];     bottom
    sum += mines[x + 1][y + 1]; bottom-right
    sum += mines[x][y + 1];     right
    sum += mines[x - 1][y + 1]; top-right
    
    return sum - (8 * '0'); // Subtract ASCII offset
}

5. Recursive Expansion

When a player clicks an empty area containing zero neighbors, the system recursively exposes all surrounding open cells. This flood-fill algorithm ensures that large safe zones are revealed instantly.

void expand_area(char mines[ARRAY_HEIGHT][ARRAY_WIDTH], char display[ARRAY_HEIGHT][ARRAY_WIDTH], int x, int y, int* cleared_count)
{
    // Boundary Check
    if (x >= 1 && x <= BOARD_SIZE && y >= 1 && y <= BOARD_SIZE)
    {
        if (display[x][y] == '*')
        {
            int adj_mines = count_neighbors(mines, x, y);
            display[x][y] = adj_mines > 0 ? adj_mines + '0' : ' ';
            
            (*cleared_count)++;
            
            // Recurse if space is clear
            if (adj_mines == 0)
            {
                for (int i = x - 1; i <= x + 1; i++)
                {
                    for (int j = y - 1; j <= y + 1; j++)
                    {
                        expand_area(mines, display, i, j, cleared_count);
                    }
                }
            }
        }
    }
}

6. Main Execution Flow

The main function manages the lifecycle of the application, including menu navigation and game looping. It initializes the random seed and handles user choices to start or terminate the process.

int main()
{
    srand((unsigned int)time(NULL));
    int choice = 0;

    do
    {
        printf("\n=== MINESWEEPER ===\n");
        printf("1. Play Game\n");
        printf("0. Exit\n");
        printf("Enter Choice: ");
        scanf("%d", &choice);

        switch (choice)
        {
        case 1:
        {
            char mines[ARRAY_HEIGHT][ARRAY_WIDTH];
            char display[ARRAY_HEIGHT][ARRAY_WIDTH];
            int win_count = 0;

            init_board(mines, ARRAY_HEIGHT, ARRAY_WIDTH, '0');
            init_board(display, ARRAY_HEIGHT, ARRAY_WIDTH, '*');
            
            place_mines(mines, BOARD_SIZE, BOARD_SIZE);
            
            play_game(mines, display, BOARD_SIZE, BOARD_SIZE);
            break;
        }
        case 0:
            printf("Goodbye!\n");
            break;
        default:
            printf("Invalid selection.\n");
        }
    } while (choice != 0);

    return 0;
}

7. Interactive Loop Implementation

This function orchestrates the turn-by-turn gameplay. It validates coordinates, checks for wins based on cleared cells, and updates the display dynamically.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.