按方向键左右移动一个字符。
一、基本技术:
1. 指定位置输出字符。如果输出空格,表示清除字符。
2. 循环和计时器的延时函数。
3. 检测键盘哪个按键处于按下状态。
二、截图
三、源代码
#include<stdio.h>
#include<time.h>
#include<windows.h>
#include<stdlib.h>
// 原作者 https://www.dotcpp.com/wp/114.html
void Pos(int x,int y)//设置光标位置
{
COORD pos;
HANDLE hOutput;
pos.X=x;
pos.Y=y;
hOutput=GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hOutput,pos);
}
#define RIGHT_EDGE 40
int tx=5,ty=5;
int tx_old,ty_old;
int status=3;
int sleeptime = 100;
void keyprocess(int ikey)
{
tx_old=tx;
ty_old=ty;
if(ikey == 1 )
{
tx= (tx)>0? tx-1:tx;
}
else if(ikey == 2 )
{
tx= (tx)<RIGHT_EDGE ? tx+1:tx;
}
}
void drawedge()
{
int i;
for(i=0;i<10;i++)
{
Pos(RIGHT_EDGE+1, i);
printf("a");
}
}
int main(int argc, char *argv[])
{
Pos(0, 0);
printf(" 按左右键移动");
drawedge();
while(1)
{
Pos(tx, ty);
printf("+");
//clear 坐标发生变化,清除原图案
if(tx!=tx_old || ty!= ty_old)
{
Pos(tx_old, ty_old);
printf(" ");
}
if(GetAsyncKeyState(VK_LEFT) )
{
keyprocess(1);
}
else if(GetAsyncKeyState(VK_RIGHT) )
{
keyprocess(2);
}
Sleep(sleeptime);//延时函数,间隔休息时间
}
return 0;
}
70多行,大型游戏,小型游戏,都是从这个基础,逐渐添加功能。