首页 > 解决方案 > C中是否有函数或语句来获取按键

问题描述

当我编译和运行代码时,我试图用代码在终端上移动一个方块。我设法在屏幕上绘制正方形,但我不知道如何获得按键。当我弄清楚如何获得按键时,我将实现它。这是我的代码,不要介意那些帮助我理解代码的建议:

#include <stdio.h>
#include <stdlib.h>

#define ROWS 16
#define COLS 24

#define dot ->
#define or ||
#define and &&

#define pointer *

typedef struct Square {
    // where?
    float x, y;
    // how big?
    float w, h;

    // what char?
    char c;
} Square;

// draw_squares takes a pointer to a pointer to a square
// assuming you know how many pointers to squares there are in a row,
// you can use this as an array of sorts
void draw_squares(Square pointer pointer, int);

// this creates a square, so you don't have to manually set everything
Square pointer create_square(float, float, float, float, char);

// main entry point
int main(void) {
    // how many?
    int square_count = 3;

    // allocate memory to store three pointers to squares back-to-back
    // basically an array
    Square pointer pointer squares = malloc(sizeof(Square pointer) * square_count);

    // create squares
    squares[0] = create_square(14, 11, 4, 4, '#');
    squares[1] = create_square(8, 6, 4, 3, '@');
    squares[2] = create_square(1, 1, 3, 7, '&');

    draw_squares(squares, square_count);

    return 0;
}

void draw_squares(Square pointer pointer squares, int len) {
    for(int y = 0; y < ROWS; ++ y) {
        for(int x = 0; x < COLS; ++ x) {
            char ch = ' ';

            for(int ix = 0; ix < len; ++ ix) {
                Square pointer s = squares[ix];

                if(
                    // `x` is within bounds horizontally
                    (s dot x) <= x and (s dot x + s dot w) > x and
                    // `y` is within bounds vertically
                    (s dot y) <= y and (s dot y + s dot h) > y
                ) {
                    ch = s dot c;
                    break ;
                }
            }

            putchar(ch);
        }

        // go to next row with a newline
        putchar('\n');
    }
}



Square pointer create_square(float x, float y, float w, float h, char c) {
    // memory allocation for the size of a square
    Square pointer sq = malloc(sizeof(Square));

    // property setting
    sq dot x = x;
    sq dot y = y;
    sq dot w = w;
    sq dot h = h;

    sq dot c = c;

    return sq;
}

标签: c

解决方案


在 C 标准中没有办法做到这一点。每个操作系统(以及就此而言的终端)都有不同的执行方式,因此跨平台解决方案的最佳选择是整合这些的外部库。例如,SFML是一个带有 C 绑定的库,允许您将按键视为事件。


推荐阅读