VS2013下实现扫雷游戏的代码书写

创建头文件:
#ifndef _GAME_H_
#define _GAME_H_

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

#pragma warning(disable:4996)

#define ROW 10
#define COL 10
#define MINE_NUM 20

void game();
void setMines(char mine[][COL + 2], int row, int col);
int getMines(char mine[][COL + 2], int col, int row, int x, int y);

#endif
 
 
//main.c文件
#include "game.h"

void menu()
{
	printf("****************************\n");
	printf("****1.play        2.exit****\n");
	printf("****************************\n");
	printf("Please Select:\n");
}
int main()
{
	int select = 0;
	do{
		menu();
		scanf("%d", &select);
		switch (select){
		case 1:
			game();
			break;
		case 2:
			exit(0);
		default:
			break;

		}
	} while (1);
	system("pause");
	return 0;
}


//game.c文件
#include "game.h"

 static int getRandomNum(int start, int end)
{
	return rand() % (end - start + 1) + start;
}
void setMines(char mine[][COL + 2], int row, int col)
{
	int num = MINE_NUM;
	srand((unsigned long)time(NULL));
	do{
		int x = getRandomNum(1,ROW);
		int y = getRandomNum(1,COL);
		if (mine[x][y] == '0'){
			mine[x][y] = '1';
			num--;
		}
	} while (num);
}
int getMines(char mine[][COL + 2], int col, int row, int x, int y)
{
	return (mine[x - 1][y - 1] - '0') + \
		(mine[x - 1][y] - '0') + (mine[x - 1][y + 1] - '0') + \
		(mine[x][y - 1] - '0') + (mine[x][y + 1] - '0') + \
		(mine[x + 1][y - 1] - '0') + (mine[x + 1][y] - '0') + \
		(mine[x + 1][y + 1] - '0');
}
void display(char board[][COL + 2], int row, int col)
{
	printf("   ");
	int i = 1;
	for (; i <= COL; i++){
		printf("%3d", 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");
	}
}
void game()
{
	char mine[ROW + 2][COL + 2];
	char show[ROW + 2][COL + 2];

	memset(show, '*', (ROW + 2)*(COL + 2));
	memset(mine, '0', (ROW + 2)*(COL + 2));

	setMines(mine, (ROW + 2),(COL + 2));
	int win = 0;
	do{
		system("CLS");
		int x, y;
		display(show, ROW + 2, COL + 2);
		printf("Please Choose:<x,y>:");
		scanf("%d%d", &x, &y);
		if (x >= 1 && x <= ROW && y >= 1 && y <= COL){
			if (mine[x][y] == '1'){
				printf("Game Over!\n");
				display(mine, ROW + 2, COL + 2);
				break;
			}
			else{
				int count = getMines(mine,ROW+2,COL+2,x,y);
				show[x][y] = count + '0';
				win++;
				if (win == ROW*COL - MINE_NUM){
					printf("You Win!\n");
					display(mine, ROW + 2, COL + 2);
					break;
				}
			}
		}
		else{
			//printf("Enter  error! try again!\n");
		}
	} while (1);

}
运行此程序:


开始游戏:


游戏结束,重开请按1,退出请按2!


猜你喜欢

转载自blog.csdn.net/chengx1996/article/details/80033694