Function kbhit to move object in C

只愿长相守 提交于 2019-12-24 21:26:01

问题


This program is detecting right keyboard keys, but when I am trying to move object by pressing arrow on my keyboard, but when i do this it goes in the same line, no matter which arrow i am pressing. I am asking for help to move this object in different possitions.

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

回答1:


You aren't calling the gotoxy function, all you do is printf(">");

So add that in each of the case blocks, like this one

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

Now you can drive the > character around the screen, leaving its trail.

Note that you should check that x and y stay within limits.

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


来源:https://stackoverflow.com/questions/54162272/function-kbhit-to-move-object-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!