<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include <functional>
#include <stdint.h>

using namespace std;

vector<string> split(const string& str) {
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

using RoomID = int;

struct RoomObject
{
	vector<string> names;
	string description;
	bool visible;
};

struct Room;

struct Map
{
	static const int max_width = 100, max_height = 100;
	static const int player_start_x = 50, player_start_y = 50;
    	enum Location
    	{
		UNKNOWN,
		GRAVEYARD,
		GRAVEYARD_GATES,
		KHATHARRS_MOMS_HOUSE,
		GATES_OF_SHOGUN,
		HOUSE_OF_BLUES,
		FOGGY_FOREST,
        HOUSE_OF_GDNET = 999999,
        MAX_LOCATIONS
    	};
	Location map_location[max_width][max_height];
	int x, y;
	Map()
	{
        memset(map_location, UNKNOWN, sizeof(map_location));
		x = 50;
		y = 50;
		/*map_location[50][50] = GRAVEYARD;
		map_location[50][51] = GRAVEYARD_GATES;
		map_location[50][52] = KHATHARRS_MOMS_HOUSE;
		map_location[50][52] = GATES_OF_SHOGUN;
		map_location[50][53] = HOUSE_OF_BLUES;
		map_location[50][54] = FOGGY_FOREST;*/
	}

  unordered_map<RoomID, unique_ptr<Room>> rooms;
};

struct Entity
{
    Entity(string name, int maxHealth) : name(name), health(maxHealth) {}

    void heal(int points)
    {
        health = min(100, health + points);
        cout << name << " healed to " << health << " health" << endl;
    }

    void damage(int points)
    {
        health = max(0, health - points);
        cout << name << " damaged to " << health << "health" << endl;
    }

    int getHealth() const { return health; }

    // Return false if the entity didn't know the command
    virtual bool act(vector<string> commands) = 0;

    string name;
    //Map map;

private:
    int health;
};

struct Shogun : public Entity {
  Shogun() : Entity("Shogibear", 100) {}
};

struct Item
{
    virtual void apply(Entity* entity) = 0;
    virtual string identify() const = 0;
};

struct HealthItem : public Item
{
    HealthItem(int healPower) : healPower(healPower) {}

    void apply(Entity* entity) override
    {
        entity->heal(healPower);
    }

    string identify() const override
    {
        stringstream ss;
        ss << "Health Potion (" << healPower << ")";
        return ss.str();
    }

private:
    int healPower;
};
struct BlessedSword : public Item
{
    BlessedSword(int Weapon) : Weapon(Weapon){}
void apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";}
private: int Weapon;};//will add this to entity on my next commit. <.<

/*
struct ReallyFastSword : public Item
struct TheFastcall : public Entity
{
    TheFastcall() : Entity("The Fastcall", 22) {}
    virtual bool act(vector<string> commands) override
    {
    }
};
*/

struct Khawk : public Entity
{
    Khawk() : Entity("Khawk", INT_MAX) {}
};

struct MyopicRhino : public Entity
{
    MyopicRhino(): Entity("Nearsighted One", INT_MAX) {}
};

struct Room {
    Room(RoomID idnum, string i_description) : ID(idnum) {
        description = i_description;
    }
    virtual string describe() {
        stringstream ss;
        ss << description << "\n";
        ss << "Entities: "; for (auto& ent : entities) { ss << ent->name << ", "; }; ss << "\n"; //make this look nice later
        ss << "Items: "; for (auto& obj : objects) { ss << obj.names[0] << ", "; }; ss << "\n";  //make this look nice later
        ss << "Obvious exits: "; for (auto kv : exits) { ss << kv.first << ", "; } ss << "\n"; //...
        return ss.str();
    }
    const RoomID ID; //unique id of the room
    string description; //general description of the room for the player
    vector<unique_ptr<Entity>> entities;
    vector<RoomObject> objects;
    unordered_map<string, RoomID> exits; //keys are things like "north", "down", "cave", etc.
};

struct Graveyard : public Room
{
    Graveyard() : Room(Map::Location::GRAVEYARD, "The graveyard")
    {
        exits["north"] = Map::Location::GRAVEYARD_GATES;
    }
};

struct GraveyardGates : public Room
{
    GraveyardGates() : Room(Map::Location::GRAVEYARD_GATES, "Graveyard gates")
    {
        exits["east"] = Map::Location::KHATHARRS_MOMS_HOUSE;
    }
};

struct KhatharrsMomsHouse : public Room
{
    KhatharrsMomsHouse() : Room(Map::Location::KHATHARRS_MOMS_HOUSE, "Moms house")
    {
        exits["south"] = Map::Location::FOGGY_FOREST;
    }
};

struct GatesOfShogun : public Room
{
    GatesOfShogun() : Room(Map::Location::GATES_OF_SHOGUN, "SHOGUN!")
    {
        exits["west"] = Map::Location::FOGGY_FOREST;
    }
};

struct FoggyForest : public Room
{
    FoggyForest() : Room(Map::Location::FOGGY_FOREST, "Dark creepy forest")
    {

    }
};

struct HouseOfBlues : public Room
{
    HouseOfBlues() : Room(Map::Location::HOUSE_OF_BLUES, "Music and fried southern US food")
    {
        exits["north"] = Map::Location::KHATHARRS_MOMS_HOUSE;
    }
};

struct HouseOfGDNet : public Room
{
    HouseOfGDNet() : Room(Map::Location::HOUSE_OF_GDNET, "Where else would you want to be?")
    {
        exits["none"] = Map::Location::HOUSE_OF_GDNET;
        entities.push_back(make_unique<Khawk>());
        entities.push_back(make_unique<MyopicRhino>());
    }
};

typedef bool (*actionHandlerBYEBYENAMECOLLISION)(vector<string> commands); // unused, but we can't technically delete this, and commenting it out is just cheating.

struct Player : public Entity
{
    Player(string name, int health) : Entity(name, health)
    {
        currentLocation = Map::Location::GRAVEYARD;
        map.rooms[Map::Location::GRAVEYARD] = make_unique<Graveyard>();
        map.rooms[Map::Location::GRAVEYARD_GATES] = make_unique<GraveyardGates>();
        map.rooms[Map::Location::KHATHARRS_MOMS_HOUSE] = make_unique<KhatharrsMomsHouse>();
        map.rooms[Map::Location::GATES_OF_SHOGUN] = make_unique<GatesOfShogun>();
        map.rooms[Map::Location::HOUSE_OF_BLUES] = make_unique<HouseOfBlues>();
        map.rooms[Map::Location::FOGGY_FOREST] = make_unique<FoggyForest>();
    }

    bool act(vector<string> commands) override
    {
        auto cmd = commands[0];
        if(cmd == "n") { commands = vector<string>{"go","north"}; }
        if(cmd == "s") { commands = vector<string>{"go","south"}; }
        if(cmd == "e") { commands = vector<string>{"go","east"}; }
        if(cmd == "w") { commands = vector<string>{"go","west"}; }

        /*if (commands.size() >= 1 && commands[0] == "look")
        {
            look();
            return true;
        }*/
        else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
        {
        }
        else if (commands.size() >= 2 && commands[0] == "go")
        {
            if (!travel(commands[1]))
            {
                cout << "Can't travel " << commands[1] << endl;
            }
            return true;
        }
        else if (commands.size() >= 1 && commands[0] == "items")
        {
            showItems();
            return true;
        }
        else if (commands.size() >= 2 && commands[0] == "use")
        {
            int index = stoi(commands[1]);
            useItem(index);
            return true;
        }

        return false;
    }

    bool travel(string direction)
    {
	if (map.rooms.at(currentLocation)->exits.find(direction) == map.rooms.at(currentLocation)->exits.end())
		return false;
	currentLocation = map.rooms.at(currentLocation)->exits[direction];
  look();
  return true;
  /*
	if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
		return false;
	if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
		return false;
	if ((direction == "north"&&map.map_location[map.x][map.y + 1] == Map::UNKNOWN) || (direction == "south"&&map.map_location[map.x][map.y - 1] == Map::UNKNOWN) || (direction == "east"&&map.map_location[map.x + 1][map.y] == Map::UNKNOWN)||(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN))return false;
	if (direction == "north")map.y++; if (direction == "south")map.y--; if (direction == "east")map.x++; if (direction == "west")map.x--;
  */
        return true;/*
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                if (direction == "north")
                {
					map.y++;
                    return true;
                }
                break;
            case Map::GRAVEYARD_GATES:
                if (direction == "south")
                {
					map.y--;
                    return true;
                }
                if (direction == "north")
                {
                    map.y++;
                    return true;
                }
                break;
        }

        cout << "Can't travel " << direction << endl;
        return false;*/
    }

    void look()
    {
		cout << map.rooms.at(currentLocation)->describe() << endl;
		/*
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
                break;
            case Map::GRAVEYARD_GATES:
                cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
                break;
	    case Map::GATES_OF_SHOGUN:
		cout << "Here lies the Gates of the Great Shogun. Creator of A1 weaponry; able to fork stakes by a mere glare. It is said that to look into his eyes is to see your future covered in darkness. As you notice the thick red stains which cover the gates, you are reminded of the villagers' tales of sacrifices hung from these very gates. The gate has no lock. Do you enter?" << endl;
		break;
	    case Map::HOUSE_OF_BLUES:
		cout << "This is a place where men shed tears and pour out emotion! Of course, after 2 or 3 pints of the finest ale. The miscreants who frequent cavernous house know the warmth of beds not their own. Doors sing with laughter and a timely cry or two. Will you enter to find love?" << endl;
		break;
	    case Map::FOGGY_FOREST:
		cout << "Not much is known about this forest. Only that a wolf howls 3 times in the night, every night. And those who enter have never been known to return. Do you risk your life for adventure?" << endl;
		break;
        }
		*/
    }

    void giveItem(shared_ptr<Item> item)
    {
        inventory.push_back(item);
    }

    void showItems()
    {
        if (inventory.size() == 0)
            cout << "You have no items." << endl;
        int i = 1;
        for (auto item : inventory)
        {
            cout << "  " << i++ << ". " << item->identify() << std::endl;
        }
    }

    void useItem(size_t index)
    {
        if (index > inventory.size())
        {
            cout << "Invalid index" << endl;
            return;
        }

        inventory[index-1]->apply(this);
        inventory.erase(inventory.begin() + index - 1);
    }

    RoomID currentLocation;

private:
    vector<shared_ptr<Item>> inventory;
    unordered_map<string, function<bool(vector<string>)>> actions;

    Map map;
};

class Adventure
{
public:
    void begin()
    {
        string command;
        cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
        cout << "> ";
        getline(cin, command);

        Player player(command, 100);
        player.giveItem(make_shared<HealthItem>(20));

        cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
        player.look();

        while (player.getHealth() > 0)
        {
            cout << "> ";
            getline(cin, command);
            if (player.act(split(command)) == false)
                cout << "Unknown command" << endl;
        }

        cout << "You died. Game over." << endl;
    }
};

int main()
{
    Adventure adventure;
    adventure.begin();
    return 0;
}
<commit_msg>Some entities<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include <functional>
#include <stdint.h>

using namespace std;

vector<string> split(const string& str) {
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

using RoomID = int;

struct RoomObject
{
	vector<string> names;
	string description;
	bool visible;
};

struct Room;

struct Map
{
	static const int max_width = 100, max_height = 100;
	static const int player_start_x = 50, player_start_y = 50;
    	enum Location
    	{
		UNKNOWN,
		GRAVEYARD,
		GRAVEYARD_GATES,
		KHATHARRS_MOMS_HOUSE,
		GATES_OF_SHOGUN,
		HOUSE_OF_BLUES,
		FOGGY_FOREST,
        HOUSE_OF_GDNET = 999999,
        MAX_LOCATIONS
    	};
	Location map_location[max_width][max_height];
	int x, y;
	Map()
	{
        memset(map_location, UNKNOWN, sizeof(map_location));
		x = 50;
		y = 50;
		/*map_location[50][50] = GRAVEYARD;
		map_location[50][51] = GRAVEYARD_GATES;
		map_location[50][52] = KHATHARRS_MOMS_HOUSE;
		map_location[50][52] = GATES_OF_SHOGUN;
		map_location[50][53] = HOUSE_OF_BLUES;
		map_location[50][54] = FOGGY_FOREST;*/
	}

  unordered_map<RoomID, unique_ptr<Room>> rooms;
};

struct Entity
{
    Entity(string name, int maxHealth) : name(name), health(maxHealth) {}

    void heal(int points)
    {
        health = min(100, health + points);
        cout << name << " healed to " << health << " health" << endl;
    }

    void damage(int points)
    {
        health = max(0, health - points);
        cout << name << " damaged to " << health << "health" << endl;
    }

    int getHealth() const { return health; }

    // Return false if the entity didn't know the command
    virtual bool act(vector<string> commands) = 0;

    string name;
    //Map map;

private:
    int health;
};

struct Shogun : public Entity {
  Shogun() : Entity("Shogibear", 100) {}
};

struct Item
{
    virtual void apply(Entity* entity) = 0;
    virtual string identify() const = 0;
};

struct HealthItem : public Item
{
    HealthItem(int healPower) : healPower(healPower) {}

    void apply(Entity* entity) override
    {
        entity->heal(healPower);
    }

    string identify() const override
    {
        stringstream ss;
        ss << "Health Potion (" << healPower << ")";
        return ss.str();
    }

private:
    int healPower;
};
struct BlessedSword : public Item
{
    BlessedSword(int Weapon) : Weapon(Weapon){}
void apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";}
private: int Weapon;};//will add this to entity on my next commit. <.<

/*
struct ReallyFastSword : public Item
struct TheFastcall : public Entity
{
    TheFastcall() : Entity("The Fastcall", 22) {}
    virtual bool act(vector<string> commands) override
    {
    }
};
*/

struct Khawk : public Entity
{
    Khawk() : Entity("Khawk", INT_MAX) {}
    bool act(vector<string> commands) {}
};

struct MyopicRhino : public Entity
{
    MyopicRhino(): Entity("Nearsighted One", INT_MAX) {}
    bool act(vector<string> commands) {}
};

struct Room {
    Room(RoomID idnum, string i_description) : ID(idnum) {
        description = i_description;
    }
    virtual string describe() {
        stringstream ss;
        ss << description << "\n";
        ss << "Entities: "; for (auto& ent : entities) { ss << ent->name << ", "; }; ss << "\n"; //make this look nice later
        ss << "Items: "; for (auto& obj : objects) { ss << obj.names[0] << ", "; }; ss << "\n";  //make this look nice later
        ss << "Obvious exits: "; for (auto kv : exits) { ss << kv.first << ", "; } ss << "\n"; //...
        return ss.str();
    }
    const RoomID ID; //unique id of the room
    string description; //general description of the room for the player
    vector<unique_ptr<Entity>> entities;
    vector<RoomObject> objects;
    unordered_map<string, RoomID> exits; //keys are things like "north", "down", "cave", etc.
};

struct Graveyard : public Room
{
    Graveyard() : Room(Map::Location::GRAVEYARD, "The graveyard")
    {
        exits["north"] = Map::Location::GRAVEYARD_GATES;
    }
};

struct GraveyardGates : public Room
{
    GraveyardGates() : Room(Map::Location::GRAVEYARD_GATES, "Graveyard gates")
    {
        exits["east"] = Map::Location::KHATHARRS_MOMS_HOUSE;
    }
};

struct KhatharrsMomsHouse : public Room
{
    KhatharrsMomsHouse() : Room(Map::Location::KHATHARRS_MOMS_HOUSE, "Moms house")
    {
        exits["south"] = Map::Location::FOGGY_FOREST;
    }
};

struct GatesOfShogun : public Room
{
    GatesOfShogun() : Room(Map::Location::GATES_OF_SHOGUN, "SHOGUN!")
    {
        exits["west"] = Map::Location::FOGGY_FOREST;
    }
};

struct FoggyForest : public Room
{
    FoggyForest() : Room(Map::Location::FOGGY_FOREST, "Dark creepy forest")
    {

    }
};

struct HouseOfBlues : public Room
{
    HouseOfBlues() : Room(Map::Location::HOUSE_OF_BLUES, "Music and fried southern US food")
    {
        exits["north"] = Map::Location::KHATHARRS_MOMS_HOUSE;
    }
};

struct HouseOfGDNet : public Room
{
    HouseOfGDNet() : Room(Map::Location::HOUSE_OF_GDNET, "Where else would you want to be?")
    {
        exits["none"] = Map::Location::HOUSE_OF_GDNET;
        entities.push_back(make_unique<Khawk>());
        entities.push_back(make_unique<MyopicRhino>());
    }
};

typedef bool (*actionHandlerBYEBYENAMECOLLISION)(vector<string> commands); // unused, but we can't technically delete this, and commenting it out is just cheating.

struct Player : public Entity
{
    Player(string name, int health) : Entity(name, health)
    {
        currentLocation = Map::Location::GRAVEYARD;
        map.rooms[Map::Location::GRAVEYARD] = make_unique<Graveyard>();
        map.rooms[Map::Location::GRAVEYARD_GATES] = make_unique<GraveyardGates>();
        map.rooms[Map::Location::KHATHARRS_MOMS_HOUSE] = make_unique<KhatharrsMomsHouse>();
        map.rooms[Map::Location::GATES_OF_SHOGUN] = make_unique<GatesOfShogun>();
        map.rooms[Map::Location::HOUSE_OF_BLUES] = make_unique<HouseOfBlues>();
        map.rooms[Map::Location::FOGGY_FOREST] = make_unique<FoggyForest>();
    }

    bool act(vector<string> commands) override
    {
        auto cmd = commands[0];
        if(cmd == "n") { commands = vector<string>{"go","north"}; }
        if(cmd == "s") { commands = vector<string>{"go","south"}; }
        if(cmd == "e") { commands = vector<string>{"go","east"}; }
        if(cmd == "w") { commands = vector<string>{"go","west"}; }

        /*if (commands.size() >= 1 && commands[0] == "look")
        {
            look();
            return true;
        }*/
        else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
        {
        }
        else if (commands.size() >= 2 && commands[0] == "go")
        {
            if (!travel(commands[1]))
            {
                cout << "Can't travel " << commands[1] << endl;
            }
            return true;
        }
        else if (commands.size() >= 1 && commands[0] == "items")
        {
            showItems();
            return true;
        }
        else if (commands.size() >= 2 && commands[0] == "use")
        {
            int index = stoi(commands[1]);
            useItem(index);
            return true;
        }

        return false;
    }

    bool travel(string direction)
    {
	if (map.rooms.at(currentLocation)->exits.find(direction) == map.rooms.at(currentLocation)->exits.end())
		return false;
	currentLocation = map.rooms.at(currentLocation)->exits[direction];
  look();
  return true;
  /*
	if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
		return false;
	if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
		return false;
	if ((direction == "north"&&map.map_location[map.x][map.y + 1] == Map::UNKNOWN) || (direction == "south"&&map.map_location[map.x][map.y - 1] == Map::UNKNOWN) || (direction == "east"&&map.map_location[map.x + 1][map.y] == Map::UNKNOWN)||(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN))return false;
	if (direction == "north")map.y++; if (direction == "south")map.y--; if (direction == "east")map.x++; if (direction == "west")map.x--;
  */
        return true;/*
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                if (direction == "north")
                {
					map.y++;
                    return true;
                }
                break;
            case Map::GRAVEYARD_GATES:
                if (direction == "south")
                {
					map.y--;
                    return true;
                }
                if (direction == "north")
                {
                    map.y++;
                    return true;
                }
                break;
        }

        cout << "Can't travel " << direction << endl;
        return false;*/
    }

    void look()
    {
		cout << map.rooms.at(currentLocation)->describe() << endl;
		/*
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
                break;
            case Map::GRAVEYARD_GATES:
                cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
                break;
	    case Map::GATES_OF_SHOGUN:
		cout << "Here lies the Gates of the Great Shogun. Creator of A1 weaponry; able to fork stakes by a mere glare. It is said that to look into his eyes is to see your future covered in darkness. As you notice the thick red stains which cover the gates, you are reminded of the villagers' tales of sacrifices hung from these very gates. The gate has no lock. Do you enter?" << endl;
		break;
	    case Map::HOUSE_OF_BLUES:
		cout << "This is a place where men shed tears and pour out emotion! Of course, after 2 or 3 pints of the finest ale. The miscreants who frequent cavernous house know the warmth of beds not their own. Doors sing with laughter and a timely cry or two. Will you enter to find love?" << endl;
		break;
	    case Map::FOGGY_FOREST:
		cout << "Not much is known about this forest. Only that a wolf howls 3 times in the night, every night. And those who enter have never been known to return. Do you risk your life for adventure?" << endl;
		break;
        }
		*/
    }

    void giveItem(shared_ptr<Item> item)
    {
        inventory.push_back(item);
    }

    void showItems()
    {
        if (inventory.size() == 0)
            cout << "You have no items." << endl;
        int i = 1;
        for (auto item : inventory)
        {
            cout << "  " << i++ << ". " << item->identify() << std::endl;
        }
    }

    void useItem(size_t index)
    {
        if (index > inventory.size())
        {
            cout << "Invalid index" << endl;
            return;
        }

        inventory[index-1]->apply(this);
        inventory.erase(inventory.begin() + index - 1);
    }

    RoomID currentLocation;

private:
    vector<shared_ptr<Item>> inventory;
    unordered_map<string, function<bool(vector<string>)>> actions;

    Map map;
};

class Adventure
{
public:
    void begin()
    {
        string command;
        cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
        cout << "> ";
        getline(cin, command);

        Player player(command, 100);
        player.giveItem(make_shared<HealthItem>(20));

        cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
        player.look();

        while (player.getHealth() > 0)
        {
            cout << "> ";
            getline(cin, command);
            if (player.act(split(command)) == false)
                cout << "Unknown command" << endl;
        }

        cout << "You died. Game over." << endl;
    }
};

int main()
{
    Adventure adventure;
    adventure.begin();
    return 0;
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <stdexcept>
#include "source.hpp"
#include "lexer.hpp"
#include "parser.hpp"
#include "pprint/c_pprint.hpp"

static const char PROGNAME[] = "bfc";
static const char FILETYPE[] = "bf";
static const size_t FILETYPE_LEN = 2;
// TODO: add version number (requires configure setup)

using namespace bfc;

static void
print_usage(FILE *out)
{
  fprintf(out, "usage: %s <source-file>\n", PROGNAME);
}

static void
print_filename_error(FILE *out)
{
  fprintf(out, "file must be of type %s\n", FILETYPE);
}

static int
handle_filepath(const char *filepath)
{
  size_t len = strlen(filepath);
  if (filepath[len - FILETYPE_LEN - 1] != '.'){
    print_filename_error(stderr);
    return -1;
  }

  for (size_t i = FILETYPE_LEN ; i > 0; --i){
    if (filepath[len - i] != FILETYPE[FILETYPE_LEN - i]){
      print_filename_error(stderr);
      return -1;
    }
  }

  parser<stream_source> parser{
    lexer<stream_source>{stream_source{new std::fstream{filepath}}}};
  try
  {
    ast_node ast = parser.parse();
  }
  catch (std::runtime_error& e)
  {
    printf("%s", e.what());
    return -2;
  }
  pprint::c_pprint printer{};
  std::ofstream output{std::string{filepath} + ".c"};
  printer.emit(output, ast);

  return 0;
}

int
main(int argc, const char *const *argv)
{
  if (argc != 2) {
    print_usage(stderr);
    exit(EXIT_FAILURE);
  }

  handle_filepath(argv[1]);

  return 0;
}
<commit_msg>Rename variable to avoid namespace issue<commit_after>#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <stdexcept>
#include "source.hpp"
#include "lexer.hpp"
#include "parser.hpp"
#include "pprint/c_pprint.hpp"

static const char PROGNAME[] = "bfc";
static const char FILETYPE[] = "bf";
static const size_t FILETYPE_LEN = 2;
// TODO: add version number (requires configure setup)

using namespace bfc;

static void
print_usage(FILE *out)
{
  fprintf(out, "usage: %s <source-file>\n", PROGNAME);
}

static void
print_filename_error(FILE *out)
{
  fprintf(out, "file must be of type %s\n", FILETYPE);
}

static int
handle_filepath(const char *filepath)
{
  size_t len = strlen(filepath);
  if (filepath[len - FILETYPE_LEN - 1] != '.'){
    print_filename_error(stderr);
    return -1;
  }

  for (size_t i = FILETYPE_LEN ; i > 0; --i){
    if (filepath[len - i] != FILETYPE[FILETYPE_LEN - i]){
      print_filename_error(stderr);
      return -1;
    }
  }

  parser<stream_source> parser{
    lexer<stream_source>{stream_source{new std::fstream{filepath}}}};
  try
  {
    ast_node astNode= parser.parse();
  }
  catch (std::runtime_error& e)
  {
    printf("%s", e.what());
    return -2;
  }
  pprint::c_pprint printer{};
  std::ofstream output{std::string{filepath} + ".c"};
  printer.emit(output, astNode);

  return 0;
}

int
main(int argc, const char *const *argv)
{
  if (argc != 2) {
    print_usage(stderr);
    exit(EXIT_FAILURE);
  }

  handle_filepath(argv[1]);

  return 0;
}
<|endoftext|>


<commit_before>a6f36907-2747-11e6-b4b3-e0f84713e7b8<commit_msg>Did a thing<commit_after>a708c033-2747-11e6-aa40-e0f84713e7b8<|endoftext|>


<commit_before>b7f24b75-4b02-11e5-abd0-28cfe9171a43<commit_msg>lets try again<commit_after>b7ff531e-4b02-11e5-ad1c-28cfe9171a43<|endoftext|>


<commit_before>a59e1711-2747-11e6-8080-e0f84713e7b8<commit_msg>For roselyn to integrate at some point<commit_after>a5af8223-2747-11e6-a450-e0f84713e7b8<|endoftext|>


<commit_before>2c81bb75-2748-11e6-9150-e0f84713e7b8<commit_msg>We apologise for the previous fix. Those responsible have been sacked<commit_after>2c8df33a-2748-11e6-b09f-e0f84713e7b8<|endoftext|>


<commit_before>51f5bcc2-2748-11e6-a51b-e0f84713e7b8<commit_msg>I hope I am done<commit_after>51ffafae-2748-11e6-9002-e0f84713e7b8<|endoftext|>


<commit_before>//
//  main.cpp
//  ArduinoCommTest
//
//  Created by James Rees on 10/04/2015.
//  Copyright (c) 2015 James Rees. All rights reserved.
//
#include <chrono>
#include <thread>
#include <iostream>
//#include "cArduino.h"

int main(int argc, const char * argv[]) {

  //  cArduino arduino(ArduinoBaundRate::B9600bps);
       //const FILE *file;

    FILE* file;
    file = fopen("/dev/cu.usbmodem1421","w");  //Opening device file

    while(true){
    fprintf(file,"%d", 'a'); //Writing to the file
    fprintf(file,"%c",','); //To separate digits
    fprintf(file,"%c",','); //To separate digits
    }
   // std::cout << file[0] << std::endl;

    fclose(file);

    return 0;
}
<commit_msg>Delete main.cpp<commit_after><|endoftext|>


<commit_before>//for c and posix
//#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>

//for c++
#include <string>
#include <fstream>
#include <iostream>
#include <unordered_map>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <future>

namespace cnc
{
    class ThreadPool
    {
    public:
        ThreadPool(size_t);

        template<class F, class... Args>
        auto enqueue(F &&f, Args &&... args) -> std::future<typename std::result_of<F(Args...)>::type>;

        ~ThreadPool();

    private:
        // need to keep track of threads so we can join them
        std::vector<std::thread> workers;
        // the task queue
        std::queue<std::function<void()>> tasks;

        // synchronization
        std::mutex queue_mutex;
        std::condition_variable condition;
        bool stop;
    };

    // the constructor just launches some amount of workers
    inline ThreadPool::ThreadPool(size_t threads)
            : stop(false)
    {
        for (size_t i = 0; i < threads; ++i)
            workers.emplace_back(
                    [this]
                    {
                        for (; ;)
                        {
                            std::function<void()> task;

                            {
                                std::unique_lock<std::mutex> lock(this->queue_mutex);
                                this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); });
                                if (this->stop && this->tasks.empty())
                                    return;
                                task = std::move(this->tasks.front());
                                this->tasks.pop();
                            }

                            task();
                        }
                    }
            );
    }

    // add new work item to the pool
    template<class F, class... Args>
    auto ThreadPool::enqueue(F &&f, Args &&... args) -> std::future<typename std::result_of<F(Args...)>::type> {
        using return_type = typename std::result_of<F(Args...)>::type;

        auto task = std::make_shared<std::packaged_task<return_type()>>
        (
                std::bind(std::forward<F>(f), std::forward<Args>(args)...)
        );

        std::future<return_type> res = task->get_future();
        {
            std::unique_lock<std::mutex> lock(queue_mutex);

            // don't allow enqueueing after stopping the pool
            if (stop)
                throw std::runtime_error("enqueue on stopped ThreadPool");

            tasks.emplace([task]() { (*task)(); });
        }
        condition.notify_one();
        return res;
    }

    // the destructor joins all threads
    inline ThreadPool::~ThreadPool()
    {
        {
            std::unique_lock<std::mutex> lock(queue_mutex);
            stop = true;
        }
        condition.notify_all();
        for (auto& worker: workers) worker.join();
    }

    template<typename Socket>
    void send_file(std::string const &filename, Socket const &socket)
    {
        std::ifstream ifs{filename};
        for (std::string str; ifs >> str;)
        {
            auto msg = str + "\r\n";
            send(socket, msg.c_str(), msg.size(), 0);
        }
    }

    template <typename StatusCode>
    auto make_reply_header(StatusCode code) -> std::string
    {
        const static std::unordered_map<StatusCode, std::string> status
                {
                        {200, "200 OK"},
                        {404, "404 Not Found"},
                        {501, "501 Not Implemented"}
                };

        return "HTTP/1.1 "  + status.at(code) + "\r\nContent-Type: text/html\r\n\r\n";
    }

    template <typename Socket>
    void enable_port_reusable(Socket soc)
    {
        auto optval = 1;
        setsockopt(soc, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval);
    }

    template <typename Socket, typename Integer>
    class Server
    {
    public:
        explicit Server(int port_no, std::size_t incoming_limit, Integer max_times = 9999)
                :
                _socket{ init_socket(port_no) },
                _port{ port_no },
                _limit{ incoming_limit },
                _pool( incoming_limit ),
                _max_times{ max_times }
        {
            listen(_socket, (int)incoming_limit);

        }

        auto start( int delay ) -> Integer
        {
           return run(_max_times, delay);
        }

    private:
        Socket const _socket;
        int const _port;
        std::size_t const _limit;
        ThreadPool _pool;
        Integer _max_times;

        auto init_socket(std::size_t port) const -> Socket
        {
            struct sockaddr_in addr;
            addr.sin_family = AF_INET;
            addr.sin_port = htons(port);
            addr.sin_addr.s_addr = INADDR_ANY;
            memset( addr.sin_zero, '\0', sizeof(addr.sin_zero) );

            // Create a socket and bind it the port PORT
            auto const soc = socket(PF_INET,SOCK_STREAM, 0);

            cnc::enable_port_reusable(soc);
            auto bind_result = bind(soc, (struct sockaddr *)&addr, sizeof(addr));
            if (bind_result != 0)
                std::cout << errno << std::endl;

            return soc;
        }

        auto run(Integer const max, int delay) -> Integer
        {
            auto curr = max;
            for(auto const header = cnc::make_reply_header(200); curr != 0; --curr)
            {
                auto request_handler = [&](Socket socket){
                    std::cout << "Thread[" << std::this_thread::get_id() << "] is working on socket ["  << socket << "]" << std::endl;

                    char data[512];
                    char filename[256];
                    auto size = recv(socket, data, 512, 0);                 // recieve the request using fd
                    data[size] = 0;                                         // NUL terminate it
                    sscanf(data, "GET /%s ", filename);                     // get the name of the file
                    send(socket, header.c_str(), header.size(), 0);
                    std::this_thread::sleep_for(std::chrono::seconds(delay));
                    cnc::send_file(filename, socket);
                    close(socket);                                          // close the socket
                };

                _pool.enqueue(request_handler, accept(_socket, NULL, NULL));
            }

            return  max - curr;
        }

    };

}// end of namespace cnc

int main()
{
    auto port = 3490;
    auto limit = 10u;
    cnc::Server< int, long long > server{ port, limit};

    auto delay = 5;
    server.start(delay);

//    auto const PORT = 3490;
//
//    struct sockaddr_in addr;
//    addr.sin_family = AF_INET;
//    addr.sin_port = htons(PORT);
//    addr.sin_addr.s_addr = INADDR_ANY;
//    memset( addr.sin_zero, '\0', sizeof(addr.sin_zero) );
//
//    // Create a socket and bind it the port PORT
//    auto const soc = socket(PF_INET,SOCK_STREAM, 0);
//
//    cnc::enable_port_reusable(soc);
//    auto bind_result = bind(soc, (struct sockaddr *)&addr, sizeof(addr));
//    if (bind_result != 0)
//        std::cout << errno << std::endl;
//
//    // Allow up to 10 incoming connections
//    auto const limit = 10;
//    listen(soc,limit);
//    std::cout << "listenning\n";
//
//    auto const header = cnc::make_reply_header(200);
//    for(cnc::ThreadPool pool{ limit }; true;)
//    {
//        auto request_handler = [&](int socket){
//            std::cout << "Thread[" << std::this_thread::get_id() << "] is working on socket ["  << socket << "]" << std::endl;
//
//            char data[512];
//            char filename[256];
//            auto size = recv(socket, data, 512, 0);                 // recieve the request using fd
//            data[size] = 0;                                         // NUL terminate it
//            sscanf(data, "GET /%s ", filename);                     // get the name of the file
//            send(socket, header.c_str(), header.size(), 0);
//            std::this_thread::sleep_for(std::chrono::seconds(2));
//            cnc::send_file(filename, socket);
//            close(socket);                                          // close the socket
//        };
//
//        pool.enqueue(request_handler, accept(soc, NULL, NULL));
//    }
}
<commit_msg>add dtor to close _socket<commit_after>//for c and posix
//#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>

//for c++
#include <string>
#include <fstream>
#include <iostream>
#include <unordered_map>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <future>

namespace cnc
{
    class ThreadPool
    {
    public:
        ThreadPool(size_t);

        template<class F, class... Args>
        auto enqueue(F &&f, Args &&... args) -> std::future<typename std::result_of<F(Args...)>::type>;

        ~ThreadPool();

    private:
        // need to keep track of threads so we can join them
        std::vector<std::thread> workers;
        // the task queue
        std::queue<std::function<void()>> tasks;

        // synchronization
        std::mutex queue_mutex;
        std::condition_variable condition;
        bool stop;
    };

    // the constructor just launches some amount of workers
    inline ThreadPool::ThreadPool(size_t threads)
            : stop(false)
    {
        for (size_t i = 0; i < threads; ++i)
            workers.emplace_back(
                    [this]
                    {
                        for (; ;)
                        {
                            std::function<void()> task;

                            {
                                std::unique_lock<std::mutex> lock(this->queue_mutex);
                                this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); });
                                if (this->stop && this->tasks.empty())
                                    return;
                                task = std::move(this->tasks.front());
                                this->tasks.pop();
                            }

                            task();
                        }
                    }
            );
    }

    // add new work item to the pool
    template<class F, class... Args>
    auto ThreadPool::enqueue(F &&f, Args &&... args) -> std::future<typename std::result_of<F(Args...)>::type> {
        using return_type = typename std::result_of<F(Args...)>::type;

        auto task = std::make_shared<std::packaged_task<return_type()>>
        (
                std::bind(std::forward<F>(f), std::forward<Args>(args)...)
        );

        std::future<return_type> res = task->get_future();
        {
            std::unique_lock<std::mutex> lock(queue_mutex);

            // don't allow enqueueing after stopping the pool
            if (stop)
                throw std::runtime_error("enqueue on stopped ThreadPool");

            tasks.emplace([task]() { (*task)(); });
        }
        condition.notify_one();
        return res;
    }

    // the destructor joins all threads
    inline ThreadPool::~ThreadPool()
    {
        {
            std::unique_lock<std::mutex> lock(queue_mutex);
            stop = true;
        }
        condition.notify_all();
        for (auto& worker: workers) worker.join();
    }

    template<typename Socket>
    void send_file(std::string const &filename, Socket const &socket)
    {
        std::ifstream ifs{filename};
        for (std::string str; ifs >> str;)
        {
            auto msg = str + "\r\n";
            send(socket, msg.c_str(), msg.size(), 0);
        }
    }

    template <typename StatusCode>
    auto make_reply_header(StatusCode code) -> std::string
    {
        const static std::unordered_map<StatusCode, std::string> status
                {
                        {200, "200 OK"},
                        {404, "404 Not Found"},
                        {501, "501 Not Implemented"}
                };

        return "HTTP/1.1 "  + status.at(code) + "\r\nContent-Type: text/html\r\n\r\n";
    }

    template <typename Socket>
    void enable_port_reusable(Socket soc)
    {
        auto optval = 1;
        setsockopt(soc, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval);
    }

    template <typename Socket, typename Integer>
    class Server
    {
    public:
        explicit Server(int port_no, std::size_t incoming_limit, Integer max_times = 9999) :
                _socket{ init_socket(port_no) },
                _port{ port_no },
                _limit{ incoming_limit },
                _pool( incoming_limit ),
                _max_times{ max_times }
        {
            listen(_socket, (int)incoming_limit);

        }

        auto start( int delay ) -> Integer
        {
           return run(_max_times, delay);
        }

        ~Server()
        {
            close(_socket);
        }

    private:
        Socket const _socket;
        int const _port;
        std::size_t const _limit;
        ThreadPool _pool;
        Integer _max_times;

        auto init_socket(std::size_t port) const -> Socket
        {
            struct sockaddr_in addr;
            addr.sin_family = AF_INET;
            addr.sin_port = htons(port);
            addr.sin_addr.s_addr = INADDR_ANY;
            memset( addr.sin_zero, '\0', sizeof(addr.sin_zero) );

            // Create a socket and bind it the port PORT
            auto const soc = socket(PF_INET,SOCK_STREAM, 0);

            cnc::enable_port_reusable(soc);
            auto bind_result = bind(soc, (struct sockaddr *)&addr, sizeof(addr));
            if (bind_result != 0)
                std::cout << errno << std::endl;

            return soc;
        }

        auto run(Integer const max, int delay) -> Integer
        {
            auto curr = max;
            for(auto const header = cnc::make_reply_header(200); curr != 0; --curr)
            {
                auto request_handler = [&](Socket socket){
                    std::cout << "Thread[" << std::this_thread::get_id() << "] is working on socket ["  << socket << "]" << std::endl;

                    char data[512];
                    char filename[256];
                    auto size = recv(socket, data, 512, 0);                 // recieve the request using fd
                    data[size] = 0;                                         // NUL terminate it
                    sscanf(data, "GET /%s ", filename);                     // get the name of the file
                    send(socket, header.c_str(), header.size(), 0);
                    std::this_thread::sleep_for(std::chrono::seconds(delay));
                    cnc::send_file(filename, socket);
                    close(socket);                                          // close the socket
                };

                _pool.enqueue(request_handler, accept(_socket, NULL, NULL));
            }

            return  max - curr;
        }

    };

}// end of namespace cnc

int main()
{
    auto port = 3490;
    auto limit = 10u;
    cnc::Server< int, long long > server{ port, limit};

    auto delay = 5;
    server.start(delay);

//    auto const PORT = 3490;
//
//    struct sockaddr_in addr;
//    addr.sin_family = AF_INET;
//    addr.sin_port = htons(PORT);
//    addr.sin_addr.s_addr = INADDR_ANY;
//    memset( addr.sin_zero, '\0', sizeof(addr.sin_zero) );
//
//    // Create a socket and bind it the port PORT
//    auto const soc = socket(PF_INET,SOCK_STREAM, 0);
//
//    cnc::enable_port_reusable(soc);
//    auto bind_result = bind(soc, (struct sockaddr *)&addr, sizeof(addr));
//    if (bind_result != 0)
//        std::cout << errno << std::endl;
//
//    // Allow up to 10 incoming connections
//    auto const limit = 10;
//    listen(soc,limit);
//    std::cout << "listenning\n";
//
//    auto const header = cnc::make_reply_header(200);
//    for(cnc::ThreadPool pool{ limit }; true;)
//    {
//        auto request_handler = [&](int socket){
//            std::cout << "Thread[" << std::this_thread::get_id() << "] is working on socket ["  << socket << "]" << std::endl;
//
//            char data[512];
//            char filename[256];
//            auto size = recv(socket, data, 512, 0);                 // recieve the request using fd
//            data[size] = 0;                                         // NUL terminate it
//            sscanf(data, "GET /%s ", filename);                     // get the name of the file
//            send(socket, header.c_str(), header.size(), 0);
//            std::this_thread::sleep_for(std::chrono::seconds(2));
//            cnc::send_file(filename, socket);
//            close(socket);                                          // close the socket
//        };
//
//        pool.enqueue(request_handler, accept(soc, NULL, NULL));
//    }
}
<|endoftext|>


<commit_before>#include "html5viewer/html5viewer.h"
#include "ClientWrapper.hpp"
#include "Utilities.hpp"
#include "MainWindow.hpp"

#include <boost/thread.hpp>
#include <bts/blockchain/config.hpp>
#include <signal.h>

#include <QApplication>
#include <QSettings>
#include <QPixmap>
#include <QErrorMessage>
#include <QSplashScreen>
#include <QDir>
#include <QWebSettings>
#include <QWebPage>
#include <QWebFrame>
#include <QJsonDocument>
#include <QGraphicsWebView>
#include <QTimer>
#include <QAuthenticator>
#include <QNetworkReply>
#include <QResource>
#include <QGraphicsWidget>
#include <QMainWindow>
#include <QMenuBar>
#include <QLayout>

#include <boost/program_options.hpp>

#include <bts/client/client.hpp>
#include <bts/net/upnp.hpp>
#include <bts/blockchain/chain_database.hpp>
#include <bts/rpc/rpc_server.hpp>
#include <bts/cli/cli.hpp>
#include <bts/utilities/git_revision.hpp>
#include <fc/filesystem.hpp>
#include <fc/thread/thread.hpp>
#include <fc/log/file_appender.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/io/json.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/git_revision.hpp>
#include <fc/io/json.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/signals.hpp>

#include <boost/iostreams/tee.hpp>
#include <boost/iostreams/stream.hpp>

#include <fstream>
#include <iostream>
#include <iomanip>

#ifdef NDEBUG
#include "config_prod.hpp"
#else
#include "config_dev.hpp"
#endif

class UrlReceiver : public QObject {
public:
    UrlReceiver(QObject* parent = 0):QObject(parent){}
    virtual bool eventFilter(QObject *, QEvent* event) {
        if (event->type() == QEvent::FileOpen) {
            ilog("Got FOE");
            return true;
        }
        return false;
    }
};

void setupMenus(Html5Viewer* viewer, ClientWrapper* client, MainWindow* mainWindow)
{
    auto accountMenu = mainWindow->accountMenu();

    QObject::connect(accountMenu->addAction("&Go to My Accounts"), &QAction::triggered, [viewer,client](){
        viewer->loadUrl(client->http_url().toString() + "/#/accounts");
    });
    QObject::connect(accountMenu->addAction("&Create Account"), &QAction::triggered, [viewer,client](){
        viewer->loadUrl(client->http_url().toString() + "/#/create/account");
    });
    accountMenu->addAction("&Import Account")->setEnabled(false);

    //Enable accountMenu only when wallet is unlocked.
    accountMenu->setEnabled(false);
    client->get_client()->get_wallet()->wallet_lock_state_changed.connect([accountMenu](bool locked){
        accountMenu->setEnabled(!locked);
    });
}

void prepareStartupSequence(ClientWrapper* client, Html5Viewer* viewer, MainWindow* mainWindow, QSplashScreen* splash)
{
    viewer->webView()->page()->mainFrame()->addToJavaScriptWindowObject("bitshares", client);
    viewer->webView()->page()->mainFrame()->addToJavaScriptWindowObject("magic_unicorn", new Utilities, QWebFrame::ScriptOwnership);

    QObject::connect(viewer->webView()->page()->networkAccessManager(), &QNetworkAccessManager::authenticationRequired,
                     [client](QNetworkReply*, QAuthenticator *auth) {
       auth->setUser(client->http_url().userName());
       auth->setPassword(client->http_url().password());
    });
    client->connect(client, &ClientWrapper::initialized, [viewer,client,mainWindow]() {
       ilog( "Client initialized; loading web interface from ${url}", ("url", client->http_url().toString().toStdString()) );
       viewer->webView()->load(client->http_url());
       //Now we know the URL of the app, so we can create the items in the Accounts menu
       setupMenus(viewer, client, mainWindow);
    });
    viewer->connect(viewer->webView(), &QGraphicsWebView::loadFinished, [mainWindow,splash,viewer](bool ok) {
       ilog( "Webview loaded: ${status}", ("status", ok) );
       mainWindow->show();
       splash->finish(mainWindow);
    });
    client->connect(client, &ClientWrapper::error, [=](QString errorString) {
       splash->showMessage(errorString, Qt::AlignCenter | Qt::AlignBottom, Qt::white);
       fc::usleep( fc::seconds(3) );
       qApp->exit(1);
    });
}

int main( int argc, char** argv )
{
   QCoreApplication::setOrganizationName( "BitShares" );
   QCoreApplication::setOrganizationDomain( "bitshares.org" );
   QCoreApplication::setApplicationName( BTS_BLOCKCHAIN_NAME );
   QApplication app(argc, argv);
   app.setWindowIcon(QIcon(":/images/qtapp.ico"));

#ifdef __APPLE__
   //Install OSX event handler
   ilog("Installing URL open event filter");
   app.installEventFilter(new UrlReceiver(&app));
#endif

   QTimer fc_tasks;
   fc_tasks.connect( &fc_tasks, &QTimer::timeout, [](){ fc::usleep( fc::microseconds( 1000 ) ); } );
   fc_tasks.start(33);

   QPixmap pixmap(":/images/splash_screen.jpg");
   QSplashScreen splash(pixmap);
   splash.showMessage(QObject::tr("Loading configuration..."),
                      Qt::AlignCenter | Qt::AlignBottom, Qt::white);
   splash.show();

   QWebSettings::globalSettings()->setAttribute( QWebSettings::PluginsEnabled, false );

   MainWindow mainWindow;
   auto viewer = new Html5Viewer;
   ClientWrapper client;
   mainWindow.setCentralWidget(viewer);
   prepareStartupSequence(&client, viewer, &mainWindow, &splash);

   try {
    client.initialize();
    return app.exec();
   }
   catch ( const fc::exception& e)
   {
      elog( "${e}", ("e",e.to_detail_string() ) );
      QErrorMessage::qtHandler()->showMessage( e.to_string().c_str() );
   }
}
<commit_msg>Make splash screen error messages red.<commit_after>#include "html5viewer/html5viewer.h"
#include "ClientWrapper.hpp"
#include "Utilities.hpp"
#include "MainWindow.hpp"

#include <boost/thread.hpp>
#include <bts/blockchain/config.hpp>
#include <signal.h>

#include <QApplication>
#include <QSettings>
#include <QPixmap>
#include <QErrorMessage>
#include <QSplashScreen>
#include <QDir>
#include <QWebSettings>
#include <QWebPage>
#include <QWebFrame>
#include <QJsonDocument>
#include <QGraphicsWebView>
#include <QTimer>
#include <QAuthenticator>
#include <QNetworkReply>
#include <QResource>
#include <QGraphicsWidget>
#include <QMainWindow>
#include <QMenuBar>
#include <QLayout>

#include <boost/program_options.hpp>

#include <bts/client/client.hpp>
#include <bts/net/upnp.hpp>
#include <bts/blockchain/chain_database.hpp>
#include <bts/rpc/rpc_server.hpp>
#include <bts/cli/cli.hpp>
#include <bts/utilities/git_revision.hpp>
#include <fc/filesystem.hpp>
#include <fc/thread/thread.hpp>
#include <fc/log/file_appender.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/io/json.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/git_revision.hpp>
#include <fc/io/json.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/signals.hpp>

#include <boost/iostreams/tee.hpp>
#include <boost/iostreams/stream.hpp>

#include <fstream>
#include <iostream>
#include <iomanip>

#ifdef NDEBUG
#include "config_prod.hpp"
#else
#include "config_dev.hpp"
#endif

class UrlReceiver : public QObject {
public:
    UrlReceiver(QObject* parent = 0):QObject(parent){}
    virtual bool eventFilter(QObject *, QEvent* event) {
        if (event->type() == QEvent::FileOpen) {
            ilog("Got FOE");
            return true;
        }
        return false;
    }
};

void setupMenus(Html5Viewer* viewer, ClientWrapper* client, MainWindow* mainWindow)
{
    auto accountMenu = mainWindow->accountMenu();

    QObject::connect(accountMenu->addAction("&Go to My Accounts"), &QAction::triggered, [viewer,client](){
        viewer->loadUrl(client->http_url().toString() + "/#/accounts");
    });
    QObject::connect(accountMenu->addAction("&Create Account"), &QAction::triggered, [viewer,client](){
        viewer->loadUrl(client->http_url().toString() + "/#/create/account");
    });
    accountMenu->addAction("&Import Account")->setEnabled(false);

    //Enable accountMenu only when wallet is unlocked.
    accountMenu->setEnabled(false);
    client->get_client()->get_wallet()->wallet_lock_state_changed.connect([accountMenu](bool locked){
        accountMenu->setEnabled(!locked);
    });
}

void prepareStartupSequence(ClientWrapper* client, Html5Viewer* viewer, MainWindow* mainWindow, QSplashScreen* splash)
{
    viewer->webView()->page()->mainFrame()->addToJavaScriptWindowObject("bitshares", client);
    viewer->webView()->page()->mainFrame()->addToJavaScriptWindowObject("magic_unicorn", new Utilities, QWebFrame::ScriptOwnership);

    QObject::connect(viewer->webView()->page()->networkAccessManager(), &QNetworkAccessManager::authenticationRequired,
                     [client](QNetworkReply*, QAuthenticator *auth) {
       auth->setUser(client->http_url().userName());
       auth->setPassword(client->http_url().password());
    });
    client->connect(client, &ClientWrapper::initialized, [viewer,client,mainWindow]() {
       ilog( "Client initialized; loading web interface from ${url}", ("url", client->http_url().toString().toStdString()) );
       viewer->webView()->load(client->http_url());
       //Now we know the URL of the app, so we can create the items in the Accounts menu
       setupMenus(viewer, client, mainWindow);
    });
    viewer->connect(viewer->webView(), &QGraphicsWebView::loadFinished, [mainWindow,splash,viewer](bool ok) {
       ilog( "Webview loaded: ${status}", ("status", ok) );
       mainWindow->show();
       splash->finish(mainWindow);
    });
    client->connect(client, &ClientWrapper::error, [=](QString errorString) {
       splash->showMessage(errorString, Qt::AlignCenter | Qt::AlignBottom, Qt::red);
       fc::usleep( fc::seconds(3) );
       qApp->exit(1);
    });
}

int main( int argc, char** argv )
{
   QCoreApplication::setOrganizationName( "BitShares" );
   QCoreApplication::setOrganizationDomain( "bitshares.org" );
   QCoreApplication::setApplicationName( BTS_BLOCKCHAIN_NAME );
   QApplication app(argc, argv);
   app.setWindowIcon(QIcon(":/images/qtapp.ico"));

#ifdef __APPLE__
   //Install OSX event handler
   ilog("Installing URL open event filter");
   app.installEventFilter(new UrlReceiver(&app));
#endif

   QTimer fc_tasks;
   fc_tasks.connect( &fc_tasks, &QTimer::timeout, [](){ fc::usleep( fc::microseconds( 1000 ) ); } );
   fc_tasks.start(33);

   QPixmap pixmap(":/images/splash_screen.jpg");
   QSplashScreen splash(pixmap);
   splash.showMessage(QObject::tr("Loading configuration..."),
                      Qt::AlignCenter | Qt::AlignBottom, Qt::white);
   splash.show();

   QWebSettings::globalSettings()->setAttribute( QWebSettings::PluginsEnabled, false );

   MainWindow mainWindow;
   auto viewer = new Html5Viewer;
   ClientWrapper client;
   mainWindow.setCentralWidget(viewer);
   prepareStartupSequence(&client, viewer, &mainWindow, &splash);

   try {
    client.initialize();
    return app.exec();
   }
   catch ( const fc::exception& e)
   {
      elog( "${e}", ("e",e.to_detail_string() ) );
      QErrorMessage::qtHandler()->showMessage( e.to_string().c_str() );
   }
}
<|endoftext|>


<commit_before>#include <algorithm>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>

#include <curl/curl.h>

#include "config.h"
#include "dbo_project.h"
#include "main.h"
#include "store_file.h"
#include "util.h"

static const int INSTALL_DIALOG_LINE_LENGTH = 80;

std::string const CMD_STORE = "store";
std::string const CMD_INSTALL = "install";
std::string const CMD_REMOVE = "remove";
std::string const CMD_UPGRADE = "upgrade";
std::string const CMD_HELP = "help";
std::string const cmds[] = {CMD_STORE, CMD_INSTALL, CMD_REMOVE, CMD_UPGRADE, CMD_HELP};

static std::string const USG_STORE = "[location]";
static std::string const USG_INSTALL = "<projects>...";
static std::string const USG_UPGRADE = "";
static std::string const USG_REMOVE = "<projects>...";
static std::string const USG_HELP = "[command]";

static std::vector<RemoteProject*>* const EMPTY_RPP_VEC = new std::vector<RemoteProject*>(0);

int main(int argc, char* argv[]) {
    if (argc < 2) {
        err("Too few args!");
        print("    Usage: dbo_get <command>");
        return 1;
    }

    Config::getInstance().load();

    char* cmd = argv[1];
    if (matchCmd(cmd, CMD_STORE)) {
        return setStore(argc, argv);
    } else if (matchCmd(cmd, CMD_INSTALL)) {
        return install(argc, argv);
    } else if (matchCmd(cmd, CMD_REMOVE)) {
        return remove(argc, argv);
    } else if (matchCmd(cmd, CMD_UPGRADE)) {
        err("Command not yet implemented");
        return 1;
    } else if (matchCmd(cmd, CMD_HELP)) {
        err("Command not yet implemented.");
        return 1;
    } else {
        err("Invalid command, try `dbo-get help`.");
        return 1;
    }
}

int setStore(int argc, char* argv[]) {
    if (argc < 3) {
        std::string* loc = Config::getInstance().get(Config::KEY_STORE);
        print("Current store location: " + (loc == NULL ? "NOT SET" : *loc));
        return 0;
    }

    std::string path = "";
    for (int i = 2; i < argc; i++) {
        path += argv[i];
        if (i < argc - 1) {
            path += " ";
        }
    }
    std::replace(path.begin(), path.end(), '\\', '/');
    Config::getInstance().set(Config::KEY_STORE, path);
    makePath(path);
    print("Successfully set store location as \"" + path + "\".");

    return 0;
}

std::vector<RemoteProject*>* resolve(int argc, char* argv[]) {
    print("Resolving projects...");

    std::vector<RemoteProject*>* vec = new std::vector<RemoteProject*>(argc - 2);
    bool fail = false;
    bool empty = true;
    curl_global_init(CURL_GLOBAL_ALL);
    for (int i = 0; i < argc - 2; i++) {
        std::string id = argv[2 + i];
        print("Resolving project " + id + "...");
        RemoteProject* remote = new RemoteProject(id);

        if (!remote->resolve()) {
            err("Failed to resolve " + id + ".");
            fail = true;
            return NULL;
        }

        LocalProject* local = StoreFile::getInstance().getProject(id);

        if (local == NULL || remote->getVersion() > local->getVersion()) {
            (*vec)[i] = remote;
            empty = false;
        }

        print("Done resolving " + id + ".");
    }
    curl_global_cleanup();
    return fail ? NULL : (!empty ? vec : EMPTY_RPP_VEC);
}

void printDialog(std::vector<RemoteProject*>* projects) {
    std::vector<std::string> upgradeList = std::vector<std::string>(projects->size());
    std::vector<std::string> installList = std::vector<std::string>(projects->size());
    int ui = 0;
    int ii = 0;
    int nu = 0;
    for (size_t i = 0; i < projects->size(); i++) {
        RemoteProject* remote = (*projects)[i];
        if (remote == NULL) {
            nu++;
            continue;
        }
        LocalProject* local = StoreFile::getInstance().getProject(remote->getId());
        if (local != NULL) {
            upgradeList[ui++] = remote->getId();
        } else {
            installList[ii++] = remote->getId();
        }
    }

    if (ui > 0) {
        print("The following projects will be upgraded:");
        std::string line = "  ";
        for (size_t i = 0; i < upgradeList.size(); i++) {
            if (upgradeList[i] == "") {
                break;
            }
            std::string newLine = line + upgradeList[i];
            if (line.length() + 1 > INSTALL_DIALOG_LINE_LENGTH) {
                print(line);
                line = "  " + upgradeList[i];
            } else {
                line = newLine + " ";
            }
        }
        print(line);
    }

    if (ii > 0) {
        print("The following projects will be newly installed:");
        std::string line = "  ";
        for (size_t i = 0; i < installList.size(); i++) {
            if (installList[i] == "") {
                break;
            }
            std::string newLine = line + installList[i];
            if (line.length() + 1 > INSTALL_DIALOG_LINE_LENGTH) {
                print(line);
                line = "  " + installList[i] + " ";
            } else {
                line = newLine + " ";
            }
        }
        print(line);
    }

    print(std::to_string(ui) + " upgraded, " + std::to_string(ii) + " newly installed, 0 to remove, "
        + std::to_string(nu) + " not upgraded.");
}

int install(int argc, char* argv[]) {
    if (argc < 3) {
        tooFewArgs(CMD_INSTALL, USG_INSTALL);
        return 1;
    }

    std::string* loc = Config::getInstance().get(Config::KEY_STORE);
    if (loc == NULL) {
        err("Store location is not set; please run store command first.");
        return 1;
    }
    makePath(*loc);

    std::vector<RemoteProject*>* projects = resolve(argc, argv);

    if (projects == NULL) {
        err("No projects specified for installation.");
        return 1;
    }

    if (projects->empty()) {
        print("Already up-to-date.");
        return 0;
    }

    printDialog(projects);

    for (size_t i = 0; i < projects->size(); i++) {
        RemoteProject* proj = (*projects)[i];
        if (proj == NULL) {
            continue;
        }

        LocalProject* local = StoreFile::getInstance().getProject(proj->getId());
        if (local != NULL) {
            print("Upgrading project " + proj->getId() + " (#" + std::to_string(local->getVersion()) + " -> #" + std::to_string(proj->getVersion()) + ").");
        } else {
            print("Installing project " + proj->getId() + "...");
        }
        if (!proj->install()) {
            return 1;
        }
        print("Done installing " + proj->getId() + ".");
    }

    StoreFile::getInstance().save();

    return 0;
}

int remove(int argc, char* argv[]) {
    if (argc < 3) {
        tooFewArgs(CMD_REMOVE, USG_REMOVE);
        return 1;
    }

    std::string* loc = Config::getInstance().get(Config::KEY_STORE);
    if (loc == NULL) {
        err("Store location is not set; please run store command first.");
        return 1;
    }
    makePath(*loc);

    bool fail = false;;
    std::vector<LocalProject> projects = std::vector<LocalProject>(argc - 2);
    for (int i = 0; i < argc - 2; i++) {
        std::string id = argv[i + 2];
        print("Resolving project " + id + "...");
        LocalProject* proj = StoreFile::getInstance().getProject(id);
        if (proj != NULL) {
            if (!fail) {
                projects[i] = *proj;
            }
        } else {
            err("No project with ID " + id + " is currently installed.");
            fail = true;
        }
    }
    if (fail) {
        err("No projects specified for removal.");
        return 1;
    }

    for (size_t i = 0; i < projects.size(); i++) {
        LocalProject proj = projects[i];
        print("Removing project " + proj.getId() + "...");
        proj.remove();
        print("Done removing " + proj.getId() + ".");
    }

    StoreFile::getInstance().save();

    return 0;
}
<commit_msg>Implement super cow powers<commit_after>#include <algorithm>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>

#include <curl/curl.h>

#include "config.h"
#include "dbo_project.h"
#include "main.h"
#include "store_file.h"
#include "util.h"

static const int INSTALL_DIALOG_LINE_LENGTH = 80;

std::string const CMD_STORE = "store";
std::string const CMD_INSTALL = "install";
std::string const CMD_REMOVE = "remove";
std::string const CMD_UPGRADE = "upgrade";
std::string const CMD_HELP = "help";
std::string const CMD_MOO = "moo";
std::string const cmds[] = {CMD_STORE, CMD_INSTALL, CMD_REMOVE, CMD_UPGRADE, CMD_HELP, CMD_MOO};

static std::string const USG_STORE = "[location]";
static std::string const USG_INSTALL = "<projects>...";
static std::string const USG_UPGRADE = "";
static std::string const USG_REMOVE = "<projects>...";
static std::string const USG_HELP = "[command]";

static std::vector<RemoteProject*>* const EMPTY_RPP_VEC = new std::vector<RemoteProject*>(0);

int main(int argc, char* argv[]) {
    if (argc < 2) {
        err("Too few args!");
        print("    Usage: dbo_get <command>");
        return 1;
    }

    Config::getInstance().load();

    char* cmd = argv[1];
    if (matchCmd(cmd, CMD_STORE)) {
        return setStore(argc, argv);
    } else if (matchCmd(cmd, CMD_INSTALL)) {
        return install(argc, argv);
    } else if (matchCmd(cmd, CMD_REMOVE)) {
        return remove(argc, argv);
    } else if (matchCmd(cmd, CMD_UPGRADE)) {
        err("Command not yet implemented");
        return 1;
    } else if (matchCmd(cmd, CMD_HELP)) {
        err("Command not yet implemented.");
        return 1;
    } else if (matchCmd(cmd, CMD_MOO)) {
        print("Yes, you're very clever.");
    } else {
        err("Invalid command, try `dbo-get help`.");
        return 1;
    }
}

int setStore(int argc, char* argv[]) {
    if (argc < 3) {
        std::string* loc = Config::getInstance().get(Config::KEY_STORE);
        print("Current store location: " + (loc == NULL ? "NOT SET" : *loc));
        return 0;
    }

    std::string path = "";
    for (int i = 2; i < argc; i++) {
        path += argv[i];
        if (i < argc - 1) {
            path += " ";
        }
    }
    std::replace(path.begin(), path.end(), '\\', '/');
    Config::getInstance().set(Config::KEY_STORE, path);
    makePath(path);
    print("Successfully set store location as \"" + path + "\".");

    return 0;
}

std::vector<RemoteProject*>* resolve(int argc, char* argv[]) {
    print("Resolving projects...");

    std::vector<RemoteProject*>* vec = new std::vector<RemoteProject*>(argc - 2);
    bool fail = false;
    bool empty = true;
    curl_global_init(CURL_GLOBAL_ALL);
    for (int i = 0; i < argc - 2; i++) {
        std::string id = argv[2 + i];
        print("Resolving project " + id + "...");
        RemoteProject* remote = new RemoteProject(id);

        if (!remote->resolve()) {
            err("Failed to resolve " + id + ".");
            fail = true;
            return NULL;
        }

        LocalProject* local = StoreFile::getInstance().getProject(id);

        if (local == NULL || remote->getVersion() > local->getVersion()) {
            (*vec)[i] = remote;
            empty = false;
        }

        print("Done resolving " + id + ".");
    }
    curl_global_cleanup();
    return fail ? NULL : (!empty ? vec : EMPTY_RPP_VEC);
}

void printDialog(std::vector<RemoteProject*>* projects) {
    std::vector<std::string> upgradeList = std::vector<std::string>(projects->size());
    std::vector<std::string> installList = std::vector<std::string>(projects->size());
    int ui = 0;
    int ii = 0;
    int nu = 0;
    for (size_t i = 0; i < projects->size(); i++) {
        RemoteProject* remote = (*projects)[i];
        if (remote == NULL) {
            nu++;
            continue;
        }
        LocalProject* local = StoreFile::getInstance().getProject(remote->getId());
        if (local != NULL) {
            upgradeList[ui++] = remote->getId();
        } else {
            installList[ii++] = remote->getId();
        }
    }

    if (ui > 0) {
        print("The following projects will be upgraded:");
        std::string line = "  ";
        for (size_t i = 0; i < upgradeList.size(); i++) {
            if (upgradeList[i] == "") {
                break;
            }
            std::string newLine = line + upgradeList[i];
            if (line.length() + 1 > INSTALL_DIALOG_LINE_LENGTH) {
                print(line);
                line = "  " + upgradeList[i];
            } else {
                line = newLine + " ";
            }
        }
        print(line);
    }

    if (ii > 0) {
        print("The following projects will be newly installed:");
        std::string line = "  ";
        for (size_t i = 0; i < installList.size(); i++) {
            if (installList[i] == "") {
                break;
            }
            std::string newLine = line + installList[i];
            if (line.length() + 1 > INSTALL_DIALOG_LINE_LENGTH) {
                print(line);
                line = "  " + installList[i] + " ";
            } else {
                line = newLine + " ";
            }
        }
        print(line);
    }

    print(std::to_string(ui) + " upgraded, " + std::to_string(ii) + " newly installed, 0 to remove, "
        + std::to_string(nu) + " not upgraded.");
}

int install(int argc, char* argv[]) {
    if (argc < 3) {
        tooFewArgs(CMD_INSTALL, USG_INSTALL);
        return 1;
    }

    std::string* loc = Config::getInstance().get(Config::KEY_STORE);
    if (loc == NULL) {
        err("Store location is not set; please run store command first.");
        return 1;
    }
    makePath(*loc);

    std::vector<RemoteProject*>* projects = resolve(argc, argv);

    if (projects == NULL) {
        err("No projects specified for installation.");
        return 1;
    }

    if (projects->empty()) {
        print("Already up-to-date.");
        return 0;
    }

    printDialog(projects);

    for (size_t i = 0; i < projects->size(); i++) {
        RemoteProject* proj = (*projects)[i];
        if (proj == NULL) {
            continue;
        }

        LocalProject* local = StoreFile::getInstance().getProject(proj->getId());
        if (local != NULL) {
            print("Upgrading project " + proj->getId() + " (#" + std::to_string(local->getVersion()) + " -> #" + std::to_string(proj->getVersion()) + ").");
        } else {
            print("Installing project " + proj->getId() + "...");
        }
        if (!proj->install()) {
            return 1;
        }
        print("Done installing " + proj->getId() + ".");
    }

    StoreFile::getInstance().save();

    return 0;
}

int remove(int argc, char* argv[]) {
    if (argc < 3) {
        tooFewArgs(CMD_REMOVE, USG_REMOVE);
        return 1;
    }

    std::string* loc = Config::getInstance().get(Config::KEY_STORE);
    if (loc == NULL) {
        err("Store location is not set; please run store command first.");
        return 1;
    }
    makePath(*loc);

    bool fail = false;;
    std::vector<LocalProject> projects = std::vector<LocalProject>(argc - 2);
    for (int i = 0; i < argc - 2; i++) {
        std::string id = argv[i + 2];
        print("Resolving project " + id + "...");
        LocalProject* proj = StoreFile::getInstance().getProject(id);
        if (proj != NULL) {
            if (!fail) {
                projects[i] = *proj;
            }
        } else {
            err("No project with ID " + id + " is currently installed.");
            fail = true;
        }
    }
    if (fail) {
        err("No projects specified for removal.");
        return 1;
    }

    for (size_t i = 0; i < projects.size(); i++) {
        LocalProject proj = projects[i];
        print("Removing project " + proj.getId() + "...");
        proj.remove();
        print("Done removing " + proj.getId() + ".");
    }

    StoreFile::getInstance().save();

    return 0;
}
<|endoftext|>


<commit_before>7e74f594-2749-11e6-927e-e0f84713e7b8<commit_msg>this is my first commit?<commit_after>7e801cb3-2749-11e6-b5ef-e0f84713e7b8<|endoftext|>


<commit_before>9c579399-2747-11e6-96e2-e0f84713e7b8<commit_msg>Added that feature we discussed on... Was it monday?<commit_after>9c69f2e1-2747-11e6-8585-e0f84713e7b8<|endoftext|>


<commit_before>#include <sstream>
#include <dequeue>
#include <SFML/Graphics.hpp>

#define PPB 32

sf::Font font;

sf::RenderTexture tile_texture[26];

class Tile
{
	char character;
	sf::Sprite sprite;
public:
	Tile(char ch) :
		sprite(tile_texture[ch - 'A'].getTexture())
	{
		character = ch;
	}

	void set_pos(int x, int y)
	{
		sprite.setPosition(x * PPB, y * PPB);
	}

	void draw_on(sf::RenderWindow & window) const
	{
		window.draw(sprite);
	}
};

class InfiniteGrid
{
	int min[2];
	int max[2];
	std::dequeue<std::dequeue<Tile*>> grid;
public:
	InfiniteGrid() : min {0, 0}, max {-1, -1}, grid()
	{
	}

	Tile* get(int x, int y)
	{
		if (grid.size() == 0)
			return nullptr;
		if (min[0] <= x && x <= max[0] && min[1] <= y && y <= max[1])
			return grid[x][y];
		else
			return nullptr;
	}

	void set(int x, int y, Tile* tile)
	{
		if (grid.size() == 0)
		{
			grid.push_back(std::dequeue());
			grid[0].push_back(tile);
			min[0] = 0;
			min[1] = 0;
			max[0] = 0;
			max[1] = 0;
		}
		else
		{
			if (x < min[0])
			{
				for (int i = x; i < min[0]; i++)
					grid.push_front(std::dequeue(height));
				min[0] = x;
			}
			else if (x > max[0])
			{
				for (int i = x; i < max[0]; i++)
					grid.push_back(std::dequeue(height));
				max[0] = x;
			}
			if (y < min[1])
			{
				for (auto col : grid)
					for (int i = y; i < min[1]; i++)
						col->push_front(nullptr);
				min[1] = y;
			}
			else if (y > max[1])
			{
				for (auto col : grid)
					for (int i = y; i < min[1]; i++)
						col->push_back(nullptr);
				min[1] = y;
			}
		}
	}
};

int main()
{
	font.loadFromFile("/usr/share/fonts/TTF/VeraMono.ttf");

	// create tile textures
	for (char ch = 'A'; ch <= 'Z'; ch++)
	{
		sf::RectangleShape tile(sf::Vector2f(PPB, PPB));
		tile.setFillColor(sf::Color(255, 255, 175));
		tile_texture[ch - 'A'].draw(tile);

		std::stringstream string;
		string << ch;
		sf::Text letter(string.str(), font, 24);
		tile_texture[ch - 'A'].draw(letter);
		tile_texture[ch - 'A'].display();
	}

	sf::Color background(22, 22, 22);

	sf::RenderWindow window(sf::VideoMode(1024, 600), "Bananagrams", sf::Style::Titlebar);

	int pos[2] = {0, 0};
	int delta[2] = {0, 0};
	float held[2] = {0, 0};

	float repeat_delay = 0.5;
	float repeat_speed = 0.1;

	sf::RectangleShape cursor(sf::Vector2f(PPB, PPB));
	cursor.setFillColor(sf::Color(0, 0, 0, 0));
	cursor.setOutlineThickness(5);
	cursor.setOutlineColor(sf::Color(0, 200, 0));

	sf::Clock clock;
	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed || (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape))
				window.close();
			else if (event.type == sf::Event::KeyPressed)
			{
				switch (event.key.code)
				{
					case sf::Keyboard::Left:
						delta[0] = -1;
						break;
					case sf::Keyboard::Right:
						delta[0] = 1;
						break;
					case sf::Keyboard::Up:
						delta[1] = -1;
						break;
					case sf::Keyboard::Down:
						delta[1] = 1;
						break;
					default:
						break;
				}
			}
			else if (event.type == sf::Event::KeyReleased)
			{
				switch (event.key.code)
				{
					case sf::Keyboard::Left:
					case sf::Keyboard::Right:
						delta[0] = 0;
						break;
					case sf::Keyboard::Up:
					case sf::Keyboard::Down:
						delta[1] = 0;
						break;
					default:
						break;
				}
			}
		}

		float time = clock.getElapsedTime().asSeconds();
		clock.restart();

		for (unsigned int i = 0; i < 2; i++)
		{
			if (delta[i] == 0)
				held[i] = 0;
			else
			{
				if (held[i] == 0)
					pos[i] += delta[i];
				else
					while (held[i] > repeat_delay)
					{
						pos[i] += delta[i];
						held[i] -= repeat_speed;
					}
				held[i] += time;
			}
		}

		cursor.setPosition(pos[0] * PPB, pos[1] * PPB);

		window.clear(background);
		window.draw(cursor);

		window.display();
	}

	return 0;
}
<commit_msg>Remake InfiniteGrid class. Keypress adds tiles<commit_after>#include <iostream>
#include <sstream>
#include <vector>
#include <SFML/Graphics.hpp>

using std::cerr;
using std::endl;

#define PPB 32

sf::Font font;

sf::RenderTexture tile_texture[26];

class Tile
{
	char character;
	sf::Sprite sprite;
public:
	Tile(char ch) :
		sprite(tile_texture[ch - 'A'].getTexture())
	{
		character = ch;
	}

	void set_pos(int x, int y)
	{
		sprite.setPosition(x * PPB, y * PPB);
	}

	void draw_on(sf::RenderWindow & window) const
	{
		window.draw(sprite);
	}
};

class InfiniteGrid
{
	std::vector<Tile*> grid;

	inline unsigned int bijection(unsigned x, unsigned int y) const
	{
		return ((x + y) * (x + y + 1)) / 2 + x;
	}

	unsigned int convert(int x, int y) const
	{
		if (x >= 0 && y >= 0)
			return 4 * bijection(x, y);
		if (x < 0 && y >= 0)
			return 4 * bijection(-x - 1, y) + 1;
		if (x >= 0 && y < 0)
			return 4 * bijection(x, -y - 1) + 2;
		else
			return 4 * bijection(-x - 1, -y - 1) + 3;
	}
public:
	InfiniteGrid() : grid()
	{
	}

	Tile* get(int x, int y) const
	{
		unsigned int n = convert(x, y);
		if (n >= grid.size())
			return nullptr;
		return grid[n];
	}

	Tile* remove(int x, int y)
	{
		unsigned int n = convert(x, y);
		if (n < grid.size())
		{
			Tile* tile = grid[n];
			if (tile == nullptr)
				return nullptr;

			grid[n] = nullptr;
			for (n = grid.size(); n --> 0;)
				if (grid[n] != nullptr)
					break;
			// TODO won't ever shrink to 0
			grid.resize(n + 1, nullptr);
			return tile;
		}
		return nullptr;
	}

	Tile* swap(int x, int y, Tile* tile)
	{
		// TODO raise error if tile is null
		unsigned int n = convert(x, y);
		if (n >= grid.size())
			// TODO catch failure
			grid.resize(n + 1, nullptr);
		Tile* swp = grid[n];
		tile->set_pos(x, y);
		grid[n] = tile;
		return swp;
	}

	void draw_on(sf::RenderWindow& window) const
	{
		for (auto tile : grid)
			if (tile != nullptr)
				tile->draw_on(window);
	}
};

int main()
{
	font.loadFromFile("/usr/share/fonts/TTF/VeraMono.ttf");
	InfiniteGrid grid;

	cerr << "Generating textures...\n";
	// create tiles
	std::vector<Tile*> tiles;
	for (char ch = 'A'; ch <= 'Z'; ch++)
	{
		// TODO error check
		tile_texture[ch - 'A'].create(PPB, PPB);
		tile_texture[ch - 'A'].clear(sf::Color(255, 255, 175));

		std::stringstream string;
		string << ch;
		sf::Text letter(string.str(), font, 24);
		letter.setColor(sf::Color::Black);
		tile_texture[ch - 'A'].draw(letter);
		tile_texture[ch - 'A'].display();

		tiles.push_back(new Tile(ch));
	}

	sf::Color background(22, 22, 22);

	sf::RenderWindow window(sf::VideoMode(1024, 600), "Bananagrams", sf::Style::Titlebar);

	int pos[2] = {0, 0};
	int delta[2] = {0, 0};
	float held[2] = {0, 0};

	float repeat_delay = 0.5;
	float repeat_speed = 0.1;

	sf::RectangleShape cursor(sf::Vector2f(PPB, PPB));
	cursor.setFillColor(sf::Color(0, 0, 0, 0));
	cursor.setOutlineThickness(3);
	cursor.setOutlineColor(sf::Color(0, 200, 0));

	sf::Clock clock;
	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed || (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape))
				window.close();
			else if (event.type == sf::Event::KeyPressed)
			{
				switch (event.key.code)
				{
					case sf::Keyboard::Left:
						delta[0] = -1;
						break;
					case sf::Keyboard::Right:
						delta[0] = 1;
						break;
					case sf::Keyboard::Up:
						delta[1] = -1;
						break;
					case sf::Keyboard::Down:
						delta[1] = 1;
						break;
					default:
						break;
				}
				if (sf::Keyboard::A <= event.key.code && event.key.code <= sf::Keyboard::Z)
				{
					grid.swap(pos[0], pos[1], tiles[event.key.code - sf::Keyboard::A]);
				}
			}
			else if (event.type == sf::Event::KeyReleased)
			{
				switch (event.key.code)
				{
					case sf::Keyboard::Left:
					case sf::Keyboard::Right:
						delta[0] = 0;
						break;
					case sf::Keyboard::Up:
					case sf::Keyboard::Down:
						delta[1] = 0;
						break;
					default:
						break;
				}
			}
		}

		float time = clock.getElapsedTime().asSeconds();
		clock.restart();

		for (unsigned int i = 0; i < 2; i++)
		{
			if (delta[i] == 0)
				held[i] = 0;
			else
			{
				if (held[i] == 0)
					pos[i] += delta[i];
				else
					while (held[i] > repeat_delay)
					{
						pos[i] += delta[i];
						held[i] -= repeat_speed;
					}
				held[i] += time;
			}
		}

		cursor.setPosition(pos[0] * PPB, pos[1] * PPB);

		window.clear(background);
		grid.draw_on(window);
		window.draw(cursor);

		window.display();
	}

	return 0;
}
<|endoftext|>


<commit_before>d600676e-2747-11e6-baf0-e0f84713e7b8<commit_msg>Backup, rebase this later<commit_after>d611ff8a-2747-11e6-893c-e0f84713e7b8<|endoftext|>


<commit_before>#include <cstdlib>
#include <iostream>
#include <string>
#include <opencv/cv.hpp>
#include "Ellipse.h"

static constexpr size_t MAX_RADIUS = 600;
static constexpr size_t MAX_SIZE = 1920;

static std::tuple<EllipseGeometry, Eigen::MatrixX2f> generate_problem(size_t n, float sigma);
static std::tuple<EllipseGeometry, Eigen::MatrixX2f> generate_cv_fail();
static void plot(const Eigen::MatrixX2f& points, const EllipseGeometry& eg1, const EllipseGeometry& eg2);

int main(int argc, char** argv)
{
  using namespace std;

  if (argc < 3) {
    cerr << "USAGE: " << argv[0] << " NPOINTS SIGMA" << endl;
    return 1;
  }

  std::tuple<EllipseGeometry, Eigen::MatrixX2f> problem;

  if (std::string("FAIL") == argv[1]) {
    problem = generate_cv_fail();
  }
  else {
    size_t npoints = std::atoi(argv[1]);
    float sigma = std::atof(argv[2]);
    problem = generate_problem(npoints, sigma);
  }

  cout << "PROBLEM:"
      << "\nELLIPSE:\n" << get<0>(problem)
      << "\nPOINTS:\n" << get<1>(problem)
      << endl;

  auto ell = fit_ellipse(get<1>(problem));
  auto conic = to_conic(ell);
  cout << "COEFFICIENTS:\n" << get<0>(conic)
      << "\nELLIPSE: " << ell
      << "\nERROR: " << fit_error(get<1>(problem), conic)
      << endl;

  auto cv_ell = cv_fit_ellipse(get<1>(problem));
  auto cv_conic = to_conic(cv_ell);
  cout << "CV COEFFICIENTS:\n" << get<0>(cv_conic)
      << "\nCV ELLIPSE: " << cv_ell
      << "\nCV ERROR: " << fit_error(get<1>(problem), cv_conic)
      << endl;

  plot(get<1>(problem), ell, cv_ell);

  return 0;
}

// We hard-code many of the parameters.
static std::tuple<EllipseGeometry, Eigen::MatrixX2f> generate_problem(size_t n, float sigma)
{
  using Eigen::Vector2f;
  auto g = get_ellipse_generator(Vector2f(MAX_SIZE/4, MAX_SIZE-MAX_SIZE/4), Vector2f(50, MAX_RADIUS), 0.1, 2*M_PI/32, sigma);
  Eigen::MatrixX2f ret(n, 2);
  for (size_t i = 0; i < n; ++i)
    ret.row(i) = g();
  return std::make_tuple(g.geometry(), ret);
}

static void plot(const Eigen::MatrixX2f& points, const EllipseGeometry& eg1, const EllipseGeometry& eg2)
{
  using namespace cv;

  namedWindow("FITTING", WINDOW_AUTOSIZE);
  Mat image(MAX_SIZE, MAX_SIZE, CV_8UC1);

  for (size_t i = 0; i < points.rows(); ++i)
    circle(image, Point(points(i,0), points(i,1)), 4, 255);

  ellipse(image, Point(eg1.center(0), eg1.center(1)), Size(eg1.radius(0), eg1.radius(1)), eg1.angle*180/M_PI, 0, 360, 255, 2);
  ellipse(image, Point(eg2.center(0), eg2.center(1)), Size(eg2.radius(0), eg2.radius(1)), eg2.angle*180/M_PI, 0, 360, 255, 1);

  imshow("FITTING", image);
  waitKey(0);
}

static std::tuple<EllipseGeometry, Eigen::MatrixX2f> generate_cv_fail()
{
  using Eigen::Vector2f;
  EllipseGeometry geom{Vector2f(1094.5, 1225.16), Vector2f(567.041, 365.318), 0.245385};
  Eigen::MatrixX2f data(10, 2);
  data <<
      924.784, 764.160,
      928.388, 615.903,
      847.4  , 888.014,
      929.406, 741.675,
      904.564, 825.605,
      926.742, 760.746,
      863.479, 873.406,
      910.987, 808.863,
      929.145, 744.976,
      917.474, 791.823;
  return std::make_tuple(geom, data);
}
<commit_msg>Color-coded drawing.<commit_after>#include <cstdlib>
#include <iostream>
#include <string>
#include <opencv/cv.hpp>
#include "Ellipse.h"

static constexpr size_t MAX_RADIUS = 600;
static constexpr size_t MAX_SIZE = 1920;

static std::tuple<EllipseGeometry, Eigen::MatrixX2f> generate_problem(size_t n, float sigma);
static std::tuple<EllipseGeometry, Eigen::MatrixX2f> generate_cv_fail();
static void plot(const Eigen::MatrixX2f& points, const EllipseGeometry& eg1, const EllipseGeometry& eg2);

int main(int argc, char** argv)
{
  using namespace std;

  if (argc < 3) {
    cerr << "USAGE: " << argv[0] << " NPOINTS SIGMA" << endl;
    return 1;
  }

  std::tuple<EllipseGeometry, Eigen::MatrixX2f> problem;

  if (std::string("FAIL") == argv[1]) {
    problem = generate_cv_fail();
  }
  else {
    size_t npoints = std::atoi(argv[1]);
    float sigma = std::atof(argv[2]);
    problem = generate_problem(npoints, sigma);
  }

  cout << "PROBLEM:"
      << "\nELLIPSE:\n" << get<0>(problem)
      << "\nPOINTS:\n" << get<1>(problem)
      << endl;

  auto ell = fit_ellipse(get<1>(problem));
  auto conic = to_conic(ell);
  cout << "COEFFICIENTS:\n" << get<0>(conic)
      << "\nELLIPSE: " << ell
      << "\nERROR: " << fit_error(get<1>(problem), conic)
      << endl;

  auto cv_ell = cv_fit_ellipse(get<1>(problem));
  auto cv_conic = to_conic(cv_ell);
  cout << "CV COEFFICIENTS:\n" << get<0>(cv_conic)
      << "\nCV ELLIPSE: " << cv_ell
      << "\nCV ERROR: " << fit_error(get<1>(problem), cv_conic)
      << endl;

  plot(get<1>(problem), ell, cv_ell);

  return 0;
}

// We hard-code many of the parameters.
static std::tuple<EllipseGeometry, Eigen::MatrixX2f> generate_problem(size_t n, float sigma)
{
  using Eigen::Vector2f;
  auto g = get_ellipse_generator(Vector2f(MAX_SIZE/4, MAX_SIZE-MAX_SIZE/4), Vector2f(50, MAX_RADIUS), 0.1, 2*M_PI/32, sigma);
  Eigen::MatrixX2f ret(n, 2);
  for (size_t i = 0; i < n; ++i)
    ret.row(i) = g();
  return std::make_tuple(g.geometry(), ret);
}

static void plot(const Eigen::MatrixX2f& points, const EllipseGeometry& eg1, const EllipseGeometry& eg2)
{
  using namespace cv;

  namedWindow("FITTING", WINDOW_AUTOSIZE);
  Mat image(MAX_SIZE, MAX_SIZE, CV_8UC4);

  for (size_t i = 0; i < points.rows(); ++i)
    circle(image, Point(points(i,0), points(i,1)), 6, Scalar(255, 255, 255));

  ellipse(image, Point(eg1.center(0), eg1.center(1)), Size(eg1.radius(0), eg1.radius(1)), eg1.angle*180/M_PI, 0, 360, Scalar(255, 0, 255), 2);
  ellipse(image, Point(eg2.center(0), eg2.center(1)), Size(eg2.radius(0), eg2.radius(1)), eg2.angle*180/M_PI, 0, 360, Scalar(0, 0, 255), 1);

  imshow("FITTING", image);
  waitKey(0);
}

static std::tuple<EllipseGeometry, Eigen::MatrixX2f> generate_cv_fail()
{
  using Eigen::Vector2f;
  EllipseGeometry geom{Vector2f(1094.5, 1225.16), Vector2f(567.041, 365.318), 0.245385};
  Eigen::MatrixX2f data(10, 2);
  data <<
      924.784, 764.160,
      928.388, 615.903,
      847.4  , 888.014,
      929.406, 741.675,
      904.564, 825.605,
      926.742, 760.746,
      863.479, 873.406,
      910.987, 808.863,
      929.145, 744.976,
      917.474, 791.823;
  return std::make_tuple(geom, data);
}
<|endoftext|>


<commit_before>6003fdbd-2749-11e6-ad27-e0f84713e7b8<commit_msg>lets try again<commit_after>601335d7-2749-11e6-ae67-e0f84713e7b8<|endoftext|>


<commit_before>bccd2823-2747-11e6-ac81-e0f84713e7b8<commit_msg>OKAY this time it should work<commit_after>bce9fbd4-2747-11e6-adf1-e0f84713e7b8<|endoftext|>