栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

基于C++的FPS射击训练小游戏

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

基于C++的FPS射击训练小游戏

文章目录
  • 前言
  • 一、开始前的准备
  • 二、主要模块的具体设计
    • 1.查询新建的圆是否满足要求
    • 2.玩家操作模块的设计
  • 完整代码
  • 总结


前言

本文在Visual Studio 2019 的C++环境下进行,需要装载graphics图形库
由于朋友比较喜欢吃鸡,自己做的一个简单的FPS快速反应射击的训练软件,希望能提高他的反击速度hhh


一、开始前的准备

在开始前我们需要确定并部署整个游戏需要的数据结构,以及他们的并发问题,虽然不愿意承认,但它们的确困扰了我一点时间,掉了我一些头发。
第一,射击的目标,简单地利用graphics绘画一个球的图案即可,为此我们需要构造一个该球圆心坐标以及半径的结构体如下。

struct _Ball {
	int x;     // 当前位置
	int y;
	float radius;  // 半径大小
	_Ball(int _x, int _y, int _r = 10):x(_x), y(_y), radius(_r){}
};

第二,我们需要对游戏机制做出具体的设计。由于是反应速度训练,球的出现时间必须限定,为了更好地吸引注意并且降低难度,球将从一开始的初始半径不断增长到指定值,到最大半径时若没有被射击,则该球消失,并对丢失球的计数miss_num+1。射击命中则score+1。
分析具体需要的结构:我们需要不断生成球,该球是需要不断增删的(点击就删除),且后生成的球半径肯定比前面生成的要大,因此我们可以模拟LRU的思想,利用list存储上述提到的结构体_Ball,来达到O(1)进行频繁增删的情况,利用map保存list迭代器,从而达到O(1)的查找时间,那么对于某点的增删改查都只需要O(1)的复杂度。虽然在本游戏中较少数据(毕竟球太多咱根本无法点击到)体现不出效果,但是这也是一种较好的思想。


二、主要模块的具体设计 1.查询新建的圆是否满足要求

这里主要满足两个要求:
1.对于新建的圆来说,我们需要其两个圆心之间的距离大于2*init_radius(初始半径大小)
2.对于鼠标坐标来说,我们需要判断该点在不在圆内(上)
代码如下:

inline int check(int& x, int& y, int r = init_radius) { //如果存在相撞的点,那么返回这个点的x坐标
	if (!lst.size())
		return 0;
	for (auto& iter : lst) {
		if (iter.x == x || (iter.x - x)*(iter.x - x)+(iter.y - y)* (iter.y - y) < (r + iter.radius)* (r + iter.radius))
			return iter.x;
	}
	return 0;
}

2.玩家操作模块的设计

玩家操作的代码是游戏逻辑的重点。
代码如下:

inline void player_ctrl(bool _using = true) { //玩家鼠标控制以及键盘控制消息输入
	if (!_using)
		return;
	mouse_msg mou_msg;  //鼠标消息结构体
	key_msg k_msg;      //键盘消息结构体
	bool isleftdown = false;

	thread getting_key([&]() { //键盘输入
		while (is_run()) {
			if (kbhit()) {
				k_msg = getkey();
				if (k_msg.key == 0x1b) { //0x1b为ESC,按下ESC关闭游戏窗口
					End_of_program();
				}
				score = 0;				//ESC外的任意键将重置时间、分数等
				game_time = fclock();
				miss_num = 0;
			}
		}
	});

	thread getting_mouse([&]() {
		while (is_run()) {
			// putchar(0);
			isleftdown = false;
			while (mousemsg()) {		//获取鼠标信息,不断查找是否有按下的消息,有则进行下一步
				mou_msg = getmouse(); 
				if (mou_msg.is_left() && mou_msg.is_down()) {
					isleftdown = true;
					break;
				}
			}
			if (isleftdown) {          //鼠标按下
				int x, y;
				mousepos(&x, &y);    //获取鼠标坐标
				my_mutex.lock(); //获取锁,多线程共享数据,因为修改操作会影响其线程迭代器的读取
				int x0 = check(x, y, 0);  
				if (x0) { //存在相撞的点,去掉该点
					lst.erase(mp[x0]);
					mp.erase(x0);
					score++;
				}
				my_mutex.unlock();
				flushmouse(); //将剩下的鼠标数据流清空
			}
		}
	});
	while (is_run()) {
		api_sleep(10);
	}
	getting_mouse.join(); 
}

完整代码

代码如下:


//#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
mutex my_mutex;
#define SCR_WIDTH      1200 // 窗口宽度
#define SCR_HEIGHT     800 // 窗口高度
#define MAX_BALL       10 // 同时存在的球最大值
#define init_radius    10 // 初始化球的半径
#define max_radius     40 // 最大球的半径,最大减最小半径/10 即为球的存在时间,球以0.1/10ms的速度进行增大
#define randnumx        SCR_WIDTH-max_radius*4+1  //随机出现的坐标相关设置
#define randnumy        SCR_HEIGHT-max_radius*4+1

struct _Ball {
	int x;     // 当前位置
	int y;
	float radius;  // 半径大小
	_Ball(int _x, int _y, int _r = 10):x(_x), y(_y), radius(_r){}
};

list<_Ball> lst;
unordered_map::iterator> mp;

unsigned miss_num = 0;
double game_time = 0;
unsigned score = 0;
char str[102];

inline void End_of_program() {
	puts("Got to the end.");
	cleardevice();
	closegraph();
	exit(1);
}
inline void MySleep(unsigned dms) {
	unsigned rec_time = clock();
	while (clock() - rec_time < dms);
	return;
}
inline void output_crash() {
	sprintf_s(str, "missing: %d times", miss_num);
	outtextxy(10, 10, str);
	sprintf_s(str, "time   : %.0f sec", fclock() - game_time);
	outtextxy(10, 40, str);
	sprintf_s(str, "score  : %d points", score);
	outtextxy(10, 70, str);
}
inline int check(int& x, int& y, int r = init_radius) { //如果存在相撞的点,那么返回这个点的x坐标
	if (!lst.size())
		return 0;
	for (auto& iter : lst) {
		if (iter.x == x || (iter.x - x)*(iter.x - x)+(iter.y - y)* (iter.y - y) < (r + iter.radius)* (r + iter.radius))
			return iter.x;
	}
	return 0;
}

inline void player_ctrl(bool _using = true) { //玩家鼠标控制,可能会删除数据
	if (!_using)
		return;
	mouse_msg mou_msg;
	key_msg k_msg;
	bool isleftdown = false;
	bool switch_state_space = false;
	bool switch_state_esc = false;
	thread getting_key([&]() {
		while (is_run()) {
			if (kbhit()) {
				k_msg = getkey();
				if (k_msg.key == 0x1b) {
					End_of_program();
				}
				score = 0;
				game_time = fclock();
				miss_num = 0;
			}
		}
	});

	thread getting_mouse([&]() {
		while (is_run()) {
			// putchar(0);
			isleftdown = false;
			while (mousemsg()) {//获取鼠标信息,没有则等待
				mou_msg = getmouse(); 
				if (mou_msg.is_left() && mou_msg.is_down()) {
					isleftdown = true;
					break;
				}
			}
			if (isleftdown) {
				int x, y;
				mousepos(&x, &y);
				my_mutex.lock();
				int x0 = check(x, y, 0);
				if (x0) { //存在相撞的点,去掉该点
					lst.erase(mp[x0]);
					mp.erase(x0);
					score++;
				}
				my_mutex.unlock();
				showmouse(true);
				flushmouse();
			}
		}
	});
	while (is_run()) {
		api_sleep(10);
	}
	getting_mouse.join(); 
}
inline void draw() { //将球打印出来
	for (; is_run(); delay_ms(10)) { 
		cleardevice();
		my_mutex.lock();
		for (auto &itr : mp) {
			_Ball b = *itr.second;
			fillellipse(b.x, b.y, b.radius, b.radius);
		}
		my_mutex.unlock();
		output_crash();
	}
	return ;
}

inline void createball() { //创建一个球,对mp和list中增加数据
	if (mp.size() == MAX_BALL)
		return ;
	int x, y;
	do {
	x = rand() % randnumx + max_radius*2;
	y = rand() % randnumy + max_radius*2;
	} while (check(x, y));
	_Ball ball(x, y, init_radius);
	lst.push_front(ball);
	mp[x] = lst.begin();
}

inline void refresh() { //检查末尾是否超时并添加,可能删除数据
	for (; is_run(); MySleep(10)) {
		if (!lst.size())
			continue;
		my_mutex.lock();
		for (auto& l : lst) 
			l.radius += 0.1;
		if (mp.size() < MAX_BALL)
			createball();
		if (lst.back().radius > max_radius) {
			mp.erase(lst.back().x);
			lst.pop_back();
			miss_num++;
		}
		my_mutex.unlock();
	}
	return ;
}

int main() {
	initgraph(SCR_WIDTH, SCR_HEIGHT, INIT_RENDERMANUAL | INIT_NOFORCEEXIT);
	setcaption("Click the balls as you can!");
	setcolor(WHITE);
	setfillcolor(BLACK);
	lst.push_front(_Ball(SCR_WIDTH/2, SCR_HEIGHT/2));
	mp[SCR_WIDTH / 2] = lst.begin();
	thread player_ctrl_thd(player_ctrl, 1);
	thread draw_thd(draw);
	thread refresh_thd(refresh);
	game_time = fclock(); // 记录当前窗口运行时间
	_set_abort_behavior(0, _WRITE_ABORT_MSG);

	player_ctrl_thd.join();
	refresh_thd.join();
	draw_thd.join();

	return 0;
}

总结

本文其实遇到了不少的BUG,虽然代码只有短短的一百多行。涵盖的内容其实并不少,一方面对于该进程的内存空间,线程可以直接访问,因此多线程竞争共享区需要上锁,这会带来一定的开销,虽然在该处体现不出,但是还是值得去思考该问题的方案。
此外,对于屏幕刷新,如果在短时间多次刷新屏幕并写入,会引起屏幕的闪烁。graphics内部可以通过关键字INIT_RENDERMANUAL 实现双缓存。
后来可能会维护该项目,比如优化界面、在实验室内部开辟空间添加排行榜信息等等。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/879655.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号