【问题标题】:Function kbhit to move object in C函数 kbhit 在 C 中移动对象
【发布时间】:2019-01-12 17:45:35
【问题描述】:

这个程序正在检测右键盘键,但是当我试图通过按键盘上的箭头移动对象时,但是当我这样做时,无论我按哪个箭头,它都会进入同一行。 我正在寻求帮助以将这个对象移动到不同的位置。

#include <stdio.h>
#include <windows.h>
#include <time.h>
#include <stdlib.h>
#include <conio.h>
COORD coord={0, 0};

struct Ship{
    int x,y;
}Ship;
struct Ship S;
void gotoxy (int x, int y){
    coord.X = x; coord.Y = y; // X and Y coordinates
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void print()
{
    system("CLS");
    coord.X = 0;
    coord.Y = 0;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
        printf (">");
} 

int main(){
    time_t last_change = clock();
    int game=1;
    int speed=300;
    print();
    int x=0, y=0;

    while (game==1){
            if (kbhit()){
                int c = getch();
                //printf("%d",c);
                if (c==224){
                    c = getch();
                    //printf("%d",c);
                    switch (c){
                        case 72: {y--;printf(">");}
                        break;
                        case 80: {y++;printf(">");}
                        break;
                        case 77: {x++;printf(">");}
                        break;
                        case 75: {x--;printf(">");}
                        break;
                    }
                }
            };
        last_change= clock();
        }
}

【问题讨论】:

    标签: c move kbhit


    【解决方案1】:

    你没有调用gotoxy函数,你所做的只是printf("&gt;");

    所以在每个 case 块中添加它,就像这个

    case 72: y--;
             gotoxy(x, y);
             printf(">");
             break;
    

    现在您可以在屏幕上驾驶&gt; 字符,留下它的踪迹。

    请注意,您应该检查xy 是否在限制范围内。

    case 72: if (y > 0) {
                 y--;
                 gotoxy(x, y);
                 printf(">");
             }
             break;
    

    【讨论】:

    • 按什么键进入一行?您必须更改所有情况,而不仅仅是一个。
    • 即使我按照你说的那样改变了它仍然在一条车道上行驶:(
    • switch (c){ case 72: y++;高氧(x,y); printf(">");休息;案例 80:是的;高氧(x,y); printf(">");休息;案例 77:x++;高氧(x,y); printf(">");休息;案例 75:x--;高氧(x,y); printf(">");
    • 你按哪个键?左箭头?添加限制。
    • 我按下所有箭头,它在同一行:P
    猜你喜欢
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 2021-01-20
    相关资源
    最近更新 更多