C语言实现简单的扫雷小游戏-完整代码

直接上代码

#define  _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void menu()
{
	printf("************\n");
	printf("***1.game***\n");
	printf("***0.exit***\n");
	printf("************\n");
}



void DIY(int* pN, int* pX)
{
T:
	printf("自定义棋盘长宽N:");
	scanf("%d", pN);
	printf("自定义雷的数量X:");
	scanf("%d", pX);
	if (*pN < 1 || *pX<1 || *pX >(*pN) * (*pN) - 1)
	{
		printf("error\n");
		goto T;
	}
}


char** create_board(int N)
{
	char** p = (char**)malloc(N * sizeof(char*));
	for (int i = 0; i < N; i++)
	{
		*(p + i) = (char*)malloc(N * sizeof(char));
	}
	return p;
}



void zero_board(char** p, int N, char sign)
{
	for (int i = 0; i < N; i++)
	{
		for (int j = 0; j < N; j++)
		{
			p[i][j] = sign;
		}
	}
}

void show_board(char** p, int N)
{
	for (int x = 0; x <= N; x++)
	{
		printf("%d ", x);
	}
	printf("\n");
	for (int i = 1; i <= N; i++)
	{
		printf("%d ", i);
		for (int j = 1; j <= N; j++)
		{
			printf("%c ", p[i][j]);
		}
		printf("\n");
	}
}


void set_boom(char** p, int N, int X)
{
	while (X)
	{
		int x = (rand() % N + 1);
		int y = (rand() % N + 1);
		if (p[x][y] == '0')
		{
			p[x][y] = '1';
			X--;
		}
	}
}


void check_boom(char** p1, char** p2, int N, int X)
{
	int left = N * N - X;
	while (left)
	{
		printf("输入坐标:");
		int x = 0;
		int y = 0;
		scanf("%d%d", &x, &y);
		if (x<1 || x>N || y<1 || y>N)
		{
			printf("error\n");
		}
		else if (p2[x][y] != '*')
		{
			printf("error\n");
		}
		else if (p1[x][y] == '1')
		{
			printf("BOOM!!!\n");
			show_board(p1, N);
			return;
		}
		else
		{
			p2[x][y] = count_boom(p1, x, y) + '0';
			show_board(p2, N);
			left--;
		}
	}
	if (!left)
	{
		printf("WIN!!!\n");
		show_board(p1, N);
	}
}


int count_boom(char** p, int x, int y)
{
	int count = 0;
	for (int i = -1; i <= 1; i++)
	{
		for (int j = -1; j <= 1; j++)
		{
			count += p[x + i][y + j] - '0';
		}
	}
	return count;
}




void game()
{
	int N, X;
	DIY(&N, &X);
	char** pb1 = create_board(N + 2);
	char** pb2 = create_board(N + 2);
	zero_board(pb1, N + 2, '0');
	zero_board(pb2, N + 2, '*');
	show_board(pb2, N);
	set_boom(pb1, N, X);
	check_boom(pb1, pb2, N, X);
}




int main()
{
	srand((unsigned int)time(NULL));
	int input = 0;
	while (1)
	{
		menu();
		scanf("%d", &input);
		switch (input)
		{
		case 1:
			game();
			break;
		case 0:
			printf("exit\n");
			return 0;
		default:
			printf("error\n");
		}
	}
}



这里只是为了各位更好的CV将代码放在了一起,当然,真正在写的时候建议分三个文件:

  • "game.h"用于声明函数
  • "game.c"用于创建函数
  • "test.c"用于放主函数
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值