Genetic generation of cars in a 2D environment
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.
 
 
 
 
 

128 lines
2.7 KiB

//
// Game.m
// iOSGLEssentials
//
// Created by Joshua Moerman on 08/03/14.
//
//
#import "Game.h"
#include "Drawer.h"
#include "Car.h"
#include "Path.h"
#include <moggle/core/gl.hpp>
#include <Box2D/Box2D.h>
#include <string>
#include <map>
#include <functional>
using namespace moggle;
static int ncars = 10;
struct GameCPP{
std::map<std::string, std::function<void()>> actions;
bool should_regenerate = false;
int steps = 2;
std::string bundle;
Drawer drawer{bundle};
b2Vec2 gravity{0.0f, -10.0f};
b2World world{gravity};
std::vector<Car> cars;
Path path{world};
GameCPP(std::string const & bundle_)
: bundle(bundle_){
actions["regenerate"] = [this]{ should_regenerate = true; };
actions["speed"] = [this]{ steps *= 2; if(steps >= 32) steps = 2; };
path.buildUpTo(100);
create_cars();
drawer.SetFlags(b2Draw::e_shapeBit + b2Draw::e_jointBit);
world.SetDebugDraw(&drawer);
}
void create_cars(){
for(int i = 0; i < ncars; ++i){
cars.emplace_back(world);
}
}
void draw(){
drawer.camera = convert(getFurthest());
drawer.clear();
world.DrawDebugData();
drawer.draw();
}
void update(float dt){
if(should_regenerate){
should_regenerate = false;
cars.clear();
create_cars();
}
for(int i = 0; i < steps; ++i){
path.buildUpTo(getFurthest().x + 25);
world.Step(dt, 8, 3);
}
}
void resize(float width, float height){
drawer.resize(width, height);
}
b2Vec2 getFurthest() const {
b2Vec2 furthest = {0, 0};
for(auto&& c : cars){
auto p = c.getPosition();
if(p.x > furthest.x){
furthest = p;
}
}
return furthest;
}
};
@implementation Game{
GameCPP * game;
NSMutableArray * actions;
}
@synthesize windowSize, actions;
- (id)init{
if(self = [super init]){
NSString * path = [[NSBundle mainBundle] resourcePath];
game = new GameCPP([path UTF8String]);
actions = [NSMutableArray arrayWithCapacity: 10];
for(auto&& p : game->actions){
[actions addObject:[NSString stringWithUTF8String:p.first.c_str()]];
}
}
return self;
}
- (void)update:(float)dt{
game->update(dt);
}
- (void)draw{
game->draw();
}
- (void)action:(NSString *)a{
game->actions[[a UTF8String]]();
}
- (void)setWindowSize:(CGSize)windowSize_{
windowSize = windowSize_;
game->resize(windowSize.width, windowSize.height);
}
@end