Featured image of post 【从零开始的C++游戏开发】提瓦特幸存者

【从零开始的C++游戏开发】提瓦特幸存者

制作一个简单版类吸血鬼幸存者游戏,这一系列教程第1个项目的笔记

目录

概览

技术栈:C++ + EasyX

项目目标:设计游戏的动画框架,接入键盘的按键操作,提供更具交互性的玩法。在数据和逻辑层面,实现简单的2D平面内的碰撞检查;实现敌人的随机生成和索敌跟踪逻辑。添加音乐和音效,丰富游戏的完成度。添加主菜单界面。使用享元模式来优化程序性能。

课程来源B站-Voidmatrix

核心玩法

玩家点击 开始 按钮进入游戏,使用 上 下 左 右 按键控制角色移动。在玩家角色的周围会有一圈子弹,野猪敌人会从屏幕外源源不断地涌向玩家。当子弹碰到敌人后,会击杀敌人并增加游戏得分。当敌人碰触到玩家角色时,游戏结束。

项目主体开发

设计思路

游戏主框架的设计

创建窗口、创建游戏主循环和稳定帧率,这个写法基本是游戏开发框架的固定格式,因为在 系列笔记第0集 基础 中有详细的解释,此处就不再赘述。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
int main()
{
    //========= 初始化数据 ==========
	initgraph(1280, 720);
	
    bool is_running = true;
    const int FPS = 60;
	
	ExMessage msg;
	
	BeginBatchDraw();
   
	while (is_running)	// 游戏主循环
	{
		DWORD start_time = GetTickCount();
        
        //========= 处理输入 =========
		while (peekmessage(&msg))
		{
			
		}	
        
        //======== 处理更新 =========

		cleardevice();

		//======== 处理渲染 =========
		
		FlushBatchDraw();

        //========= 稳定帧率 =========
		DWORD end_time = GetTickCount();
		DWORD delta_time = end_time - start_time;
		if (delta_time < 1000 / FPS)
		{
			Sleep(1000 / FPS - delta_time);
		}
	}

	EndBatchDraw();
	return 0;
}

各个对象/类的设计

本项目并没有使用多态来抽象出更上层的对象。基本按照一个对象设计一个类的思路进行。为了更加符合初学者的直觉和理解,将所有的代码放在了main.cpp 中,使用了大量的全局变量实现项目。

  • 玩家类
  • 子弹类(玩家周围的一圈子弹)
  • 敌人类
  • 动画类和图集类(实现和优化动画效果)
  • 按钮基类
    • 开始游戏按钮
    • 退出游戏按钮

开发流程

  • 游戏框架的设计

  • 图片的加载和渲染

    • 解决思路:使用EasyX的库函数:loadimage, putimage
    • 问题:png图片会产生黑边
      • 解决思路:自己在putimage的基础上重载一个含有透明通道的函数
      • 注意:要包含对应的库 pragma comment(lib, "MSIMG32.LIB")
  • 动画的实现

    • 问题1:如何让图片动起来?
      • 解决思路:计数器 ===> 优化:计时器
    • 问题2:动画的实现出现大量重复代码
      • 解决思路:封装Animation类
  • 角色移动的实现

    • 问题1:玩家移动时出现“卡顿感”
      • 解决思路:使用bool变量来标识按键的按下和抬起,间接控制玩家的运动
    • 问题2:玩家在斜线运动的速度快于水平/竖直方向
      • 解决思路:使用单位向量统一各个方向的速度
  • 问题:在试图实现敌人动画时发现和玩家的数据会一起混在Animation类中

    • 解决思路:使用面向对象的思想,创建各类管理各自的数据和逻辑
  • Player类的实现

  • Bullet类的实现

  • Enemy类的实现

    • 问题1:敌人刷新机制的实现
      • 解决思路:将敌人随机生成在地图外的一条边上
    • 注意点:函数中如果需要传入别的类的对象,要用引用传入,如果不会改变这个参数,就加上const
    • 问题2:敌人自动寻路机制的实现
      • 解决思路:玩家位置与敌人位置之差,计算其单位向量,就是敌人的移动方向
  • 2D碰撞检测的实现

    • 问题1:敌人和子弹的碰撞
      • 解决思路:将敌人看作一个矩形处理,而子弹则按照点来处理
    • 问题2:玩家和敌人的碰撞
      • 解决思路:将敌人的中心点作为碰撞点,与玩家的矩形进行碰撞检测
  • 子弹的更新、视觉效果的提升

    • 问题:让子弹的运动更加炫酷
      • 解决思路:给子弹一个切向速度、一个径向速度
  • 删除被击杀的敌人

    • 解决思路:先用 swap 将待删除的敌人移到vector末尾,再使用 pop_back,最后使用 delete 释放内存。这是一种 在元素次序无关 时性能较好的删除方法。
  • 添加和绘制玩家得分

  • 添加音效

    • 解决思路:使用Windows的库函数:mciSendString
    • 注意:要包含对应的库 pragma comment(lib, "Winmm.lib")
  • 优化:性能提升

    • 解决思路:使用 享元模式 优化资源加载
    • 注意:不能在Animation中释放其持有的Atlas,因为它是共享的,所以只能由更上层的代码控制
  • 添加主菜单UI、按钮类的设计

关键步骤和解决思路

图片的加载和渲染

实现读取/加载图片

阅读文档,可以看到EasyX使用 loadimage 这个函数来加载图片,这个函数有一个重载,此处我们直接使用较简单的 从图片文件中获取图像 这一个:

1
2
3
4
5
6
7
8
// 从图片文件获取图像(bmp/gif/jpg/png/tif/emf/wmf/ico)
int loadimage(
	IMAGE* pDstImg,			// 保存图像的 IMAGE 对象指针
	LPCTSTR pImgFile,		// 图片文件名
	int nWidth = 0,			// 图片的拉伸宽度
	int nHeight = 0,		// 图片的拉伸高度
	bool bResize = false	// 是否调整 IMAGE 的大小以适应图片
);

此处需要注意的是,第一个参数是一个图片的指针对象。我们不直接将图片加载到窗口中,而是先保存到变量里,然后在后续绘制中使用,所以要传入要给非空指针;第二个参数是图片的路径字符串;后三个参数均提供了默认值,用来设置图片的缩放属性,此项目中用不到,所以暂时忽略。那么,要加载程序目录下的图片 text.jpg , 可以这样表示:

1
2
IMAGE img;
loadimage(&img, _T("test.jpg"));
实现渲染图片

同样阅读文档,我们发现可以使用 putimage 这个函数来绘制图片:

1
2
3
4
5
6
7
// 绘制图像
void putimage(
	int dstX,				// 绘制位置的 x 坐标
	int dstY,				// 绘制位置的 y 坐标
	IMAGE *pSrcImg,			// 要绘制的 IMAGE 对象指针
	DWORD dwRop = SRCCOPY	// 三元光栅操作码
);

其中,第一二个参数是图片绘制在世界坐标中的位置。最后一个参数 三元光栅操作码 我们在这个项目中也忽略不计。那么如果要绘制刚刚加载的图片,这样我们可以写:

1
2
3
4
5
6
// 加载图片
IMAGE img;
loadimage(&img, _T("test.jpg"));

// 绘制图片
putimage(100, 200, &img);

如果这张图片的像素是 300 * 300 ,那么这张图片在游戏界面中的坐标是这样的:

需要注意的是,我们需要自己封装带有透明通道的 putimage函数,来解决显示的 png 图片带有黑框的问题:

1
2
3
4
5
6
7
8
9
#pragma comment(lib, "MSIMG32.LIB") 

void putimage_alpha(int x, int y, IMAGE* img)
{
	int w = img->getwidth();
	int h = img->getheight();
	AlphaBlend(GetImageHDC(NULL), x, y, w, h, GetImageHDC(img),
		0, 0, w, h, { AC_SRC_OVER,0,255,AC_SRC_ALPHA });
}

在函数之前(最好放在文件的开始处,要链接相关的库 #pragma comment(lib, "MSIMG32.LIB")

实现动画及渲染

如何让画面动起来?

游戏中角色动画的常见实现可以笼统地分为两类:序列帧动画关键帧动画

序列帧动画 :通常由一组图片素材构成,在程序中随着时间推移,我们不断地切换显示这一序列的图片,借助视觉暂留效应,产生动画效果。

关键帧动画 如骨骼动画等,因为涉及更复杂的图形学技术,此处暂不讨论。

注意,我们不能通过调用 Sleep() 函数来解决这个问题。因为当调用 Sleep() 函数时,程序会卡在那里,等待一定时间,这是一个“阻塞式”的行为,而在我们的游戏框架设计中,所有的画面渲染等操作,都应该式在一次又一次的循环中进行,每次循环的时间都控制在 1/60秒(FPS) 内。也就是说,我们切换动画轮播的任务,应该分摊在多帧之间进行,而不是在一次循环内全部结束。此处涉及到一个游戏编程中的核心思想:主循环内应尽量避免阻塞式的行为或者过于繁重且耗时过长的任务

为了确保动画序列帧可以在间隔固定的时间进行切换,采用了计时器的思路来做这样的一个计数器:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
int idx_current_anim = 0;	// 1. 存储当前动画帧的帧索引

const int PLAYER_ANIM_NUM = 6;	// 动画帧总数量

int main()
{
    .....
        
    while (is_running)
    {
        while (peekmessage(&msg))
  	    {
        
        }
    
        static int counter = 0;	// 2. 记录当前动画帧一共播放了几个游戏帧
                                // 用static修饰可以确保计数器只有在第一个游戏帧时被初始化为0
        // 每5个游戏帧切换一个动画帧
        if (++counter % 5 == 0)
            idx_current_anim++;

        ifidx_current_anim % PLAYER_ANIM_NUM == 0)
            idx_current_anim = 0;
        }  

        ......
}

动画的渲染本质就是将IMAGE数组中的图片依次绘制即可。先加载:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
const int PLAYER_ANIM_NUM = 6;	// 动画帧总数量

IMAGE img_player_left[PLAYER_ANIM_NUM];
IMAGE img_player_right[PLAYER_ANIM_NUM];

void load_animation()
{
    for (size_t i = 0; i < PLAYER_ANIM_NUM; i++)
    {
        std::wstring path = L"img/player_left_" + std::to_wstring(i) + L".png";
        loadimage(&img_player_left[i], path.c_str());
    }
    
    for (size_t i = 0; i < PLAYER_ANIM_NUM; i++)
    {
        std::wstring path = L"img/player_right_" + std::to_wstring(i) + L".png";
        loadimage(&img_player_right[i], path.c_str());
    }
}

然后在 main 中绘制这一系列动画图片的数组:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
int main()
{
    ......
   
	while (is_running)	// 游戏主循环
	{
		DWORD start_time = GetTickCount();
        
        //========= 处理输入 =========
		while (peekmessage(&msg))
		{
			
		}	
        
        //======== 处理更新 =========

		cleardevice();

		//======== 处理渲染 =========
		putimage_alpha(500, 500, &img_player_left[idx_current_anim]);
        
		FlushBatchDraw();

       ......
    }
}
将动画的实现封装成动画类

数据结构层面,用vector来存储动画所需图片的指针vector<IMAGE*> 。在构造函数中,需要加载动画所需的图片资源同时为其分配了内存空间,那么对应的,需要在析构函数中释放图片资源被释放内存空间.

在播放动画时,参数中除了需要知道动画播放的位置外,还增加了一个参数int delta用来表示距离上一次调用Play函数过去了多久时间,这是将“计数器”概念转为了“计时器”。之所以优化为这种设计,是因为一个动画的播放速度也就是 帧间隔,应该是与实际时间有关的,而不是与游戏的帧率有关,我们希望的是无论游戏帧的频率有多快,动画的播放速度是一致的,而不是画面刷新越快,动画播放越快。所以使用与实际时间有关的定时器,会比每一下调用都累加一次的计数器更能满足这种需求。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Animation
{
public:
	Animation(LPCTSTR path, int num, int interval)	// 加载动画帧图片资源
    {
        interval_ms = interval;
        
        TCHAR path_file[256];
        for (size_t i = 0; i < num; i++)
        {
            _sprintf_s(path_file, path, i);
            
            IMAGE* frame = new IMAGE();
            loadimage(frame, path_file);
            frame_list.push_bacl(frame);
        }
    }
    
    void Play(int x, int y, int delta)	// 播放动画 
    {
        timer += delta;
        if (timer >= interval_ms)
        {
            idx_frame = (idx_frame + 1) % frame_list.size();
            timer = 0;
        }
        
        // 绘制每一帧图片
        pitimage_alpha(x, y, frame_list[idx_frame]);
    }
    
    ~Animation()	// 释放资源
    {
        for (size_t i = 0; i < frame_list.size(); i++)
        {
            delete frame_list[i];
        }
    }
private:
    vector<IMAGE*> frame_list;
    int interval_ms = 0;	// 帧间隔
    int timer = 0;
    int idx_frame = 0;
}

实现角色移动

如果我们直接在按下按键时,用在不同坐标轴上累加位移的方式来控制玩家,会出现手感上的“卡顿感”。这是因为 WM_KEYDOWN 消息的产生是与我们的主循环 异步进行 的,且触发的频率与操作系统和硬件设备相关,这就导致在有些游戏帧中事件处理部分对多个WM_KEYDOWN消息进行了处理,而在其余游戏帧中WM_KEYDOWN消息较少或没有,这就导致角色在某些游戏帧中前进的距离较远/近一些,在宏观上展现为移动过程中的卡顿感。另外,当我们按下方向键时,会首先有一个 WM_KEYDOWN 消息进入消息事件队列中,随后,当我们保持按键按下状态一段时间后,才会有接连不断的 WM_KEYDOWN 消息被触发。

所以,要确保角色在每一个游戏帧中都连贯地移动相同的距离,从玩家的角色触发,就是:当玩家按下按键时,WM_KEYDOWN 消息触发,角色开始移动;当玩家抬起按键时,WM_KEYUP 消息触发,角色结束移动。所以使用相应的四个布尔变量来代表玩家的移动方向,我们通过改变按键的按下和抬起来改变这四个布尔变量的值,然后根据布尔变量的值来实现玩家在坐标轴上的位移:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
void ProcessEvent(const ExMessage& msg)
{
	if (msg.message == WM_KEYDOWN)
	{
		switch (msg.vkcode)
		{
		case VK_UP:
			is_moving_up = true;
			break;
		case VK_DOWN:
			is_moving_down = true;
			break;
		case VK_LEFT:
			is_moving_left = true;
			break;
		case VK_RIGHT:
			is_moving_right = true;
			break;
		}
	}

	if (msg.message == WM_KEYUP)
	{
		switch (msg.vkcode)
		{
		case VK_UP:
			is_moving_up = false;
			break;
		case VK_DOWN:
			is_moving_down = false;
			break;
		case VK_LEFT:
			is_moving_left = false;
			break;
		case VK_RIGHT:
			is_moving_right = false;
			break;
		}
	}		
}

void Move()
{
    if (is_moving_up)
        position.y -= SPEED;
    if (is_moving_down)
        position.y += SPEED;
    if (is_moving_left)
        position.x -= SPEED;
    if (is_moving_right)
        position.x += SPEED;
}

另外,为了避免玩家在斜角运动时位移更多的问题,需要使其在该速度方向的向量是单位向量:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
int dir_x = is_move_right - is_move_left;
int dir_y = is_move_down - is_move_up;
double len_dir = sqrt(dir_x * dir_x + dir_y + dir_y);
if(len_dir != 0)
{
    double normalized_x = dir_x / len_dir;
    double normalized_y = dir_y / len_dir;
    player_pos.x += (int)(PLAYER_SPEED * normalized_x);
    player_pos.y += (int)(PLAYER_SPEED * normalized_y);
}

各个类的封装

为了避免各个数据糅杂散落在项目的各处,将每个对象相关的逻辑和数据封装到各组的类中。以玩家类为例,大致的类的设计:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Player
{
public:
    Player()
    {
        // 初始化资源:动画资源、图片资源等
    }
    ~Player()
    {
        // 释放资源
    }
    void ProcessEvent(const ExMessage& msg)
    {
        // 玩家的输入逻辑
    }
    void Move()
    {
        // 处理玩家移动
    }
    void Draw(int delta)
    {
        // 绘制玩家
    }   
private:
    ......
}

敌人类的实现细节

敌人的随机生成机制
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 敌人生成的边界
enum class SpawnEdge
{
	Up = 0,
	Down,
	Left,
	Right
};

// 将敌人生成在四条边界中随机的一条上
SpawnEdge edge = (SpawnEdge)(rand() % 4);
// 具体的随机坐标值
switch (edge)
{
case SpawnEdge::Up:
	position.x = rand() % WINDOW_WIDTH;
	position.y = -FRAME_HEIGHT;
	break;
case SpawnEdge::Down:
	position.x = rand() % WINDOW_WIDTH;
	position.y = WINDOW_HEIGHT;
	break;
case SpawnEdge::Left:
	position.x = -FRAME_WIDTH;
	position.y = rand() % WINDOW_HEIGHT;
	break;
case SpawnEdge::Right:
	position.x = WINDOW_WIDTH;
	position.y = rand () % WINDOW_HEIGHT;
	break;
default:
	break;
}
敌人的寻路机制
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
void Move(const Player& player)
{
    const POINT& player_position = player.GetPosition();
    int dir_x = player_position.x - position.x;
    int dir_y = player_position.y - position.y;
    double dir_len = sqrt(dir_x * dir_x + dir_y * dir_y);
    if (dir_len != 0)
    {
        double normalized_x = dir_x / dir_len;
        double normalized_y = dir_y / dir_len;
        position.x += (int)(normalized_x * SPEED);
        position.y += (int)(normalized_y * SPEED);
    }

    if (dir_x > 0)
        facing_left = false;
    else if (dir_x < 0)
        facing_left = true;
}

2D碰撞检测的实现

这部分都放在敌人类中实现,玩家或者子弹的对象作为引用传入函数中,避免不必要的拷贝。

敌人和子弹
1
2
3
4
5
6
7
8
bool CheckBulletCollision(const Bullet& bullet) // 在参数前添加const:这个参数在函数中不会被修改
{
    // 将子弹等效为一个点,判断该点是否在敌人的矩形内
    bool is_overlap_x = bullet.position.x >= position.x && bullet.position.x <= position.x + FRAME_WIDTH;
    bool is_overlap_y = bullet.position.y >= position.y && bullet.position.y <= position.y + FRAME_HEIGHT;
		
    return is_overlap_x && is_overlap_y;
}
敌人和玩家

在游戏的碰撞检测中,一般不会太严格。如果将敌人和玩家均作为一个矩形去检测碰撞,可能会发生两者只有一个角落重叠但是从视觉上看并未发生碰撞的情况,让玩家困惑。所以一般情况下,受击碰撞器都会小于图片尺寸。此处采用将敌人中心作为一个碰撞点来处理。

1
2
3
4
5
6
7
8
9
bool CheckPlayerCollision(const Player& player)
{
	// 将敌人的中心点位置视为敌人的碰撞点
	POINT check_position = { position.x + FRAME_WIDTH / 2, position.y + FRAME_HEIGHT / 2 };
	bool is_overlap_x = check_position.x >= player.GetPosition().x && check_position.x <= player.GetPosition().x + player.FRAME_WIDTH;
	bool is_overlap_y = check_position.y >= player.GetPosition().y && check_position.y <= player.GetPosition().y + player.FRAME_HEIGHT;
	
	return is_overlap_x && is_overlap_y;
}

子弹的更新和视觉效果的提升

因为围绕玩家的子弹是由一圈3颗子弹组成的,所以将其作为全局函数处理。

关于子弹的运动,可以通过随着时间的推移改变α的值来表示,为了计算方便,此处的角度单位均为弧度:

相应的代码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// 更新子弹位置
void UpdateBullets(vector<Bullet>& bullet_list, const Player& player)
{
	// 让子弹有一个不断收缩的效果,视觉上更加炫酷
	const double RADIAL_SPEED = 0.0045; // 径向波动速度
	const double TANGENT_SPEED = 0.0055; // 切向波动速度

	double radian_interval = 2 * PI / bullet_list.size(); // 三颗子弹间的弧度间隔

	// 根据玩家的位置,依次更新每颗子弹的位置
	POINT player_position = player.GetPosition();
	double radius = BULLET_BASE_RADIUS + BULLET_RADIUS_CHANGE_RANGE * sin(GetTickCount() * RADIAL_SPEED);
	for (size_t i = 0; i < bullet_list.size(); i++)
	{
		double radian = GetTickCount() * TANGENT_SPEED + radian_interval * i;
		bullet_list[i].position.x = player_position.x + player.FRAME_WIDTH / 2 + (int)(radius * sin(radian));
		bullet_list[i].position.y = player_position.y + player.FRAME_HEIGHT / 2 + (int)(radius * cos(radian));
	}
}

删除被击杀的敌人

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// 依次检查敌人列表,移除被击杀的敌人
for (size_t i = 0; i < enemy_list.size(); i++) // 因为此处会动容器本身,所以不能用迭代器遍历
{
	Enemy* enemy = enemy_list[i];
	if (!enemy->CheckAlive())
	{
		// 和容器最后一个元素交换后,移除最后一个
		// * 是元素顺序无关紧要时,性能较好的一种删除方法
		swap(enemy_list[i], enemy_list.back());
		enemy_list.pop_back();
		delete enemy;
	}
}

播放音效

此项目使用Windows的库函数实现播放音效。可以写成这样的代码:

1
2
3
4
5
// 打开项目文件夹mus下的bgm.mp3文件,并且以后就叫它“bgm”
mciSendString(_T("open mus/bgm.mp3 alias bgm"), NULL, 0, NULL);	// 加载音效

// 播放别名叫bgm的音效,并从开头处循环播放
mciSendString(_T("play bgm repeat from 0"), NULL, 0, NULL);		// 如果不需要循环,就不要加repeat	

提升性能:使用享元模式优化资源加载

游戏中的模型和贴图资源所占比例很高,对硬盘空间和游戏启动时间的消耗都很大。享元模式在游戏开发中非常常用。比如,游戏中的一棵树的资源,一般的写法和使用享元模式的写法对比:

1
2
3
4
5
6
7
8
//========= 一般写法 =========
// 树的结构体
struct Tree
{
    Model model;	// 树的模型
    Texture texture;// 树的贴图
    int x, y, z;	// 树的位置
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
//======= 享元模式写法 =======

// 树的资产结构体
// 无论树有多少棵,均使用同一个TreeAsset对象中的数据
// 这也是绘制一棵树所需数据中最庞大的那部分
struct TreeAsset
{
    Model model;	// 树的模型
    Texture texture;// 树的贴图
}

// 树结构体
struct Tree
{
    TreeAsset* asset;	// 树的资产的指针
    int x, y, z;		// 树的位置
}

在此项目中,对Animation类进行重新拆分和设计,提取游戏中每一个个体敌人可以共享的数据 std::vector<IMAGE*> frame_list ,而其他三个私有成员,则是状态信息,是每一个敌人独有的。

每个个体持有共享数据的图集类:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// 资源加载优化
class Atlas
{
public:
	Atlas(LPCTSTR path, int num)
	{
		// 加载图片
		TCHAR path_file[256];
		for (int i = 0; i < num; i++)
		{
			_stprintf_s(path_file, path, i);

			IMAGE* frame = new IMAGE();
			loadimage(frame, path_file);
			frame_list.push_back(frame);
		}
	}

	~Atlas()
	{
		for (int i = 0; i < frame_list.size(); i++)
		{
			delete frame_list[i];
		}
	}

public:
	vector<IMAGE*> frame_list;
};

每个个体独有的数据封装在Animation类中:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Animation
{
public: 
	Animation(Atlas* atlas, int interval)
	{
		anim_atlas = atlas;
		interval_ms = interval;
	}

	~Animation() = default; // atlas是Animation类对象共享的公共资产,所以不能在Animation的析构函数中使用delete释放atlas指针
							// 需要在更上一层释放(main)
							// 况且这里也没有new

	// 播放动画
	void Play(int x, int y, int delta_time)
	{
		timer += delta_time;
		if (timer >= interval_ms)
		{
			idx_frame = (idx_frame + 1) % anim_atlas->frame_list.size();
			timer = 0;
		}

		putimage_alpha(x, y, anim_atlas->frame_list[idx_frame]);
	}

private:
	int interval_ms = 0; // 帧间隔
	int timer = 0; // 动画计时器
	int idx_frame = 0; // 动画帧索引

private:
	Atlas* anim_atlas; // 需要持有Atlas类的指针
};

按钮类的设计

按钮的状态有三种:Idle、Hover和Pushed,理清这三者的跳转关系来编写玩家输入的代码:

相应的,我们需要处理的情况也有三种:鼠标移动、左键按下、左键抬起:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void ProcessEvent(const ExMessage& msg)
{
	switch (msg.message)
	{
	case WM_MOUSEMOVE:
		if (status == Status::Idle && CheckCursorHit(msg.x, msg.y))
			status = Status::Hovered;
		else if (status == Status::Idle && !CheckCursorHit(msg.x, msg.y))
			status = Status::Idle;
		else if (status == Status::Hovered && !CheckCursorHit(msg.x, msg.y))
			status = Status::Idle;
		break;
	case WM_LBUTTONDOWN:
		if (CheckCursorHit(msg.x, msg.y))
			status = Status::Pushed;
		break;
	case WM_LBUTTONUP:
		if (status == Status::Pushed)
			OnClick();
		break;
	default:
		break;
	}
}

番外篇:角色动画特效和像素缓冲区

色彩知识补充

图片的最小单位是像素,像素的色彩由三原色红、绿、蓝(Red Green Blue),也就是我们常说的“RGB”,经过不同强度的各原色混合得到。如果用一个Color的结构体,可以这样表示:

1
2
3
4
5
6
struct Color
{
    int r;
    int g;
    int b;
};

“图片”本质上就是由这些像素所构成的二维数组。一张像素为 100*100 的图片可以等价为 Color image[100][100]; 那么在窗口中绘制一张图片的过程就是将这个小一点的二维数组拷贝到窗口这个大一点的二维数组的过程。而绘制的坐标则决定了像素数组位置的索引EasyX的 IMAGE 类中,有一个 DWORD* m_pBuffer; 的指针,用来指向存储图片像素色彩的缓冲区地址。由因为二维数组在内存中的存储其实是按照从左到右、从上到下的方式连续存储的,所以如果我们想要访问 (x, y) 位置的像素颜色的值,用二维数组表示的代码是 Color pix_color = image[y][x] ,在EasyX中需要转化为 DWORD pix_color = buffer[y * width + x] (width为图片宽度)。而这个指向像素缓冲区的指针,则可以由EasyX提供的接口 DWORD* GetImageBuffer(IMAGE* PImg = NULL) 获取。所以,如果要获得 image 这张图片的色彩缓冲区,可以这样写 DWORD* buffer = GetImageBuffer(&image),缓冲区中的每一个 DWORD 类型的元素都占据四个字节,存储RGBA(RGB色彩元素和透明通道)的信息。

图像翻转效果的实现

首先加载原始的图片素材,此例中为玩家向左的动画图片。然后定义玩家角色向右的动画序列帧数组,遍历每一张向左的图片并进行翻转。需要注意的是,首先我们需要使用了 Resize 来向右的序列帧图片调整为相同的大小,因为定义的IMAGE 对象如果没有使用其他对象进行拷贝构造或者使用 loadimage 函数进行加载的话,内部的像素缓存区默认是不存在的,所以 Resize 的过程同时也是对 IMAGE 对象进行内存分配的过程。接着,我们获取向左的图片和向右的图片的像素缓冲区,遍历图片像素缓冲区中的每一个像素,将它从向左的图片中拷贝到向右的图片中对应的位置上。那么在x轴上的元素在翻转后的位置索引为 width - 1 - x。具体的实现是这样的:

加载向左的动画帧图片:

1
2
3
4
5
6
7
8
9
IMAGE img_player_left[6];

// 加载玩家向左的动画
for (int i = 0; i < 6; i++)
{
    static TCHAR img_path[256];
    _stprintf_s(img_path, _T("img/paimon_left_&d.png"), i);
    loadimage(&img_player_left[i], img_path);
}

实现向右翻转的动画帧图片:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
IMAGE img_player_right[6];

for (int i = 0; i < 6; i++)
{
    int width = img_player_left[i].getwidth();
    int height = img_player_left[i].getheight();
    Resize(&img_player_right[i], width, height);	// 调整向右动画图片尺寸,同时为向右的图片开辟内存空间
    
    // 遍历两套图片的色彩缓冲区,逐行进行水平翻转
    // 并将相应索引上的像素信息拷贝给向右图片,完成翻转
    DWORD* color_buffer_left_img = GetImageBuffer(&img_player_left[i]);
    DWORD* color_buffer_right_img = GetImageBuffer(&img_player_right[i]);
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            int idx_left_img = y * width + x;					// 源像素索引(向左图片)
            int idx_right_img = y * width + (width - 1 - x);	// 目标像素索引(向右图片)
            color_buffer_right_img[idx_right_img] = color_buffer_left_img[idx_left_img];
        }
    }
}

获取每一个像素颜色的RGB分量

EasyX提供了 GetGValue GetRValueGetBValue 这三个宏来分别获取分量值。但需要特别注意的是,常用的COLORREF(一种表示颜色的类型,本质上是32位的整数)在内存中的表示形式为 0xbbggrr ,里面的红色和蓝色是对调的,所以我们在用EasyX的三个宏获取RGB分量时要需要调换R和B的位置:

1
2
3
4
DWORD pix_color = buffer[y * width + x];
BYTE r = GetBValue(pix_color);
BYTE g = GetGValue(pix_color);
BYTE b = GetRValue(pix_color);

图片闪烁效果的实现

本质上就是切换图片正常状态的序列帧和其纯白色的剪影序列帧即可。剪影序列帧也是可以通过操作渲染缓冲区进行动态生成。那么如何将像素的颜色设置为纯白色呢?首先可以使用RGB宏组合出COLORREF类型的值,然后使用BGR交换红色和蓝色的顺序,最后设置其透明通道的值:

1
2
3
4
// 前半部分获得标准顺序RGB的白色:0x00FFFFFF
// 后半部分构造alpha通道(透明度):(BYTE)(255)是8位的255,代表完全不透明,向左位移24位,得到0xFF000000
// 前后部分用按位或进行合并,得到0xFFFFFFFF,即完全不透明的纯白色
DWORD white_pix = BGR(RGB(255, 255, 255)) | (((DWORD)(BYTE)(255)) << 24);

那么实现图片闪烁的具体思路就是:先定义一个剪影序列帧的图片数组,然后同样遍历每一张原始图片素材,使用 Resize 将它们设置为相同大小并开辟内存空间。然后分别获取它们的色彩缓冲区,在两层循环中先判断当前位置的颜色是否为白色,如果不是则设置为白色:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
IMAGE img_player_left_sketch[6];

// 生成玩家向左动画的剪影
for (int i = 0; i < 6; i++)
{
    // 调整剪影动画图片尺寸大小同时开辟内存
    int width = img_player_left[i].getwidth();
    int height = img_player_left[i].getheight();
    Resize(&img_player_left_sketch[i], width, height);
    
    // 获取两套图片的色彩缓冲区
    DWORD* color_buffer_raw_img = GetImageBuffer(&img_player_left[i]);
    DWORD* color_buffer_sketch_img = GetImageBuffer(&img_player_left_sketch[i]);
    
    // 遍历图片的色彩缓冲区,将透明度不为0的像素设置为白色
   	for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            int idx = y * width + x;
            if ((color_buffer_raw_img[idx] & 0xFF000000) >> 24)	// if的判断条件为真,即像素不为0(白色)
                color_buffer_sketch_img[idx] = BGR(RGB(255, 255, 255)) | (((DWORD)(BYTE)(255)) << 24);
        }
    }
}

冻结效果的实现

Alpha混合的原理

EasyX在绘制图片是不考虑透明度的,那么透明度存在时的色彩计算公式为 最终颜色 = 源颜色 * Alpha + 目标颜色 * (1 - Alpha) 此处的Alpha值不是0 - 255,而是0 - 1的浮点数。 也就是说,如果将一张纯绿色的图片绘制到一张纯红色背景图片上时,覆盖位置的颜色可以进行这样的计算:

不考虑Alpha混合图片叠加效果
不考虑 Alpha 混合的图片叠加效果
考虑Alpha混合图片叠加效果
考虑 Alpha 混合的图片叠加效果及其计算公式

所以冰冻效果的实现思路,可以将一张冰冻的图片,以半透明的方式贴附在正常显示的图片之上。

具体实现

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// 拷贝当前帧用于后续处理
IMAGE img_current_frame(img_player_left[counter]);
int width = img_curent_frame.getwidth();
int height = img_curent_frame.getheight();

// 获取当前帧图片和冰冻图片的色彩缓冲区
DWORD* color_buffer_ice_img = GetImageBuffer(&img_ice);
DWORD* color_buffer_frame_img = GetImageBuffer(&img_current_frame);

// 遍历当前帧的色彩缓冲区,将不透明的区域进行混叠
for (int y = 0; y < height; y++)
{
    for (int x = 0; x < width; x++)
    {
        int idx = y * width + x;
        static const float RATIO = 0.25f;	// 混叠比例
        DWORD color_ice_img = color_buffer_ice_img[idx];
        DWORD color_frame_img = color_buffer_frame_img[idx];
        if ((color_frame_img & 0xFF000000) >> 24)	// 0xFF000000为透明通道
        {
            // 注意:色彩缓冲区中颜色存储的顺序是BGR,所以获取时需要调换B和R的位置
            BYTE r = (BYTE)(GetBValue(color_frame_img) * RATIO + GetBValue(color_ice_img) * (1 - RATIO));
            BYTE g = (BYTE)(GetGValue(color_frame_img) * RATIO + GetGValue(color_ice_img) * (1 - RATIO));
            BYTE b = (BYTE)(GetRValue(color_frame_img) * RATIO + GetRValue(color_ice_img) * (1 - RATIO));
            // 与透明通道叠加
            color_buffer_frame_img[idx] = (BGR(RGB(r, g, b)) | (((DWORD)(BYTE)(255)) << 24);
        }
    }
}

优化:给冰冻状态增加高亮效果

思路:用一条白色扫描线从上至下扫描图片,为了让效果更逼真,我们对混叠后的贴图先进行亮度提取,只有亮度大于一定阈值的部分才会显示为白色条带,所以调整后的完整代码是这样的:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
void RenderFrozenPlayer()
{
    static const POINT position = { 1075, 345};
    
    static int counter = 0;			// 动画帧索引
    static int anim_timer = 0;		// 动画计时器
    static int frozen_timer = 0;	// 冰冻状态计时器
    static const int THICKNESS = 5;	// 扫描线宽度
    static int hightlight_pos_y = 0;// 扫描线竖直坐标
    static bool is_frozen = false;	// 当前是否正在冰冻
    
    // 如果没有处于冰冻状态则更新动画计时器
    if ((!is_frozen) && (++anim_timer % 3 == 0))
        counter = (counter + 1) % 6;
    // 更新冻结计时器并重置扫描线位置
    if (++frozen_timer % 100 == 0)
    {
        is_frozen = !is_frozen;
        highlight_pos_y = -THICKNESS;
    }
    
    // 绘制玩家脚底阴影
    putimage_alpha(position.x + (80 - 32) / 2, position.y + 80, &img_shadow);
    
    // 根据当前是否处于冰冻状态渲染不同的动画帧
    if (is_frozen)
    {
        // 拷贝当前帧用于后续处理
        IMAGE img_current_frame(img_player_left[counter]);
        int width = img_curent_frame.getwidth();
        int height = img_curent_frame.getheight();

        // 更新高亮扫描线竖直坐标
        highlight_pos_y = (highlight_pos_y + 2) % height;
        
        // 获取当前帧图片和冰冻图片的色彩缓冲区
		DWORD* color_buffer_ice_img = GetImageBuffer(&img_ice);
		DWORD* color_buffer_frame_img = GetImageBuffer(&img_current_frame);
        
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                int idx = y * width + x;
                static const float RATIO = 0.25f;		// 混叠比例
                static const float THRESHOLD = 0.84f;	// 高亮阈值
                DWORD color_ice_img = color_buffer_ice_img[idx];
                DWORD color_frame_img = color_buffer_frame_img[idx];
                if ((color_frame_img & 0xFF000000) >> 24)	// 0xFF000000为透明通道
                {
                    // 注意:色彩缓冲区中颜色存储的顺序是BGR,所以获取时需要调换B和R的位置
                    BYTE r = (BYTE)(GetBValue(color_frame_img) 
                                    * RATIO + GetBValue(color_ice_img) * (1 - RATIO));
                    BYTE g = (BYTE)(GetGValue(color_frame_img) 
                                    * RATIO + GetGValue(color_ice_img) * (1 - RATIO));
                    BYTE b = (BYTE)(GetRValue(color_frame_img) 
                                    * RATIO + GetRValue(color_ice_img) * (1 - RATIO));

                    // 如果高亮扫描线处的像素亮度大于阈值,则直接将该像素设置为白色
                    if ((y >= hightlight_pos_y && y < = highlight_pos_y + THICKNESS)
                       && ((r / 255.0f) * 0.2126f + (g / 255.0f) * 0.7152f + (b / 255.0f) * 0.0722f 
                           >= TRESHOLD))
                    {
                    	color_buffer_frame_img[idx] 
                            = (BGR(RGB(255, 255, 255)) | (((DWORD)(BYTE)(255)) << 24);
                        continue;
                    }
                    color_buffer_frame_img[idx] = (BGR(RGB(r, g, b)) | (((DWORD)(BYTE)(255)) << 24);
                }
            }
        }
        putimage_alpha(position.x, position.y, &img_current_frame);	
    }
	else
        putimage_alpha(position.x, position.y, &img_player_left[counter]);
}

对于RGB色彩分量的亮度计算时,每个颜色前的系数来自于经验公式。

项目主体部分的完整源码

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
#include <graphics.h>
#include <string>
#include <vector>
using namespace std;

/* =============== 知识点 ===============
* 1.主循环内应尽量避免阻塞式行为或者过于繁重且耗时过长的任务
* 2.用计数器和用计时器来控制动画的帧更新的区别:
*	计数器:会存在电脑的刷新速度越快,帧更新就越快的情况
*	计时器:不管什么电脑,帧更新都和实际的时间流逝一致
* 3.利用享元模式对资源加载进行优化
*/ 

const int WINDOW_WIDTH = 1280;
const int WINDOW_HEIGHT = 720;

const int FPS = 60;

const double PI = 3.14159;

const int BULLET_BASE_RADIUS = 100;
const int BULLET_RADIUS_CHANGE_RANGE = 25;

const int PLAYER_ANIM_NUM = 6;
const int ENEMY_ANIM_NUM = 6;

const int BUTTON_WIDTH = 192;
const int BUTTON_HEIGHT = 75;

bool is_game_started = false;
bool is_running = true;

#pragma comment(lib, "MSIMG32.LIB") // pragma comment作用:链接库
#pragma comment(lib, "Winmm.lib") // 音频播放的库

// 自己定义一个可以处理透明度的图片绘制函数
void putimage_alpha(int x, int y, IMAGE* img);

// 资源加载优化
class Atlas
{
public:
	Atlas(LPCTSTR path, int num)
	{
		// 加载图片
		TCHAR path_file[256];
		for (int i = 0; i < num; i++)
		{
			_stprintf_s(path_file, path, i);

			IMAGE* frame = new IMAGE();
			loadimage(frame, path_file);
			frame_list.push_back(frame);
		}
	}

	~Atlas()
	{
		for (int i = 0; i < frame_list.size(); i++)
		{
			delete frame_list[i];
		}
	}

public:
	vector<IMAGE*> frame_list;
};

Atlas* atlas_player_left; // 放在main中初始化
Atlas* atlas_player_right;
Atlas* atlas_enemy_left;
Atlas* atlas_enemy_right;

class Animation
{
public: 
	Animation(Atlas* atlas, int interval)
	{
		anim_atlas = atlas;
		interval_ms = interval;
	}

	~Animation() = default; // atlas是Animation类对象共享的公共资产,所以不能在Animation的析构函数中使用delete释放atlas指针
							// 需要在更上一层释放(main)
							// 况且这里也没有new

	// 播放动画
	void Play(int x, int y, int delta_time)
	{
		timer += delta_time;
		if (timer >= interval_ms)
		{
			idx_frame = (idx_frame + 1) % anim_atlas->frame_list.size();
			timer = 0;
		}

		putimage_alpha(x, y, anim_atlas->frame_list[idx_frame]);
	}

private:
	int interval_ms = 0; // 帧间隔
	int timer = 0; // 动画计时器
	int idx_frame = 0; // 动画帧索引

private:
	Atlas* anim_atlas; // 需要持有Atlas类的指针
};

class Player
{
public:
	Player()
	{
		loadimage(&img_shadow, _T("img/shadow_player.png"));
		anim_left = new Animation(atlas_player_left, 45);
		anim_right = new Animation(atlas_player_right, 45);
	}

	~Player()
	{
		delete anim_left;
		delete anim_right;
	}

	void ProcessEvent(const ExMessage& msg)
	{
		if (msg.message == WM_KEYDOWN)
		{
			switch (msg.vkcode)
			{
			case VK_UP:
				is_moving_up = true;
				break;
			case VK_DOWN:
				is_moving_down = true;
				break;
			case VK_LEFT:
				is_moving_left = true;
				break;
			case VK_RIGHT:
				is_moving_right = true;
				break;
			}
		}

		if (msg.message == WM_KEYUP)
		{
			switch (msg.vkcode)
			{
			case VK_UP:
				is_moving_up = false;
				break;
			case VK_DOWN:
				is_moving_down = false;
				break;
			case VK_LEFT:
				is_moving_left = false;
				break;
			case VK_RIGHT:
				is_moving_right = false;
				break;
			}
		}		
	}

	void Move()
	{
		if (is_moving_up)
			position.y -= SPEED;
		if (is_moving_down)
			position.y += SPEED;
		if (is_moving_left)
			position.x -= SPEED;
		if (is_moving_right)
			position.x += SPEED;

		// 解决斜线移动速度更快的问题
		int dir_x = is_moving_right - is_moving_left; // 向右为x轴正方向
		int dir_y = is_moving_down - is_moving_up; // 向下为y轴正方向
		double len_dir = sqrt(dir_x * dir_x + dir_y * dir_y);
		if (len_dir != 0)
		{
			double normalized_x = dir_x / len_dir;
			double normalized_y = dir_y / len_dir;
			position.x += (int)(SPEED * normalized_x);
			position.y += (int)(SPEED * normalized_y);
		}

		// 限制玩家移动范围
		if (position.x < 0) position.x = 0;
		if (position.y < 0) position.y = 0;
		if (position.x + FRAME_WIDTH > WINDOW_WIDTH) position.x = WINDOW_WIDTH - FRAME_WIDTH;
		if (position.y + FRAME_HEIGHT > WINDOW_HEIGHT) position.y = WINDOW_HEIGHT - FRAME_HEIGHT;
	}

	void Draw(int delta_time)
	{
		// 在绘制玩家之前绘制阴影
		int shadow_pos_x = position.x + (FRAME_WIDTH / 2 - SHADOW_WIDTH / 2);
		int shadow_pos_y = position.y + FRAME_HEIGHT - 8;
		putimage_alpha(shadow_pos_x, shadow_pos_y, &img_shadow);

		static bool facing_left = false;
		int dir_x = is_moving_right - is_moving_left;
		if (dir_x < 0)
			facing_left = true;
		else if (dir_x > 0)
			facing_left = false;

		if (facing_left)
			anim_left->Play(position.x, position.y, delta_time);
		else
			anim_right->Play(position.x, position.y, delta_time);
	}

	const POINT& GetPosition() const
	{
		return position;
	}

public:
	const int FRAME_WIDTH = 80;
	const int FRAME_HEIGHT = 80;

private:
	const int SPEED = 3; // player移动的速度
	const int SHADOW_WIDTH = 32;	

private:	
	IMAGE img_shadow; // 玩家脚下阴影
	Animation* anim_left;
	Animation* anim_right;
	POINT position = { 500, 500 }; // 玩家坐标

	// 解决消息处理和按键异步造成的玩家移动卡顿问题
	bool is_moving_up = false;
	bool is_moving_down = false;
	bool is_moving_left = false;
	bool is_moving_right = false;
};

class Bullet
{
public:
	Bullet() = default;
	~Bullet() = default;

	void Draw() const // 在成员方法后面加上const:这个方法不会修改类的成员变量
	{
		setlinecolor(RGB(255, 155, 50));
		setfillcolor(RGB(200, 75, 10));
		fillcircle(position.x, position.y, RADIUS);
	}

public:
	POINT position = { 0, 0 };

private:
	const int RADIUS = 10;
};

class Enemy
{
public:
	Enemy()
	{
		loadimage(&img_shadow, _T("img/shadow_enemy.png"));
		anim_left = new Animation(atlas_enemy_left, 45);
		anim_right = new Animation(atlas_enemy_right, 45);

		// 敌人生成的边界
		enum class SpawnEdge
		{
			Up = 0,
			Down,
			Left,
			Right
		};

		// 将敌人生成在四条边界中随机的一条上
		SpawnEdge edge = (SpawnEdge)(rand() % 4);
		// 具体的随机坐标值
		switch (edge)
		{
		case SpawnEdge::Up:
			position.x = rand() % WINDOW_WIDTH;
			position.y = -FRAME_HEIGHT;
			break;
		case SpawnEdge::Down:
			position.x = rand() % WINDOW_WIDTH;
			position.y = WINDOW_HEIGHT;
			break;
		case SpawnEdge::Left:
			position.x = -FRAME_WIDTH;
			position.y = rand() % WINDOW_HEIGHT;
			break;
		case SpawnEdge::Right:
			position.x = WINDOW_WIDTH;
			position.y = rand () % WINDOW_HEIGHT;
			break;
		default:
			break;
		}
	}

	~Enemy()
	{
		delete anim_left;
		delete anim_right;
	}

	bool CheckBulletCollision(const Bullet& bullet) // 在参数前添加const:这个参数在函数中不会被修改
	{
		// 将子弹等效为一个点,判断该点是否在敌人的矩形内
		bool is_overlap_x = bullet.position.x >= position.x && bullet.position.x <= position.x + FRAME_WIDTH;
		bool is_overlap_y = bullet.position.y >= position.y && bullet.position.y <= position.y + FRAME_HEIGHT;
		
		return is_overlap_x && is_overlap_y;
	}

	bool CheckPlayerCollision(const Player& player)
	{
		// 将敌人的中心点位置视为敌人的碰撞点
		POINT check_position = { position.x + FRAME_WIDTH / 2, position.y + FRAME_HEIGHT / 2 };
		bool is_overlap_x = check_position.x >= player.GetPosition().x && check_position.x <= player.GetPosition().x + player.FRAME_WIDTH;
		bool is_overlap_y = check_position.y >= player.GetPosition().y && check_position.y <= player.GetPosition().y + player.FRAME_HEIGHT;
		
		return is_overlap_x && is_overlap_y;
	}

	void Move(const Player& player)
	{
		const POINT& player_position = player.GetPosition();
		int dir_x = player_position.x - position.x;
		int dir_y = player_position.y - position.y;
		double dir_len = sqrt(dir_x * dir_x + dir_y * dir_y);
		if (dir_len != 0)
		{
			double normalized_x = dir_x / dir_len;
			double normalized_y = dir_y / dir_len;
			position.x += (int)(normalized_x * SPEED);
			position.y += (int)(normalized_y * SPEED);
		}

		if (dir_x > 0)
			facing_left = false;
		else if (dir_x < 0)
			facing_left = true;
	}

	void Draw(int delta_time)
	{
		int shadow_pos_x = position.x + (FRAME_WIDTH / 2 - SHADOW_WIDTH / 2);
		int shadow_pos_y = position.y + FRAME_HEIGHT - 35;
		putimage_alpha(shadow_pos_x, shadow_pos_y, &img_shadow);

		if (facing_left)
			anim_left->Play(position.x, position.y, delta_time);
		else
			anim_right->Play(position.x, position.y, delta_time);
	}

	void Hurt()
	{
		alive = false;
	}

	bool CheckAlive()
	{
		return alive;
	}

private: 
	const int SPEED = 2; 
	const int FRAME_WIDTH = 80;
	const int FRAME_HEIGHT = 80;
	const int SHADOW_WIDTH = 48;	

private:
	IMAGE img_shadow; 
	Animation* anim_left;
	Animation* anim_right;
	POINT position = { 0, 0 }; 
	bool facing_left = false;
	bool alive = true;
}; 

// Button的基类
class Button
{
public:
	Button(RECT rect, LPCTSTR path_imag_idle, LPCTSTR path_imag_hovered, LPCTSTR path_imag_pushed) // 加载图片
	{
		region = rect;
		loadimage(&img_idle, path_imag_idle);
		loadimage(&img_hovered, path_imag_hovered);
		loadimage(&img_pushed, path_imag_pushed);
	}

	~Button() = default;

	void Draw()
	{
		switch (status)
		{
		case Status::Idle:
			putimage(region.left, region.top, &img_idle);
			break;
		case Status::Hovered:
			putimage(region.left, region.top, &img_hovered);
			break;
		case Status::Pushed:
			putimage(region.left, region.top, &img_pushed);
			break;
		}
	}

	void ProcessEvent(const ExMessage& msg)
	{
		switch (msg.message)
		{
		case WM_MOUSEMOVE:
			if (status == Status::Idle && CheckCursorHit(msg.x, msg.y))
				status = Status::Hovered;
			else if (status == Status::Idle && !CheckCursorHit(msg.x, msg.y))
				status = Status::Idle;
			else if (status == Status::Hovered && !CheckCursorHit(msg.x, msg.y))
				status = Status::Idle;
			break;
		case WM_LBUTTONDOWN:
			if (CheckCursorHit(msg.x, msg.y))
				status = Status::Pushed;
			break;
		case WM_LBUTTONUP:
			if (status == Status::Pushed)
				OnClick();
			break;
		default:
			break;
		}
	}

protected:
	virtual void OnClick() = 0;

private:
	bool CheckCursorHit(int x, int y)
	{
		return x >= region.left && x <= region.right && y >= region.top && y <= region.bottom;
	}

private:
	enum class Status
	{
		Idle = 0,
		Hovered,
		Pushed
	};

private:
	RECT region;
	IMAGE img_idle;
	IMAGE img_hovered;
	IMAGE img_pushed;
	Status status = Status::Idle;
};

// 开始游戏按钮
class StartGameButton : public Button
{
public:
	StartGameButton(RECT rect, LPCTSTR path_imag_idle, LPCTSTR path_imag_hovered, LPCTSTR path_imag_pushed)
		: Button(rect, path_imag_idle, path_imag_hovered, path_imag_pushed) {}
	~StartGameButton() = default;

protected:
	void OnClick()
	{
		is_game_started = true;
		mciSendString(_T("play bgm repeat from 0"), NULL, 0, NULL); // 重复播放bgm
	}
};

// 退出游戏按钮
class QuitGameButton : public Button
{
public:
	QuitGameButton(RECT rect, LPCTSTR path_imag_idle, LPCTSTR path_imag_hovered, LPCTSTR path_imag_pushed)
		: Button(rect, path_imag_idle, path_imag_hovered, path_imag_pushed) {}
	~QuitGameButton() = default;
protected:
	void OnClick()
	{
		is_running = false;
	}
};

void TryGenerateEnemy(vector<Enemy*>& enemy_list);
void UpdateBullets(vector<Bullet>& bullet_list, const Player& player);
void DrawPlayerScore(int score);

int main()
{
	initgraph(WINDOW_WIDTH, WINDOW_HEIGHT);
	mciSendString(_T("open mus/bgm.mp3 alias bgm"), NULL, 0, NULL); // 加载
	mciSendString(_T("open mus/hit.wav alias hit"), NULL, 0, NULL); 

	// player和enemy的构造函数都要用到atlas,所以atlas的初始化必须放在这两者之前
	atlas_player_left = new Atlas(_T("img/player_left_%d.png"), PLAYER_ANIM_NUM);
	atlas_player_right = new Atlas(_T("img/player_right_%d.png"), PLAYER_ANIM_NUM);
	atlas_enemy_left = new Atlas(_T("img/enemy_left_%d.png"), ENEMY_ANIM_NUM);
	atlas_enemy_right = new Atlas(_T("img/enemy_right_%d.png"), ENEMY_ANIM_NUM);

	Player player; 
	vector<Enemy*> enemy_list;
	vector<Bullet> bullet_list(3); // 子弹只有三颗,所以不使用指针的形式,避免内存泄漏的风险	
	
	ExMessage msg;
	IMAGE img_menu;	
	IMAGE img_background;	

	int score = 0;

	RECT region_btn_start_game, region_btn_quit_game;
	// ================ UI ================
	region_btn_start_game.left = (WINDOW_WIDTH - BUTTON_WIDTH) / 2;
	region_btn_start_game.right = region_btn_start_game.left + BUTTON_WIDTH;
	region_btn_start_game.top = 430;
	region_btn_start_game.bottom = region_btn_start_game.top + BUTTON_HEIGHT;

	region_btn_quit_game.left = (WINDOW_WIDTH - BUTTON_WIDTH) / 2;
	region_btn_quit_game.right = region_btn_quit_game.left + BUTTON_WIDTH;
	region_btn_quit_game.top = 550;
	region_btn_quit_game.bottom = region_btn_quit_game.top + BUTTON_HEIGHT;

	StartGameButton btn_start_game = StartGameButton(region_btn_start_game,
		_T("img/ui_start_idle.png"), _T("img/ui_start_hovered.png"), _T("img/ui_start_pushed.png"));

	QuitGameButton btn_quit_game = QuitGameButton(region_btn_quit_game,
		_T("img/ui_quit_idle.png"), _T("img/ui_quit_hovered.png"), _T("img/ui_quit_pushed.png"));
	
	loadimage(&img_menu, _T("img/menu.png"));
	loadimage(&img_background, _T("img/background.png"));
	
	BeginBatchDraw();
	while (is_running)
	{
		DWORD start_time = GetTickCount();
		while (peekmessage(&msg))
		{
			if (is_game_started)
			{
				player.ProcessEvent(msg);
			}
			else
			{
				btn_start_game.ProcessEvent(msg);
				btn_quit_game.ProcessEvent(msg);
			}
		}	

		if (is_game_started)
		{
			player.Move();
			UpdateBullets(bullet_list, player);

			TryGenerateEnemy(enemy_list);
			for (Enemy* enemy : enemy_list)
				enemy->Move(player);

			// 检测敌人与玩家的碰撞
			for (Enemy* enemy : enemy_list)
			{
				if (enemy->CheckPlayerCollision(player))
				{
					static TCHAR text[128];
					_stprintf_s(text, _T("最终得分:%d!"), score);
					MessageBox(GetHWnd(), text, _T("游戏结束"), MB_OK);
					is_running = false;
					break;
				}
			}

			// 检测敌人与子弹的碰撞
			for (Enemy* enemy : enemy_list)
			{
				for (const Bullet& bullet : bullet_list)
				{
					if (enemy->CheckBulletCollision(bullet))
					{
						mciSendString(_T("play hit from 0"), NULL, 0, NULL);
						enemy->Hurt();
						score++;
					}
				}
			}

			// 依次检查敌人列表,移除被击杀的敌人
			for (size_t i = 0; i < enemy_list.size(); i++) // 因为此处会动容器本身,所以不能用迭代器遍历
			{
				Enemy* enemy = enemy_list[i];
				if (!enemy->CheckAlive())
				{
					// 和容器最后一个元素交换后,移除最后一个
					// * 是元素顺序无关紧要时,性能较好的一种删除方法
					swap(enemy_list[i], enemy_list.back());
					enemy_list.pop_back();
					delete enemy;
				}
			}
		}

		cleardevice();

		// ======= Draw  =======
		if (is_game_started)
		{
			putimage(0, 0, &img_background);
			player.Draw(1000 / FPS);
			for (Enemy* enemy : enemy_list)
				enemy->Draw(1000 / FPS);
			for (Bullet& bullet : bullet_list)
				bullet.Draw();

			DrawPlayerScore(score);
		}
		else
		{
			putimage(0, 0, &img_menu);
			btn_start_game.Draw();
			btn_quit_game.Draw();
		}

		FlushBatchDraw();

		DWORD end_time = GetTickCount();
		DWORD delta_time = end_time - start_time;
		if (delta_time < 1000 / FPS)
		{
			Sleep(1000 / FPS - delta_time);
		}
	}

	// atlas指针需在游戏主循环结束后释放
	delete atlas_player_left;
	delete atlas_player_right;
	delete atlas_enemy_left;
	delete atlas_enemy_right;

	EndBatchDraw();
	return 0;
}

void putimage_alpha(int x, int y, IMAGE* img)
{
	int w = img->getwidth();
	int h = img->getheight();
	AlphaBlend(GetImageHDC(NULL), x, y, w, h, GetImageHDC(img),
		0, 0, w, h, { AC_SRC_OVER,0,255,AC_SRC_ALPHA });
}

void TryGenerateEnemy(vector<Enemy*>& enemy_list)
{
	const int INTERVAL = 100;
	static int counter = 0;
	if (++counter % INTERVAL == 0)
	{
		enemy_list.push_back(new Enemy());
	}
}

// 更新子弹位置
void UpdateBullets(vector<Bullet>& bullet_list, const Player& player)
{
	// 让子弹有一个不断收缩的效果,视觉上更加炫酷
	const double RADIAL_SPEED = 0.0045; // 径向波动速度
	const double TANGENT_SPEED = 0.0055; // 切向波动速度

	double radian_interval = 2 * PI / bullet_list.size(); // 三颗子弹间的弧度间隔

	// 根据玩家的位置,依次更新每颗子弹的位置
	POINT player_position = player.GetPosition();
	double radius = BULLET_BASE_RADIUS + BULLET_RADIUS_CHANGE_RANGE * sin(GetTickCount() * RADIAL_SPEED);
	for (size_t i = 0; i < bullet_list.size(); i++)
	{
		double radian = GetTickCount() * TANGENT_SPEED + radian_interval * i;
		bullet_list[i].position.x = player_position.x + player.FRAME_WIDTH / 2 + (int)(radius * sin(radian));
		bullet_list[i].position.y = player_position.y + player.FRAME_HEIGHT / 2 + (int)(radius * cos(radian));
	}
}

void DrawPlayerScore(int score)
{
	static TCHAR text[64];
	_stprintf_s(text, _T("当前玩家得分:%d"), score);

	setbkmode(TRANSPARENT);
	settextcolor(RGB(255, 85, 185));
	outtextxy(10, 10, text);
}

复盘和总结

虽然这个项目的实现还是基于初学者的直觉进行开发,并未做太多架构上的设计,但是我还是学到了很多。老师同样是从游戏的框架开始,渐渐细化每个模块,同时他清晰展示了每一部分遇到了怎样的问题,可以用怎样的思路解决问题,对我自己的开发具有很大的参考价值。同时还让我详细了解了动画的底层实现,补充了颜色和像素的知识,帮我复习了向量运动和2D碰撞。以一个非常浅显又实操的例子让我明白了享元模式和设计模式的作用。经常会有一种醍醐灌顶、拨开云雾见青天的感觉。接下来需要进一步补充的地方,一是关于3D的碰撞检测等,3D的内容在学校里以非常传统的读教科书做题的方式学过一遍,但是没有开发中的例子所以印象不深,感觉现在已经全忘了。二是游戏开发的设计模式,在读书的时候也是按照最传统的方式看书回答问题,但那时的感觉基本是看天书一般,蒙着做的题目,所以应该会继续学习这位老师相关的设计模式课程,让自己在实战中有更深刻的理解。

Licensed under CC BY-NC-SA 4.0
最后更新于 Oct 16, 2025 11:10 +0200
发表了13篇文章 · 总计9万0千字
本博客已运行
使用 Hugo 构建
主题 StackJimmy 设计