c - 函数 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();
}
}
解决方案
你没有调用gotoxy
函数,你所做的只是printf(">");
所以在每个case
块中添加它,就像这个
case 72: y--;
gotoxy(x, y);
printf(">");
break;
现在你可以在屏幕上驾驶>
角色,留下它的踪迹。
请注意,您应该检查x
并y
保持在限制范围内。
case 72: if (y > 0) {
y--;
gotoxy(x, y);
printf(">");
}
break;
推荐阅读
- python - 以 2 种不同方式从数组中获取 pd.DataFrame
- svg - SVG 中的 CamanJS?
- regex - sed 替换适用于命令行,但不适用于 sed 脚本;(
- python - Python crypt.crypt 不使用 sha512 尽管 $6$
- ios - 如何在 Swift 4 中通过 SwiftyJson 和 Almofire 创建多个按钮?
- typescript - Typescript 和 CSS 模块类型
- swift - 以编程方式切换 MKUserTrackingBarButtonItem
- r - 使用动画以编程方式控制 R-Shiny 滑块上的播放/暂停
- verilog - 你能在同一个模块中同时写行为和结构的verilog吗?
- python - 如何更改数据框中的值用整数替换浮点数