用c语言写一个简易的扫雷游戏
//game.h
#define _CRT_SECURE_NO_WARNINGS 1
#ifndef __GAME_H__
#define __GAME_H__
#include<stdio.h>
#include <stdlib.h>
#include<time.h>
#include<string.h>
#define rows 11
#define cols 11
#define Count 10
#define col (cols-2)
#define row (rows-2)
int menu();//菜单函数
void display(char show[rows][cols]);
int Game(char mine[rows][cols],char show[rows][cols]);//游戏
void set_mine(char mine[rows][cols]);//设置雷的位置
int Sweep(char mine[rows][cols],char show[rows][cols]);//开始扫雷
void move(char mine[rows][cols], int x, int y);
int get_num(char mine[rows][cols],int x,int y);//计算雷的个数
#endif//__GAME_H__
//game.c #include"game.h" //菜单函数 int menu() { printf("*******************************\n"); printf("*******1. play 0. exit********\n"); printf("*******************************\n"); return 0; } //设置雷的位置 void set_mine(char mine[rows][cols]) { int count=Count; int x=0; int y=0; srand((unsigned)time(NULL)); while (count) { x=rand()%9+1; y=rand()%9+1; if(mine[x][y]=='0') { mine[x][y]='1'; count--; } } } //打印下棋完了显示的界面 void display(char show[rows][cols]) { int i=0; int j=0; printf(" "); for(i=1;i<cols-1;i++) { printf("%d ",i); } printf("\n"); for(i=1;i<rows-1;i++) { printf("%d ",i); for(j=1;j<cols-1;j++) { printf("%c ",show[i][j]); } printf("\n"); } } //计算雷的个数 int get_num(char mine[rows][cols],int x,int y) { return mine[x-1][y+1]+mine[x-1][y]+mine[x-1][y-1]+ mine[x][y-1]+mine[x+1][y-1]+mine[x+1][y]+ mine[x+1][y+1]+mine[x][y+1]-8*'0'; } //扫雷 保证第一步不会踩到雷 int Sweep(char mine[rows][cols],char show[rows][cols]) { int count=0; int x=0; int y=0; int i=1; int x1=0; int y1=0; while(count!=(row*col-Count)) { printf("请输入坐标:"); scanf("%d%d",&x,&y); while (i==1) { i++; if(mine[x][y]=='1') { mine[x][y]='0'; while(1) { x1=rand()%9+1; y1=rand()%9+1; if(mine[x1][y1]='0') { mine[x1][y1]='1'; break; } } } } //display(show); //display(mine); if(mine[x][y]=='1') { printf("你踩到雷了!\n"); return 0; } else { int ret=get_num(mine,x,y); show[x][y]=ret+'0'; //set_mine(mine); display(show); count++; } } printf("恭喜你赢了!\n"); display(mine); return 0; } //游戏 int Game(char mine[rows][cols],char show[rows][cols]) { int x=0,y=0; set_mine(mine); display(show); //display(mine);//可以将雷的位置显示出来 Sweep(mine,show); //move(mine,x,y); return 0; }
//text.c #include "game.h" int main() { int input=0; char mine[rows][cols]; char show[rows][cols]; int i; int j; for(i=0;i<rows-1;i++) { for(j=0;j<cols-1;j++) { mine[i][j]='0'; show[i][j]='*'; } } do { menu(); printf("请选择:"); scanf("%d",&input); switch(input) { case 1: Game(mine,show); break; case 0: break; default: printf("选择错误!"); break; } } while (input); return 0; }
这个简易扫雷游戏,能确保第一步不被炸死,如果第一步踩到雷,程序就会自动自动把雷移走。