首页 > 解决方案 > 函数 kbhit 在 C 中移动对象

问题描述

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

#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();
        }
}

标签: cmovekbhit

解决方案


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

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

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

现在你可以在屏幕上驾驶>角色,留下它的踪迹。

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

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

推荐阅读