Here's my attempt to create a save feature for the 2d platformer game I am working on. I decided to only save the state of the character for now.
Unfortunately, it only works once. Whenever I try to restore from a savestate more then once, it crashes due to an assertion failure somewhere in boost/shared_ptr. What am I doing wrong? Is there a better way to do this?
SaveState class
#ifndef SAVESTATE_H
#define SAVESTATE_H
#include "thekid.h"
#include <cassert>
class SaveState
{
//Kid variables
const kid savedkid;
public:
SaveState(const kid& KidToSave): savedkid(KidToSave)
{ assert(savedkid.Alive()); }
kid RestoreFromSave() const
{ return savedkid; }
};
#endif
kid class header
#ifndef THEKID_H
#define THEKID_H
#include <vector>
#include "BOOST/shared_ptr.hpp"
#include "imagemanager.h"
#include "brush.h"
typedef std::vector<boost::shared_ptr<Brush> >* brushlist;
//Jump height is approximately 95 pixels
//95 = h = (V0*V0)/(2 * G)
//Jump duration about .8 seconds
// .8 = t = (2 * V0)/G
// h = V0 * t/4 <- initial jump speed is 475 pixels/second
//Horizontal move speed about 150 pixels/sec
//Remember to update all these values if the framerate is changed!
const double GRAVITY = .475;
const double JUMPV0 = -9.5;
const double XSPEED = 3;
const Uint32 NUMJUMPS = 2;
const double ANIMRATE = .03;
enum Animation{ STAND, WALK, JUMP, FALL};
enum Orientation{ RIGHT, LEFT};
class kid
{
//stuff to check collisions against
//Pointer not owned by the kid
brushlist worldbrushes;
img_sptr texture; //shared_ptr to an image class
double animcycle; //goes from 0 to 1 then repeats
Animation animstate;
Orientation facing;
double x,y;
double vx,vy; //used in case of being airborne
bool airborne;
boost::shared_ptr<const Brush> platform; //Brush the kid is currently standing on if not airborne
Uint32 jumpsleft;
bool isdead;
/////////////////////////////////////////
Uint32 GetAnimFrame() const;
public:
kid(double initialx, double initialy,
brushlist thebrushes);
void Update( int inputx, bool jump=false); //Inputx: -1=left, 0 = normal, 1=right
//void move( double dx, double dy);
void draw(SDL_Surface *screen, double xoff, double yoff) const;
double X() const {return x;}
double Y() const {return y;}
double Left() const {return x-15;}
double Top() const {return y-4;}
double Right() const {return x+7;}
double Bottom() const {return y+17;}
bool Alive() const {return !isdead;}
};
#endif
Save and loading code
//Globals
boost::shared_ptr<SaveState> lastsavestate;
boost::shared_ptr<kid> thekid;
//Save the game
if (thekid->Alive())
{
lastsavestate.reset(new SaveState(*thekid));
}
//Restore from last save
if (lastsavestate)
{
thekid.reset(& lastsavestate->RestoreFromSave());
}