C语言实现扫雷
game.h
#ifndef _GAME_H_ #define _GAME_H_ #include<stdio.h> #include<stdlib.h> #include<time.h> #pragma warning(disable:4996) #define MINE_NUM 20 #define ROW 10 #define COL 10 void game(); #endifmain.c
#include"game.h" void menu() { printf("**********************\n"); printf("****1 play**0 exit****\n"); printf("**********************\n"); printf("Please select:\n"); } int main() { int n; do{ menu(); scanf("%d",&n); switch (n){ case 1:game(); break; case 0:exit(0); break; default: printf("请输入<1 or 0>"); break; } } while (1); system("pause"); return 0; }
game.c
#include"game.h" void display(char board[][COL+2], int row,int col) { int i; for (i = 0; i <= COL; i++) { board[0][i] = i; printf(" %d",board[0][i]); } printf("\n"); for (i = 0; i <= COL;i++) { printf("---"); } printf("\n"); for (i=1; i <=ROW; i++) { printf("%2d|",i); int j = 1; for (; j <= COL; j++) { printf("%2c|", board[i][j]); } printf("\n"); } } int get_random_num(int start, int end) { return rand() % (end - start + 1) + start;//生成随机数;eg(1,10)rand()%10==0~9;+start==1~10; } void set_mines(char mines[][COL+2],int row,int col) { int x, y; int num = MINE_NUM; srand((unsigned long)time(NULL)); do { x = get_random_num(1,ROW);//雷在内部数组雷区 y = get_random_num(1,COL); if (mines[x][y] = '0') { mines[x][y] = '1'; num--; } } while (num); } int get_mines(char mines[][COL + 2], int row, int col, int x, int y) { return (mines[x - 1][y - 1] - '0')+(mines[x - 1][y] - '0')+(mines[x - 1][y + 1] - '0')+ (mines[x][y - 1] - '0')+(mines[x][y +1] - '0')+(mines[x + 1][y - 1] - '0')+ (mines[x + 1][y] - '0')+(mines[x + 1][y + 1] - '0'); } void game() { int x, y; int count; char show[ROW+2][COL+2]; char mines[ROW+2][COL+2]; memset(show, '*', (ROW + 2)*(COL + 2)); memset(mines, '0', (ROW + 2)*(COL + 2)); set_mines(mines, ROW + 2, COL + 2); int win = 0; do{ system("CLS"); display(show, ROW + 2, COL + 2); printf("Please enter:<x,y>:\n"); scanf("%d%d", &x, &y); if (x >= 1 && x <= ROW && y >= 1 && y <= COL) { int count = get_mines(mines, ROW + 2, COL + 2, x, y);//查看x行y列有多少雷 if (mines[x][y] == '0') { //展开周围雷数或无雷 if (mines[x - 1][y - 1] == '0') { show[x - 1][y - 1] = '0'; } if (mines[x - 1][y] == '0') { show[x - 1][y] ='0'; } if (mines[x - 1][y + 1] == '0') { show[x - 1][y + 1] = count + '0'; } if (mines[x][y - 1] == '0') { show[x][y - 1] = '0'; } if (mines[x][y + 1] == '0') { show[x][y + 1] = '0'; } if (mines[x + 1][y - 1] == '0') { show[x + 1][y - 1] = count + '0'; } if (mines[x + 1][y] == '0') { show[x + 1][y] = count + '0'; } if (mines[x + 1][y + 1] == '0') { show[x + 1][y + 1] ='0'; } show[x][y] = count + '0';//count转字符型 写进show区,字符'0':48 // display(show, ROW + 2,COL+2); win++; if (win==ROW*COL-MINE_NUM)//检测完所有的空位置 { printf("you win!\n"); display(mines, ROW + 2, COL + 2); break; } } else { printf("Game Over!\n"); display(mines, ROW + 2,COL+2); break; } } else{ printf("Enter error! Please enter:<x,y>:\n"); } } while(1); }