问题
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