函数kbhit在C中移动对象 [英] Function kbhit to move object in C
问题描述
该程序正在检测右键盘键,但是当我尝试通过按键盘上的箭头来移动对象时,但是当我这样做时,无论我按哪个箭头,它都在同一行中. 我正在寻求帮助,以将该对象移动到不同的位置.
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();
}
}
推荐答案
您没有调用gotoxy
函数,只需要printf(">");
You aren't calling the gotoxy
function, all you do is printf(">");
因此,在每个case
块中都添加它,就像这样
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.
请注意,您应检查x
和y
是否保持在限制范围内.
Note that you should check that x
and y
stay within limits.
case 72: if (y > 0) {
y--;
gotoxy(x, y);
printf(">");
}
break;
这篇关于函数kbhit在C中移动对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!