#include<stdio.h>
#include<easyx.h>
#include<time.h>#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"));//初始化car1car1.x = 128+rand()%(256-40);//0~255-40car1.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;}}
注意:当上下左右键不好用关掉电脑管家,否则会电脑管家会想删掉写的程序
可直接点x64下.exe运行或者运行.sln
该小游戏需要安装easyx图形库,自行到官网安装