EASYX键盘交互

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;


}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值