[转载]C语言游戏编程

按方向键左右移动一个字符。

一、基本技术:

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多行,大型游戏,小型游戏,都是从这个基础,逐渐添加功能。

原文作者:https://www.dotcpp.com/wp/114.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值