C/C++图形化编程(2)

2023-12-24 23:46:50

归纳编程学习的感悟,
记录奋斗路上的点滴,
希望能帮到一样刻苦的你!
如有不足欢迎指正!
共同学习交流!
🌎欢迎各位→点赞 👍+ 收藏? + 留言?📝
站在巨人的肩上是为了超过巨人!

一起加油!

?

目录

五、实现EasyX按键交互功能:

六、?实现EasyX中鼠标交互功能:


五、实现EasyX按键交互功能:

1.阻塞按键交互? ? ? ? 不按键就不运行,像C语言中的scanf函数,不输入,程序就不往下运行。

2.非阻塞按键交互? ? ? ? 不按键程序仍在运行

案例:

1.小球移动:

2.按键控制移动:

  • 双缓冲贴图(解决闪烁问题)
    • 开始双缓冲????????BeginBatchDraw();
    • 显示一帧? ? ? ? ? ?FlushBatchDraw();
    • 结束双缓冲? ? ? ?EndBatchDraw();
#include<stdio.h>
#include<graphics.h>
#include<time.h>
#include<conio.h>//_getch()函数	不需要回车确认函数,_kbhit()函数	判断存在按键再去处理
//定义球的结构体
struct Ball {
	int x;//球的坐标
	int y;
	int r;//球的半径
	int dx;//增量x
	int dy;//增量y
};
Ball ball = { 300,300,15,5,-4 };
Ball myball = {400,400,15,5,5};
void DrawBall(struct Ball ball) {//画球
	//给球填充颜色为红色
	setfillcolor(RED);
	//画出球
	solidcircle(ball.x, ball.y, ball.r);
}
void MoveBall() {//移动球
	if (ball.x - ball.r < 0 || ball.x + ball.r>=600) {
		ball.dx = -ball.dx;//撞左壁
	}
	if (ball.y - ball.r < 0 || ball.y + ball.r>=600) {
		ball.dy = -ball.dy;//撞右壁
	}
	ball.x += ball.dx;
	ball.y += ball.dy;
}
//定时器	去控制自动移动的东西
int Timer(int duration, int id) {
	static int startTime[10];//通过静态变量做10个定时器,静态变量自动被初始化
	int endTime = clock();//clock()函数统计程序运行到当前代码所需的时间
	if (endTime - startTime[id] > duration) {//触发定时器返回1
		startTime[id] = endTime;//开始时间改为上一次的结束时间
		return 1;
	}
	return 0;
}
void KeyDown() {//接收用户按键
	int useKey =_getch();
	switch (useKey) {
	case'w':
	case'W':
	case 72://小键盘的箭头上
		myball.y -= 5;
		break;
	case 's':
	case'S':
	case 80:
		myball.y += 5;
		break;
	case'a':
	case'A':
	case 75:
		myball.x -= 5;
		break;
	case'd':
	case'D':
	case 77:
		myball.x += 5;
		break;

	}
}
void KeyDown2() {//异步交互
	if (GetAsyncKeyState(VK_UP)) {
		myball.y -= 5;
	}
	if (GetAsyncKeyState(VK_DOWN)) {
		myball.y += 5;
	}
	if (GetAsyncKeyState(VK_LEFT)) {
		myball.x -= 5;
	}
	if (GetAsyncKeyState(VK_RIGHT)) {
		myball.x += 5;
	}
}
int main() {
	initgraph(600, 600);//创建800x800的窗口
	BeginBatchDraw();//双缓冲贴图,开始双缓冲
	while (1) {
		cleardevice();
		DrawBall(ball);
		DrawBall(myball);
		if (Timer(20, 0)) {
			MoveBall();
		}
		if (_kbhit()) {//判断存在按键再去处理
			KeyDown();
		}
		if (Timer(20, 1)) {
			KeyDown2();
		}
		FlushBatchDraw();//显示一帧
		//Sleep(20);//阻塞函数,做移动一般不用Sleep,他会阻塞整个程序,一般用定时器去做
	}
	EndBatchDraw();//结束双缓冲
	closegraph();
	return 0;
}

六、?实现EasyX中鼠标交互功能:

ExMassag类型的变量,去存储鼠标消息

获取鼠标消息:peekmassage(&变量)

讨论鼠标消息

  • msg.massage区分鼠标消息的类型
  • msg.x? ?msg.y鼠标的当前坐标
#include<graphics.h>
int main() {
	initgraph(600, 600);
	ExMessage msg;
	//按左键画圆,右键画方
	while (1) {
		while (peekmessage(&msg)) {
			switch (msg.message) {
				//windows massage left button down
			case WM_LBUTTONDOWN:
				circle(msg.x, msg.y, 10);
				break;
				//windows massage right button down
			case WM_RBUTTONDOWN:
				rectangle(msg.x - 10, msg.y - 10, msg.x + 10, msg.y + 10);
				break;
			}
		}
	}
	closegraph();
	return 0;
}

文章来源:https://blog.csdn.net/2301_80585598/article/details/135186144
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。