1000来行的C++小游戏,
最近写了两个这种项目了。比较尴尬的行数,因为设计模式的作用在这种规模下不明显,各种内存泄漏和耦合的问题也显现不出来。但是还是学到了一些东西的。
1.使用了单例模式,以前只写过Java的单例,C++因为静态变量赋值和Java不一样(必须在类外显式地带类型定义),所以单例模式也是不一样的;
2.使用 了C++11多线程和互斥量,用来实现NPC的自由走动,在不同回合锁住;
3.类图的设计有点问题,这到后面才发现,Location类的封装太弱了,各个类的职责不够明确,导致找bug的时候比较麻烦,可想而知如果后面再增加一两千行就更难维护;
4.边界问题没有界定好,导致总是跨界访问报错,这也是类设计的问题,没有在开始想好;
5.尽量使用了C++11的特性
项目链接:点这里 欢迎Star
刚开始画的类图如下:

我做完之后的项目目录:

单例模式的一个实现。
#include "Detective.h"
#include<string.h>
Detective* Detective::uniqueDetective = nullptr; //唯一的初始化方法
Detective::Detective(){}
Detective* Detective::getInstance(string name, string description) {
if (uniqueDetective == nullptr) {
uniqueDetective = new Detective();
uniqueDetective->setName(name);
uniqueDetective->setDescription(description);
}
return uniqueDetective;
}
#pragma once
#include <vector>
#include "Person.h"
/*
* @ClassName : Detective
* @Auther : treblez
* @E-Mail : treblez@126.com
* @Date : 2020/11/04
* @Description : Use the singleton pattern to get the only Detective object
*/
class Detective :
public Person
{
private:
vector<string> note;
static int a;
static Detective* uniqueDetective;
Detective();
public:
static Detective* getInstance(string,string);
};
本文分享了一个约1000行的C++小游戏开发经验,包括单例模式的应用、C++11多线程及互斥量的使用、类图设计的重要性等。作者还讨论了项目中遇到的一些挑战,如类职责划分不清导致的bug查找困难。
506





