Skip to content

Instantly share code, notes, and snippets.

@egonelbre
Created February 28, 2016 12:41
Show Gist options
  • Save egonelbre/6dbae195c4c3724e878e to your computer and use it in GitHub Desktop.
Save egonelbre/6dbae195c4c3724e878e to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <assert.h>
#include <typeinfo>
namespace game {
class Object { virtual void _(){}; };
class Asteroid : public Object {};
class Ship : public Object {};
class Bullet : public Object {};
class Physics {
public:
#define collide(at, bt, block) \
{ \
at* a = dynamic_cast<at*>(x); \
bt* b = dynamic_cast<bt*>(y); \
if(a && b) block \
}
bool collides(Object *x, Object *y){
collide(Asteroid, Asteroid, {
printf("asteroid with asteroid\n");
return a == b;
});
collide(Ship, Ship, {
printf("ship with ship\n");
return a == b;
});
collide(Ship, Asteroid, {
printf("ship with asteroid\n");
return false;
});
// you can assert(false), if you don't have a match
// you can generate the type-switch which fails at compile time
// or use some template trickery to not use generation
return false;
};
#undef collide
};
}
int main(int argc, char const *argv[])
{
auto physics = new game::Physics();
auto asteroid = new game::Asteroid();
auto ship = new game::Ship();
auto bullet = new game::Bullet();
physics->collides(asteroid, asteroid);
physics->collides(asteroid, ship);
physics->collides(asteroid, bullet);
physics->collides(ship, asteroid);
physics->collides(ship, ship);
physics->collides(ship, bullet);
physics->collides(bullet, asteroid);
physics->collides(bullet, ship);
physics->collides(bullet, bullet);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment