C/C++——游戏界面设置(graphics)

实现效果如图:

在这里插入图片描述

代码如下:

#include<stdio.h>
#include<graphics.h>
#include<conio.h>
#include<string.h>
//按钮属性
typedef struct Button
{
    
    
	int x;
	int y;
	int xx;
	int yy;
	COLORREF color;
	char* buttonstr;
}*LPBTN;
//按键封装
LPBTN createButton(int x, int y, int xx, int yy, COLORREF color, const char* buttonstr)
{
    
    
	LPBTN button = (LPBTN)malloc(sizeof(LPBTN));
	button->x = x;
	button->y = y;
	button->xx = xx;
	button->yy = yy;
	button->color = color;
	button->buttonstr = (char*)malloc(sizeof(char));
	strcpy(button->buttonstr, buttonstr);

	return button;
}
//绘制按钮
void drawButton(LPBTN button)
{
    
    
	setfillcolor(button->color);//设置当前设备填充颜色
	fillrectangle(button->x, button->y, button->xx, button->yy);
	setbkmode(TRANSPARENT); //设置透明背景
	setlinecolor(BLACK);//设置画线颜色
	settextstyle(30, 0, "楷体"); //设置图形文本当前字体、字符大小
	outtextxy(button->x + 15, button->y + 10, button->buttonstr);//输出图形文本字符串
}
//鼠标是否在按钮上
int isInButton(LPBTN button, MOUSEMSG m)
{
    
    
	if (button->x <= m.x && button->xx >= m.x && button->y <= m.y && button->yy >= m.y)
	{
    
    
		return 1;
	}
	return 0;
}
/*---------鼠标作用前面呈现颜色------------*/
void buttonAction(LPBTN button, MOUSEMSG m)
{
    
    
	if (isInButton(button, m))
	{
    
    
		button->color = RED;
	}
	else
	{
    
    
		button->color = BLUE;
	}
}
int main()
{
    
    
	//调用绘制按钮函数
	LPBTN play = createButton(300, 200, 450, 250, BLUE, "开始游戏");
	LPBTN pause = createButton(300, 260, 450, 310, BLUE, "暂停游戏");
	LPBTN resume = createButton(300, 320, 450, 370, BLUE, "继续游戏");
	LPBTN close = createButton(300, 380, 450, 430, BLUE, "退出游戏");
	initgraph(800, 500);
	IMAGE picture;
	loadimage(&picture, "background.jpg", 800, 500);
	putimage(0, 0, &picture);

	MOUSEMSG m;
	while (1)
	{
    
    
		BeginBatchDraw();//批量绘图,消除屏幕闪烁

/*-----------绘制按钮样式----------*/
		drawButton(play);
		drawButton(pause);
		drawButton(resume);
		drawButton(close);

		m = GetMouseMsg();//获取鼠标信息
/*---------鼠标作用前面呈现颜色------------*/
		buttonAction(play, m);
		buttonAction(pause, m);
		buttonAction(resume, m);
		buttonAction(close, m);

		EndBatchDraw();
	}
	getch();
	closegraph();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_53391957/article/details/116333969