直接上代码:
#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"用于放主函数