C語言/c++寫的C語言實戰項目掃雷
結構比較清晰,僅供參考:
核心是掃雷的遞歸算法實現
上代碼:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>#define SIZE 10
#define MINES 15char board[SIZE][SIZE]; // 游戲棋盤// 初始化棋盤,'-'表示未揭示的區域
void initBoard() {for (int i = 0; i < SIZE; ++i) {for (int j = 0; j < SIZE; ++j) {board[i][j] = '-';}}
}// 在棋盤上顯示當前狀態
void displayBoard() {printf(" ");for (int i = 0; i < SIZE; ++i) {printf("%d ", i);}printf("\n");for (int i = 0; i < SIZE; ++i) {printf("%d ", i);for (int j = 0; j < SIZE; ++j) {printf("%c ", board[i][j]);}printf("\n");}
}// 隨機布置地雷
void placeMines() {srand(time(NULL));int count = 0;while (count < MINES) {int x = rand() % SIZE;int y = rand() % SIZE;if (board[x][y] != '*') {board[x][y] = '*';count++;}}
}// 檢查坐標是否有效
int isValid(int x, int y) {return (x >= 0 && x < SIZE && y >= 0 && y < SIZE);
}// 計算周圍的地雷數量
int countAdjacentMines(int x, int y) {int count = 0;for (int i = x - 1; i <= x + 1; ++i) {for (int j = y - 1; j <= y + 1; ++j) {if (isValid(i, j) && board[i][j] == '*') {count++;}}}return count;
}// 揭示某個位置的內容
void reveal(int x, int y) {if (!isValid(x, y)) {return;}if (board[x][y] != '-') {return;}int mines = countAdjacentMines(x, y);if (mines > 0) {board[x][y] = mines + '0';} else {board[x][y] = ' ';for (int i = x - 1; i <= x + 1; ++i) {for (int j = y - 1; j <= y + 1; ++j) {reveal(i, j);}}}
}int main() {int x, y;char action;initBoard();placeMines();do {displayBoard();printf("Enter action (r for reveal, q to quit): ");scanf(" %c", &action);if (action == 'r') {printf("Enter coordinates (x y): ");scanf("%d %d", &x, &y);if (isValid(x, y)) {reveal(x, y);} else {printf("Invalid coordinates!\n");}} else if (action == 'q') {printf("Quitting game.\n");break;} else {printf("Invalid action!\n");}} while (1);return 0;
}