C++ Refresher by Christopher Pelech




The Following are some super helpful classes that should give you an idea about some basic c++ structure.

This is the example of a main function. This is where the program starts. My background is in video game development so I tend to move all my code over to classes Click here to download the source

main.cpp

#include "GameManager.h"

int main() { 
	GameManager _GameManager;	
	_GameManager.Update(); 
}
					

This is a example of a Class Header. Within it you can find examples of a static variables, enums, and function definitions

GameManager.h

#pragma once
#include iostream
#include stdio.h
#include string
#include sstream
#include cctype
#include "WeaponManager.h"
#include "MathProblemManager.h"
using namespace std;

class GameManager
{
public:
	//=========== public Vars =================
	static bool GameActive;
	static string userName;
	static string answer;
	
	WeaponManager _WeaponManager;
	MathProblemManager _MathProblemManager;
	

	//=========== Enums ====================
	enum GameState{ GET_USER_NAME, WEAPON_MANAGER, MATH_PROBLEMS, BIT_SHIFTING,  QUITTING};	
	static GameState _currentGameState; 
	
	
	//=========== public Functions =================
	GameManager(void);
	~GameManager(void);

	// ==== Useful Functions ===================
	static void printScreen(string val);
	static void ClearScreen();
	static void Pause();
	static int GetIntFromInput();
	

	//====== Main game loop ===========
	void Update();

	// ===== Change current state ======
	static void ChangeState();

	//====== Our State functions ====================
	void GetUserName();
	void UpdateWeaponManager();
	void UpdateMathProblemManager();
	void UpdateBitShiftManager();
	void QuitGame();
};

#pragma endregion
					

This is the example of class definitions, as well as how to instantiate a public static var. In addition a good example of a state system is shown, as well as an basic I/O example.

GameManager.cpp

#include "GameManager.h"

//==================================== Static Vars =================================
GameManager::GameState GameManager::_currentGameState = GameManager::GameState::GET_USER_NAME;
bool GameManager::GameActive = true;
string GameManager::userName = "";
string GameManager::answer = "";

//======================	Constructor/Destructor ============================
GameManager::GameManager(void){
	
}

GameManager::~GameManager(void){

}

//======================	Useful Functions	============================
void GameManager::printScreen(string val){	cout << val <<"\n\n";	}
void GameManager::ClearScreen(){	std::system("CLS");	}
void GameManager::Pause(){	printScreen("Press Any Key to continue..."); getline(cin, answer); }
int GameManager::GetIntFromInput(){
	int val;
	bool success = false;
	bool failed = false;
	
	while(!success){
		if(failed) printScreen("\n(I'm sorry I didnt understand that, please Enter a number)");
		else printScreen("(Please input a Decimal Number: )");

		string input = "";	getline(cin, input);

		bool has_only_digits = true;
		for (size_t n = 0; n < input.length(); n++) {
			bool isNegativeSymbol = (input[n] == '-' && n == 0);
			if (!isdigit(input[n]) && !isNegativeSymbol){
				has_only_digits = false;	
				break;	
			}
		}

		if(has_only_digits) {	stringstream(input) >> val; success = true; }
		else { failed = true; }
	}

	
	
	return val;
}



//======================	Main Game Loop  	============================
void GameManager::Update(){
	while(GameActive){
		ClearScreen();
		if(_currentGameState == GameManager::GameState::GET_USER_NAME) GetUserName();
		else if(_currentGameState == GameManager::GameState::WEAPON_MANAGER) _WeaponManager.Update();
		else if(_currentGameState == GameManager::GameState::MATH_PROBLEMS) _MathProblemManager.Update();
		else if(_currentGameState == GameManager::GameState::BIT_SHIFTING) UpdateBitShiftManager();
		else if(_currentGameState == GameManager::GameState::QUITTING) QuitGame();
	}
}

void GameManager::ChangeState(){
	bool answeredCorrectly = false;
	bool failed = false;
	while(!answeredCorrectly){
		ClearScreen();
		if(failed){ failed = false; printScreen("I'm sorry I didnt catch that " + userName + ", please try again \n\n  0) Enter User Name \n  1) Weapon Manager \n  2) Math Problems \n  3) Bit Shifting \n  Q) Quit");}
		else {printScreen("Hello " + userName + ", Please Select a Option to continue: \n\n  0) Enter User Name \n  1) Weapon Manager \n  2) Math Problems \n  3) Bit Shifting \n  Q) Quit");}
		string val = "";
		getline(cin,val);
		if(val == "0") _currentGameState = GameState::GET_USER_NAME;
		else if(val == "1") _currentGameState = GameState::WEAPON_MANAGER;
		else if(val == "2") _currentGameState = GameState::MATH_PROBLEMS;
		else if(val == "3") _currentGameState = GameState::BIT_SHIFTING;
		else if(val == "Q" || val == "q") _currentGameState = GameState::QUITTING;
		else{	failed = true;	continue; }
		answeredCorrectly = true;
	}
}

//======================	Update the current state  	============================
void GameManager::GetUserName(){
	printScreen("Hello, my name is Thursday. What would you like me to call you?");	getline(cin,userName);
	ChangeState();
}

void GameManager::QuitGame(){
	printScreen("Are you sure you want to quit? (Press 0 to exit, anything else to cancel)");	
	getline(cin, answer);
	if(answer == "0") {GameActive = false;	printScreen(""); }
	else{ChangeState();}
}

void GameManager::UpdateWeaponManager(){		ChangeState();	}
void GameManager::UpdateMathProblemManager(){	ChangeState();	}
void GameManager::UpdateBitShiftManager(){		ChangeState();	}


					

Finally I'll show you a example of structs and how useful the vector class is by doing a basic weapon manager system.

WeaponManager.h

#pragma once
#include iostream>
#include stdio.h>
#include string>
#include vector>
using namespace std;

class WeaponManager
{
public:

	// ========== Structs =============
	struct WeaponItem{
		string WeaponName;
		int WeaponDamage;
		int AmmoLeft;
		int MaxAmmo;

		WeaponItem() : WeaponName("Null"), WeaponDamage(0), AmmoLeft(0), MaxAmmo(0) {}
		WeaponItem(string name, int damage, int ammo) : WeaponName(name), WeaponDamage(damage), AmmoLeft(ammo), MaxAmmo(ammo) {}

		void FireWeapon() {
			if (AmmoLeft > 0) { AmmoLeft -= 1;  cout << "\nFired the Weapon: " << WeaponName << ", did " << WeaponDamage << " damage, " << AmmoLeft << " ammo remaining";		}
			else{	cout << "\The Weapon: " << WeaponName << ", Does not have enough ammo to fire.";	}
		}

		void ReloadWeapon() {	AmmoLeft = MaxAmmo;	cout << "You have reloaded the weapon " << WeaponName;	}

		void PrintWeapon() {	cout << "\n Weapon Name: " << WeaponName << ", Damage: " << WeaponDamage << ",  Current Ammo: " << AmmoLeft << ", Max Ammo: " + MaxAmmo;	}

	};

	// ======= Enums =========
	enum WeaponManagerState { Idle, AddingWeapon, RemovingWeapon, PrintingWeaponList, ChangingWeapon, FiringCurrentWeapon, Reloading, Exit};

	// ======== Vars ===========
	static int CurrentWeaponItem;
	static std::vector[WeaponItem] Inventory;
	static WeaponManagerState currentState;

	// ======= Constructors =========
	WeaponManager(void);
	~WeaponManager(void);

	// ======= Functions =============
	void Update();

	void ChangeWeaponState();
	void AddWeapon();
	void RemoveWeapon();
	void PrintWeaponList();
	void ChangeCurrentWeapon();
	void FireCurrentWeapon();
	void DoReload();
	void DoExit();

	void backToIdle();
};

					

Just like before, here is the class definitions

WeaponManager.cpp

#include "GameManager.h"

#pragma region ====================  Static Vars ====================
WeaponManager::WeaponManagerState WeaponManager::currentState = WeaponManager::WeaponManagerState::Idle;
std::vector[WeaponManager::WeaponItem] WeaponManager::Inventory;
int WeaponManager::CurrentWeaponItem = -1;

#pragma endregion

#pragma region ====================  Constructors  ==================== 
WeaponManager::WeaponManager(void) {}
WeaponManager::~WeaponManager(void){}

#pragma endregion


#pragma region ====================  Generic Functions  ==================== 

void WeaponManager::DoExit() { GameManager::Pause(); GameManager::ChangeState(); }
void WeaponManager::backToIdle() { cout << "\n";	GameManager::Pause();	currentState = WeaponManagerState::Idle; }

#pragma endregion

#pragma region ====================  Main Loop  ==================== 

void WeaponManager::Update() {
	std::system("CLS");

	if (currentState == WeaponManagerState::Idle) { ChangeWeaponState(); }
	else if (currentState == WeaponManagerState::AddingWeapon) { AddWeapon(); }
	else if (currentState == WeaponManagerState::ChangingWeapon) { ChangeCurrentWeapon(); }
	else if (currentState == WeaponManagerState::FiringCurrentWeapon) { FireCurrentWeapon(); }
	else if (currentState == WeaponManagerState::PrintingWeaponList) { PrintWeaponList(); }
	else if (currentState == WeaponManagerState::RemovingWeapon) { RemoveWeapon(); }
	else if (currentState == WeaponManagerState::Reloading) { DoReload(); }
	else if (currentState == WeaponManagerState::Exit) {}
}

#pragma endregion


#pragma region ====================  Change State  ==================== 

void WeaponManager::ChangeWeaponState() {
	bool answeredCorrectly = false;
	bool failed = false;
	while (!answeredCorrectly) {
		std::system("CLS");
		string options = "\n\n1) AddingWeapon \n2) ChangingWeapon \n3) FiringCurrentWeapon \n4) PrintingWeaponList \n5) RemovingWeapon \n6) Reloading \nQ) Exit \n\n";
		if (failed) { failed = false; cout << "I'm sorry I didnt catch that , please try again " << options; }
		else { cout << "Please Select a Option to continue: " << options; }
		string val = "";
		getline(cin, val);
		if (val == "1") currentState = WeaponManagerState::AddingWeapon;
		else if (val == "2") currentState = WeaponManagerState::ChangingWeapon;
		else if (val == "3") currentState = WeaponManagerState::FiringCurrentWeapon;
		else if (val == "4") currentState = WeaponManagerState::PrintingWeaponList;
		else if (val == "5")currentState = WeaponManagerState::RemovingWeapon;
		else if (val == "6")currentState = WeaponManagerState::Reloading;
		else if (val == "Q" || val == "q") currentState = WeaponManagerState::Exit;
		else { failed = true;	continue; }
		answeredCorrectly = true;
	}

}
#pragma endregion


#pragma region ====================  Add Weapon  ==================== 
void WeaponManager::AddWeapon() {
	string _weaponName = "";
	cout << "\nPlease Enter a weapon name: \n\n";
	getline(cin, _weaponName);
	int damage = 0, ammo = 1;
	
	cout << "\nPlease Enter a weapon Damage: ";
	damage = GameManager::GetIntFromInput();

	cout << "\nPlease Enter a Max Ammo: ";
	ammo = GameManager::GetIntFromInput();
	
	WeaponManager::WeaponItem tempItem(_weaponName, damage, ammo);

	Inventory.push_back(tempItem);
	if (CurrentWeaponItem == -1) CurrentWeaponItem = 0;
	cout << "\n\nAdded the weapon: " << tempItem.WeaponName << ", to inventory \n";

	backToIdle();
}
#pragma endregion

#pragma region ====================  Change Current Weapon  ==================== 

void WeaponManager::ChangeCurrentWeapon() {
	if (Inventory.size() > 0) {
		bool success = false;
		bool failed = false;
		while (!success) {
			std::system("CLS");
			if (failed) cout << "\nI'm sorry I didnt catch that... What Index would you like to remove the in the list? \n";
			else cout << "\nWhat Index would you like to remove the in the list? \n";

			for (int i = 0; i < Inventory.size(); i++) { cout << "\n " << i << ") " << Inventory[i].WeaponName; }
			cout << "\n\n";
			int answer = GameManager::GetIntFromInput();
			if (answer > 0 && answer < Inventory.size()) {
				CurrentWeaponItem = answer;
				cout << "\nThe current selected weapon is: " << Inventory[CurrentWeaponItem].WeaponName << "\n";
				success = true;
			}
			else {
				failed = true;
			}
		}
	}
	else {
		cout << "\nI'm sorry the current inventory is empty\n";
	}

	backToIdle();
}
#pragma endregion

#pragma region ====================  Fire Current Weapon  ==================== 
void WeaponManager::FireCurrentWeapon() {
	if (CurrentWeaponItem == -1) {
		cout << "\nNo weapon is currently selected, please select a weapon\n";
	}else {

		bool firing = true;
		while (firing) {
			Inventory[CurrentWeaponItem].FireWeapon();
			cout << "\n\nWould you like to Fire Again? (0 = No, anything else for yes)\n";

			string answer = "";
			getline(cin, answer);
			if (answer == "0") { firing = false; }
			else{ std::system("CLS"); }
		}
	}
	
	backToIdle();
}
#pragma endregion

#pragma region ====================  Print Weapon List  ==================== 
void WeaponManager::PrintWeaponList() {
	cout << "\nPrinting the Inventory: \n";

	for (int i = 0; i < Inventory.size(); i++){ Inventory[i].PrintWeapon(); }

	backToIdle();
	
}
#pragma endregion

#pragma region ====================  Remove Weapon  ==================== 
void WeaponManager::RemoveWeapon() {
	if (Inventory.size() > 0) {
		bool success = false;
		bool failed = false;
		while (!success) {
			std::system("CLS");
			if(failed) cout << "\nI'm sorry I didnt catch that... What Index would you like to remove the in the list? \n";
			else cout << "\nWhat Index would you like to remove the in the list? \n";

			for (int i = 0; i < Inventory.size(); i++) { cout << "\n " << i << ") " << Inventory[i].WeaponName; }
			cout << "\n";
			int answer = GameManager::GetIntFromInput();
			if (answer >= 0 && answer < Inventory.size()) {
				Inventory.erase(Inventory.begin() + answer);	
				if (Inventory.size() == 0) {	CurrentWeaponItem = -1;	}
				else if (CurrentWeaponItem >= Inventory.size()) { CurrentWeaponItem = Inventory.size() - 1; }
				else if (CurrentWeaponItem >= answer) { CurrentWeaponItem -= 1; }
			}
			else {
				failed = true;
			}
		}
	}
	else {	cout << "\nI'm sorry the current inventory is empty";}

	backToIdle();

}
#pragma endregion

#pragma region ====================  Reload Weapon  ==================== 
void WeaponManager::DoReload() {
	if (CurrentWeaponItem == -1) {
		cout << "\nNo weapon is currently selected, please select a weapon";
	}
	else {
		Inventory[CurrentWeaponItem].ReloadWeapon();
	}

	backToIdle();
}
#pragma endregion




					

Hoped this refresher helped! Be sure to leave feedback

Leave a Comment:


Search

Coming Soon...