C语言—控制小球移动(同贪吃蛇移动原理)

目录

01、实现效果

​02、代码


01、实现效果

 通过控制W/S/A/D方向移动。

02、代码

#include<stdio.h>
#include<windows.h>//使用gotoxy(光标 移动函数)
#include<conio.h>//监听键盘输入
struct Coord
{
	int x;
	int y;
}coord;
int direct = '0';
void Move();
void gotoxy(int x, int y);
void HideCursor();
int main(int argc,char *argv[])
{
	//初始化位置
	coord.x = 20;
	coord.y = 20;
	gotoxy(coord.x, coord.y);
	printf("o");
	HideCursor();
	while (1)
	{
		Move();
	}
	
	return 0;
}
//移动函数
void Move()
{
	int i = 0;
	if (_kbhit)//监听键盘输入
	{
		fflush(stdin);
		direct = _getch();
	}
	//移动时,清空上一位置
	gotoxy(coord.x,coord.y);
	printf(" ");

	switch (direct)
	{
	case 'W':
	case 'w':
		coord.y--; break;
	case 'S':
	case 's':
		coord.y++; break;
	case 'A':
	case 'a':
		coord.x--; break;
	case 'D':
	case 'd':
		coord.x++; break;
	}
	gotoxy(coord.x, coord.y);
	printf("o");
}
//移动光标函数
void gotoxy(int x, int y)
{
	COORD pos;
	pos.X = x;
	pos.Y = y;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
//隐藏光标函数
void HideCursor() 
{
	HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
	CONSOLE_CURSOR_INFO cci;
	GetConsoleCursorInfo(hOut, &cci);
	cci.bVisible = FALSE;
	SetConsoleCursorInfo(hOut, &cci);
}

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值