用C语言实现扫雷游戏(二)

上次完成扫雷的布局后,此次加入了雷的描绘,雷的产生以及简化主函数。

#include<graphics.h>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

#define MINE_YES -1 

void init_system();
void init_globals();
void close_system();
void test_data();
void set_mines();
void draw_mine_area();
void draw_box(int x,int y,int w,int h,int depth);
void draw_mine(int x,int y);

int m_y0,m_x0,m_w,m_h,m_col,m_row;
int *m_pMines;
int m_num;


void main()
{
	init_system();
	draw_mine_area();
	set_mines();
	test_data();
	getch();
	close_system();
}

void init_system()
{
	m_row=20,m_col=30,m_w=30,m_h=30;
	m_pMines=NULL;
	m_num=50;
	init_globals();
}

void init_globals()
{
	int w,h;
	m_x0=m_w+m_w/2,m_y0=m_h+m_h+m_h/2;
	m_pMines=(int *)malloc(sizeof(int)*m_row*m_col);
	w=(m_w+1)*m_col+3*m_w-1;
	h=(m_h+1)*m_row+4*m_h-1;
	initgraph(w,h);
}

void close_system()
{
	closegraph();
	free(m_pMines);
}

void test_data()
{
	int i,j,k=0;
	int x,y;
	y=m_y0;
	for(i=0;i<m_row;i++)
	{
		x=m_x0;
		for(j=0;j<m_col;j++)
		{
			if(m_pMines[k]==MINE_YES)
			{
				draw_mine(x,y);
			}
			k++;
			x+=m_w+1;
		}
		y+=m_h+1;
	}
}

void set_mines()
{
	int i,k,m;
	m=m_row*m_col;
	for(i=0;i<m;i++) m_pMines[i]=0;
	srand(time(NULL));
	i=0;
	while(i<m_num)
	{
		k=rand()%m;
		if(m_pMines[k]!=MINE_YES)
		{
			m_pMines[k]=MINE_YES;
			i++;
		}
	}
}

void draw_mine_area()
{
	int i,j;
	int x,y;
	int x1,y1,x2,y2,w,h;
	setfillstyle(BS_SOLID);
	setfillcolor(LIGHTGRAY);
	x1=m_x0-m_w;
	y1=m_y0-m_h-m_h;
	x2=m_x0+(m_w+1)*m_col+m_w-1;
	y2=m_y0+(m_h+1)*m_row+m_h-1;
	fillrectangle(x1,y1,x2,y2);

	x1=m_x0-3;
	y1=m_y0-3;
	w=x2-x1-m_w+3;
	h=y2-y1-m_h+3;
	draw_box(x1,y1,w,h,-3);

	x1=m_x0-3;
	y1=m_y0-m_h-m_h/2;
	w=3*m_w;
	h=m_h;
	draw_box(x1,y1,w,h,-3);

	x1=x2-4*m_w;
	y1=m_y0-m_h-m_h/2;
	w=3*m_w;
	h=m_h;
	draw_box(x1,y1,w,h,-3);

	y=m_y0;
	for(i=0;i<m_row;i++)
	{
		x=m_x0;
		for(j=0;j<m_col;j++)
		{
			draw_box(x,y,m_w,m_h,3);
			x+=m_w+1;
		}
		y+=m_h+1;
	}
}

void draw_box(int x,int y,int w,int h,int depth)
{
	int k,mdepth;
	setfillstyle(BS_SOLID);
	setfillcolor(LIGHTGRAY);
	fillrectangle(x,y,x+w,y+h);
	if(depth>=0) mdepth=depth;
	else         mdepth=-depth;

	if(depth>=0) setcolor(WHITE);
	else         setcolor(DARKGRAY);
	for(k=0;k<mdepth;k++)
	{
		line(x,y+k,x+w,y+k);
		line(x+k,y,x+k,y+h);
	}
	if(depth>=0) setcolor(DARKGRAY);
	else         setcolor(WHITE);
	for(k=0;k<mdepth;k++)
	{
		line(x+w-k,y+k,x+w-k,y+h-k);
		line(x+k,y+h-k,x+w-k,y+h-k);
	}
}

void draw_mine(int x,int y)
{
	draw_box(x,y,m_w,m_h,-2);
	setlinestyle(PS_SOLID,1);
	setlinecolor(BLACK);
	setfillstyle(BS_SOLID);
	setfillcolor(BLACK);
	fillcircle(x+m_w/2,y+m_h/2,m_w/3);
}

猜你喜欢

转载自blog.csdn.net/nidie508/article/details/88953617
今日推荐