赛车游戏简单单车C语言版

#include
#include
#include


#define WIDTH 512
#define HEIGHT 768

//定义一个汽车类
struct FCar
{
	//坐标
	float x, y;
	// 汽车种类
	int type;
	//汽车速度
	float speed;
};

//定义全局变量 图片坐标
IMAGE BG_IMG;
//背景图片坐标
float BG1_Y, BG2_Y;
//定义汽车图片
IMAGE CAR_IMG[4][2];
//定义一个汽车
FCar car1;

//初始化游戏(初始化一些数据,加载图片)
void InitGame();
//绘制游戏
void DrawGame();
//更新游戏
void UpdateGame();

int main()
{
	//初始化随机数种子
	srand(time(NULL));
	HWND hWnd=initgraph(WIDTH, HEIGHT);
	//1.77 标准横屏 640 360
	//窗口标题
	SetWindowText(hWnd,TEXT("精品赛车"));
	InitGame();
	while (TRUE)
	{
		DrawGame();
		UpdateGame();
	}
	return 0;
}

void InitGame()
{
	BG1_Y = 0;
	BG2_Y = -HEIGHT;
	
	//加载背景图片
	loadimage(&BG_IMG,TEXT("assets/Background.jpg"));
	//加载汽车图片
	loadimage(&CAR_IMG[0][0], TEXT("assets/Car00.jpg"));
	loadimage(&CAR_IMG[0][1], TEXT("assets/Car01.jpg"));
	loadimage(&CAR_IMG[1][0], TEXT("assets/Car10.jpg"));
	loadimage(&CAR_IMG[1][1], TEXT("assets/Car11.jpg"));
	loadimage(&CAR_IMG[2][0], TEXT("assets/Car20.jpg"));
	loadimage(&CAR_IMG[2][1], TEXT("assets/Car21.jpg"));
	loadimage(&CAR_IMG[3][0], TEXT("assets/Car30.jpg"));
	loadimage(&CAR_IMG[3][1], TEXT("assets/Car31.jpg"));
	//初始化car1
	car1.x = 128+rand()%(256-40);//0~255-40
	car1.y = 0;
	car1.type = rand()%4;
	car1.speed = 0.3;

}

void DrawGame()
{
	//双缓冲贴图(一帧一帧显示)
	BeginBatchDraw();
	cleardevice();
	//输出背景图片
	putimage(0, BG1_Y, &BG_IMG);
	putimage(0, BG2_Y, &BG_IMG);
	//设置线条样式
	setlinestyle(PS_DASH,3);
	//画线
	line(128, 0, 128, HEIGHT);
	line(128+256, 0, 128+256, HEIGHT);
	//显示car1车
	putimage(car1.x, car1.y, &CAR_IMG[car1.type][0], SRCPAINT);
	putimage(car1.x, car1.y, &CAR_IMG[car1.type][1], SRCAND);
	//图片从缓冲区中拿出来
	EndBatchDraw();
}

void UpdateGame()
{
	BG1_Y+=0.2;
	BG2_Y+=0.2;
	if (BG1_Y >= HEIGHT)
	{
		BG1_Y = -HEIGHT;
	}
	if (BG2_Y >= HEIGHT)
	{
		BG2_Y = -HEIGHT;
	}
	
		//控制车辆移动
		if (GetAsyncKeyState(VK_UP))//获取异部键盘状态
		{
			car1.y -= car1.speed;
		}
		if (GetAsyncKeyState(VK_DOWN))
		{
			car1.y += car1.speed;
		}
		if (GetAsyncKeyState(VK_LEFT))
		{
			if (car1.x > 128)
				car1.x -= car1.speed;
		}
		if (GetAsyncKeyState(VK_RIGHT))
		{
			if (car1.x < 128 + (256 - 40))
				car1.x += car1.speed;
		}
	
	
}

赛车游戏简单单车C语言版_第1张图片

注意:当上下左右键不好用关掉电脑管家,否则会电脑管家会想删掉写的程序

可直接点x64下.exe运行或者运行.sln

该小游戏需要安装easyx图形库,自行到官网安装

你可能感兴趣的:(游戏)