Skip to content

The Basics

Leeor Dicker edited this page Aug 21, 2018 · 5 revisions

All NAS2D applications have the same basic construction.

'Utility' objects such as the Mixer, Renderer, Filesystem, EventHandler and Configuration objects are instantiated, a State object is instantiated and a standard application loop is entered.

Getting Started

For most intents and purposes, you'll use the Game object. The barebones for your entry point function will look like this:

#include <iostream>
#include "NAS2D/NAS2D.h"

int main(int argc, char *argv[])
{
	try
	{
		NAS2D::Game game("My game", argv[0], "config.xml");
		game.go(new StartState());
	}
	catch(Exception e)
	{
		std::cout << e.brief().c_str() << ": " << e.description().c_str() << std::endl;
	}
	catch(...)
	{
		std::cout << "Unexpected error." << std::endl;
	}

	return 0;
}

In the above example code, several parameters are passed to a Game object's constructor and then Game::go() is called with a pointer to a State called StartState.

What are State's?

States represent logical states in your program. For instance a title screen, an options screen, the main game screen, save and load screens, etc. Your state objects will derive from the State object and must overload two virtual functions, void initialize() and State* update(). These are called by the StateManager object which is handled by the Game object created above.

Using Core Objects

All other core objects such as the Renderer, Mixer, Filesystem and Configuration are accessed using the Utility object. Getting handles to these objects looks like this:

Utility<Renderer>::get();
Utility<Mixer>::get();
Utility<Filesystem>::get();

These calls will return a reference to the object type requested and will allow you to call the appropriate functions. As such you will frequently keep a reference to these objects to keep the code more readable:

Renderer& r = Utility<Renderer>::get();
Mixer& m = Utility<Mixer>::get();
	
r.drawBox(0, 0, 50, 50, 255, 255, 255, 255);
r.drawPixel(10, 10, 255, 0, 255, 255);
	
m.playSound(sound);

Exceptions & Exception Safety

NAS2D performs a lot of checks to ensure that the data and information passed into it makes sense. NAS2D does not attempt to correct errors and in many cases will throw an exception if it finds something out of place. As the end user of the API, you can catch specific errors you might expect or you an use a generic exception handler to gracefully terminate your application.

For example, if you want to load a bitmap font with a glyph size of 8x8 and an image size of 128x128, the expected glyph width/height will be 8. If either of these are not 8 or the image size is not 128x128 Font will throw NAS2D::font_invalid_glyph_map.