赞
踩
eg1:使用键盘的上下左右按钮控制小球的上下左右移动
#include <stdio.h> #include <easyx.h> #include <iostream> #include <math.h> #include <conio.h> #define PI 3.14 int main() { // 键盘交互 initgraph(800, 600); setorigin(400, 300); setaspectratio(1, -1); setbkcolor(RGB(164, 225, 202)); cleardevice(); setfillcolor(WHITE); // x y 表示圆心的坐标 int x = 0; int y = 0; solidcircle(x, y, 50); while (1) { /* getchar函数: 1: 从缓冲区中读取一个字符 2: 如果字符读取成功,就返回读取到的字符 3: 若是缓冲区中没有数据,就会阻塞函数,直到缓冲区中有数据 getch函数: getch函数可以不阻塞缓冲区及时响应的,使用该函数需要引入头文件conio.h才能被使用 使用平台提供的函数时需要在前面添加下划线以便和c语言提供的函数做一个区分 */ char c = _getch(); // 选择分支语句 switch (c) { case 'w': y = y + 50; break; case 's': y = y - 50; break; case 'a': x = x - 50; break; case 'd': x = x + 50; break; } // 清空窗体,重新绘制圆形 cleardevice(); solidcircle(x, y, 50); } return 0; }
eg2:一直变化的场景实现键盘控制
#include <stdio.h> #include <easyx.h> #include <iostream> #include <math.h> #include <conio.h> #define PI 3.14 int main() { // 键盘交互 initgraph(800, 600); setorigin(400, 300); setaspectratio(1, -1); setbkcolor(RGB(164, 225, 202)); cleardevice(); setfillcolor(WHITE); // x y 表示圆心的坐标 int x = -400,y = 0; // 相邻帧之间移动的距离 int dx = 5, dy = 0; solidcircle(x, y, 50); while (1) { cleardevice(); solidcircle(x, y, 50); Sleep(40); /* kbhit函数可以检查getch函数输入缓存区中是否有数据 如果没有数据就返回0,如果有数据就返回非0 */ if (_kbhit() != 0) { char c = _getch(); // 选择分支语句 switch (c) { case 'w': dx = 0; dy = 5; break; case 's': dx = 0; dy = -5; break; case 'a': dx = -5; dy = 0; break; case 'd': dx = 5; dy = 0; break; } x += dx; y += dy; } } getchar(); closegraph(); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。