text stringlengths 54 60.6k |
|---|
<commit_before>cffd434a-2e4e-11e5-8e2e-28cfe91dbc4b<commit_msg>d00909dc-2e4e-11e5-b6f3-28cfe91dbc4b<commit_after>d00909dc-2e4e-11e5-b6f3-28cfe91dbc4b<|endoftext|> |
<commit_before>fbea5ccc-ad5c-11e7-8c90-ac87a332f658<commit_msg>Typical bobby<commit_after>fc5da8d9-ad5c-11e7-a322-ac87a332f658<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include <functional>
#include <limits>
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) {}
bool act(vector<string> commands) { return false; }
};
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", std::numeric_limits<int>::max()) {}
bool act(vector<string> commands) {}
};
struct MyopicRhino : public Entity
{
MyopicRhino(): Entity("Nearsighted One", std::numeric_limits<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;
entities.emplace_back(make_unique<Shogun>());
}
};
struct FoggyForest : public Room
{
FoggyForest() : Room(Map::Location::FOGGY_FOREST, "Dark creepy forest")
{
exits["east"] = Map::Location::GATES_OF_SHOGUN;
}
};
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>more work towards cleaning up act()<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include <functional>
#include <limits>
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) {}
bool act(vector<string> commands) { return false; }
};
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", std::numeric_limits<int>::max()) {}
bool act(vector<string> commands) {}
};
struct MyopicRhino : public Entity
{
MyopicRhino(): Entity("Nearsighted One", std::numeric_limits<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;
entities.emplace_back(make_unique<Shogun>());
}
};
struct FoggyForest : public Room
{
FoggyForest() : Room(Map::Location::FOGGY_FOREST, "Dark creepy forest")
{
exits["east"] = Map::Location::GATES_OF_SHOGUN;
}
};
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;
}
else if (commands.size() >= 1)
{}
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(Player*, 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 "part_data.hpp"
#include "cosmology.hpp"
#include "power.hpp"
#include "displacement.hpp"
#include "read_param.hpp"
#include "thermalvel.hpp"
#include "save.hpp"
#include <cassert>
int main(int argc, char **argv)
{
if(argc < 2)
{
fprintf(stdout, "\nParameters are missing.\n");
fprintf(stdout, "Call with <ParameterFile>\n\n");
exit(0);
}
/*Make sure stdout is line buffered even when not
* printing to a terminal but, eg, perl*/
setlinebuf(stdout);
//May throw std::runtime_error
try {
//Read the config file
SpbConfigParser config(argv[1]);
//Cosmological parameters
const auto Omega = config.PopValue<double>("Omega");
const auto OmegaLambda = config.PopValue<double>("OmegaLambda");
const auto OmegaBaryon = config.PopValue<double>("OmegaBaryon");
const auto OmegaDM_2ndSpecies = config.PopValue<double>("OmegaDM_2ndSpecies");
const auto HubbleParam = config.PopValue<double>("HubbleParam");
//Which output format should we use. 3 is HDF5, 2 is Gadget 2. Default to 3.
const auto ICFormat = config.PopValue<int>("ICFormat", 3);
//How many output files to use in the set
const auto NumFiles = config.PopValue<int>("NumFiles");
//Parameters of the simulation box
const auto Box = config.PopValue<double>("Box");
const auto Redshift = config.PopValue<double>("Redshift");
const double InitTime = 1 / (1 + Redshift);
//Size of FFT
const size_t Nmesh = config.PopValue<int>("Nmesh");
//Unused unless CAMB spectrum
const auto FileWithInputSpectrum = config.PopValue<std::string>("FileWithInputSpectrum");
const auto FileWithTransfer = config.PopValue<std::string>("FileWithTransfer");
const auto InputSpectrum_UnitLength_in_cm = config.PopValue<double>("InputSpectrum_UnitLength_in_cm", 3.085678e24);
//Output filenames
const auto OutputDir = config.PopValue<std::string>("OutputDir");
const auto FileBase = config.PopValue<std::string>("FileBase");
//Random number seed
const auto Seed = config.PopValue<int>("Seed");
//Various boolean flags
const auto ReNormalizeInputSpectrum = config.PopValue<bool>("ReNormalizeInputSpectrum", false);
const auto RayleighScatter = config.PopValue<bool>("RayleighScatter", true);
//Power spectrum to use. Default to CAMB
const auto WhichSpectrum = config.PopValue<int>("WhichSpectrum", 2);
//Is twolpt on?
const auto twolpt = config.PopValue<bool>("TWOLPT",true);
//Unit system
const auto UnitLength_in_cm = config.PopValue<double>("UnitLength_in_cm", 3.085678e21);
const auto UnitVelocity_in_cm_per_s = config.PopValue<double>("UnitVelocity_in_cm_per_s", 1e5);
const auto UnitMass_in_g = config.PopValue<double>("UnitMass_in_g", 1.989e43);
const double UnitTime_in_s = UnitLength_in_cm / UnitVelocity_in_cm_per_s;
//WDM options
bool WDM_Vtherm_On = config.PopValue<bool>("WDM_On",false);
WDM_Vtherm_On = config.PopValue<bool>("WDM_Vtherm_On",false) && WDM_Vtherm_On;
const auto WDM_PartMass_in_kev = config.PopValue<double>("WDM_PartMass_in_kev", 0);
//Neutrino options
//Enable particle neutrinos for type 2 particles. Does nothing unless NU_Vtherm is also true
bool NU_Vtherm_On = config.PopValue<bool>("NU_On",false);
//Add thermal velocities to type 2 particles if NU_On is also true.
NU_Vtherm_On = config.PopValue<bool>("NU_Vtherm_On",false) && NU_Vtherm_On;
//This triggers the use of neutrinos via an altered transfer function
//Should be on only if you are faking neutrinos by combining them with the dark matter,
//and changing the transfer function, which is a terrible way of simulating neutrinos. So leave it off.
const auto combined_neutrinos = config.PopValue<bool>("NU_KSPACE",false);
//Changes whether we have two heavy and one light neutrino or one heavy two light.
const auto InvertedHierarchy = config.PopValue<bool>("InvertedHierarchy",false);
//Total neutrino mass
const auto NU_PartMass_in_ev = config.PopValue<double>("NU_PartMass_in_ev",0);
//Parameter for the Efstathiou power spectrum. Generally does nothing.
const auto ShapeGamma = config.PopValue<double>("ShapeGamma",0.201);
//Needed if ReNormaliseInputSpectrum is on. Otherwise unused
const auto PrimordialIndex = config.PopValue<double>("PrimordialIndex",1.);
const auto Sigma8 = config.PopValue<double>("Sigma8",0.8);
//Number of particles desired
std::valarray<int64_t> npart((int64_t)0,(size_t)N_TYPE);
int CbRtNpart[6] = {0};
CbRtNpart[BARYON_TYPE] = config.PopValue<int>("NBaryon", 0);
CbRtNpart[DM_TYPE] = config.PopValue<int>("NCDM", 0);
CbRtNpart[NEUTRINO_TYPE] = config.PopValue<int>("NNeutrino", 0);
for(int type=0; type<N_TYPES; ++type)
npart[type] = static_cast<int64_t>(CbRtNpart[type])*CbRtNpart[type]*CbRtNpart[type];
printf("Particle numbers: %ld %ld %ld\n",npart[BARYON_TYPE], npart[DM_TYPE], npart[NEUTRINO_TYPE]);
assert(npart[BARYON_TYPE] > 0 || npart[DM_TYPE] > 0 || npart[NEUTRINO_TYPE] > 0);
if (Nmesh % 2 != 0){
printf("Nmesh must be even or correct output is not guaranteed.\n");
exit(1);
}
std::vector<std::string> unexpected = config.GetRemainingKeys();
if(unexpected.size() > 0){
std::cerr<<"Config file contained the following unexpected keys:"<<std::endl;
for(auto unex: unexpected)
std::cerr<<unex<<std::endl;
exit(1);
}
DisplacementFields displace(Nmesh, Seed, Box, twolpt);
/*Set particle numbers*/
if(npart.sum() == 0)
exit(1);
//Initialise a power spectrum
PowerSpec * PSpec;
switch(WhichSpectrum)
{
case 1:
PSpec = new PowerSpec_EH(HubbleParam, Omega, OmegaBaryon, UnitLength_in_cm);
break;
case 2:
PSpec = new PowerSpec_Tabulated(FileWithTransfer, FileWithInputSpectrum, Omega, OmegaLambda, OmegaBaryon, OmegaDM_2ndSpecies,InputSpectrum_UnitLength_in_cm, UnitLength_in_cm, !npart[BARYON_TYPE], combined_neutrinos);
break;
default:
PSpec = new PowerSpec_Efstathiou(ShapeGamma, UnitLength_in_cm);
}
//Make a cosmology
Cosmology cosmo(HubbleParam, Omega, OmegaLambda, NU_PartMass_in_ev, InvertedHierarchy);
//If normalisation or WDM are on, decorate the base power spectrum
//to do that
if (ReNormalizeInputSpectrum) {
PSpec = new NormalizedPowerSpec(PSpec, Sigma8, PrimordialIndex, cosmo.GrowthFactor(InitTime, 1.0), UnitLength_in_cm);
}
if(WDM_Vtherm_On)
PSpec = new WDMPowerSpec(PSpec, WDM_PartMass_in_kev, Omega, OmegaBaryon, HubbleParam, UnitLength_in_cm);
std::string extension("");
if (ICFormat > 4 || ICFormat < 2) {
fprintf(stderr, "Supported ICFormats:\n 2: Gadget 2 format files\n 3: HDF5\n 4: BigFile\n");
exit(1);
}
if (ICFormat == 3){
printf("Outputting HDF5 ICs\n");
extension=".hdf5";
}
GadgetWriter::GWriteBaseSnap *osnap;
#ifdef HAVE_BGFL
if(ICFormat == 4) {
osnap = new GadgetWriter::GWriteBigSnap(OutputDir+std::string("/")+FileBase+extension, npart, NumFiles);
}
else
#endif
osnap = new GadgetWriter::GWriteSnap(OutputDir+std::string("/")+FileBase+extension, npart,NumFiles, sizeof(id_type));
assert(osnap);
/*Write headers*/
gadget_header header = generate_header(npart, Omega, OmegaBaryon, OmegaDM_2ndSpecies, OmegaLambda, HubbleParam, Box, InitTime, UnitMass_in_g, UnitLength_in_cm, UnitVelocity_in_cm_per_s, combined_neutrinos);
//Generate regular particle grid
part_grid Pgrid(CbRtNpart, header.mass, Box);
if(osnap->WriteHeaders(header)) {
fprintf(stderr, "Could not write headers to snapshot\n");
exit(1);
}
int64_t FirstId=1;
//Compute the factors to go from velocity to displacement
const double hubble_a = cosmo.Hubble(InitTime)*UnitTime_in_s;
const double vel_prefac = InitTime * hubble_a * cosmo.F_Omega(InitTime) /sqrt(InitTime);
//Only used if twolpt is on
//This is slightly approximate: we are assuming that D2 ~ -3/7 Da^2 Omega_m^{-1/143} (Bouchet, F 1995, A&A 296)
const double vel_prefac2 = -3./7.*pow(Omega, -1./143)*InitTime * hubble_a * cosmo.F2_Omega(InitTime) /sqrt(InitTime);
printf("vel_prefac= %g hubble_a=%g fom=%g Omega=%g \n", vel_prefac, hubble_a, cosmo.F_Omega(InitTime), Omega);
for(int type=0; type<N_TYPE;type++){
if(npart[type] == 0)
continue;
FermiDiracVel * therm_vels = NULL;
//For WDM thermal velocities
if(WDM_Vtherm_On && type == 1){
const double wdm_vth = WDM_V0(Redshift, WDM_PartMass_in_kev, Omega-OmegaBaryon, HubbleParam, UnitVelocity_in_cm_per_s);
therm_vels = new FermiDiracVel (wdm_vth);
printf("\nWarm dark matter rms velocity dispersion at starting redshift = %g km/sec\n\n",3.59714 * wdm_vth);
}
#ifdef NEUTRINOS
//Neutrino thermal velocities
if(NU_Vtherm_On && type == 2) {
//Init structure for neutrino velocities
const double v_th = NU_V0(Redshift, NU_PartMass_in_ev, UnitVelocity_in_cm_per_s);
therm_vels = new FermiDiracVel (v_th);
printf("\nNeutrino rms vel. dispersion %g (km/s)\n\n",v_th/sqrt(1+Redshift));
}
#endif //NEUTRINOS
lpt_data outdata = displace.displacement_fields(type, Pgrid, PSpec, RayleighScatter);
outdata.SetVelPrefac(vel_prefac, vel_prefac2);
FirstId = write_particle_data(*osnap, type,&outdata, Pgrid, therm_vels, FirstId);
delete therm_vels;
}
delete PSpec;
printf("Initial scale factor = %g\n", InitTime);
}
catch(std::ios_base::failure& e) {
std::cerr<<e.what();
return 4;
}
catch(std::runtime_error& e) {
std::cerr<<e.what();
return 1;
}
catch(std::invalid_argument& e) {
std::cerr<<e.what();
return 2;
}
catch(std::domain_error& e) {
std::cerr<<e.what();
return 3;
}
return 0;
}
<commit_msg>Clean up name of neutrino options<commit_after>#include "part_data.hpp"
#include "cosmology.hpp"
#include "power.hpp"
#include "displacement.hpp"
#include "read_param.hpp"
#include "thermalvel.hpp"
#include "save.hpp"
#include <cassert>
int main(int argc, char **argv)
{
if(argc < 2)
{
fprintf(stdout, "\nParameters are missing.\n");
fprintf(stdout, "Call with <ParameterFile>\n\n");
exit(0);
}
/*Make sure stdout is line buffered even when not
* printing to a terminal but, eg, perl*/
setlinebuf(stdout);
//May throw std::runtime_error
try {
//Read the config file
SpbConfigParser config(argv[1]);
//Cosmological parameters
const auto Omega = config.PopValue<double>("Omega");
const auto OmegaLambda = config.PopValue<double>("OmegaLambda");
const auto OmegaBaryon = config.PopValue<double>("OmegaBaryon");
const auto OmegaDM_2ndSpecies = config.PopValue<double>("OmegaNeutrino");
const auto HubbleParam = config.PopValue<double>("HubbleParam");
//Which output format should we use. 4 is bigfile, 3 is HDF5, 2 is Gadget 2. Default to 3.
const auto ICFormat = config.PopValue<int>("ICFormat", 3);
//How many output files to use in the set
const auto NumFiles = config.PopValue<int>("NumFiles");
//Parameters of the simulation box
const auto Box = config.PopValue<double>("Box");
const auto Redshift = config.PopValue<double>("Redshift");
const double InitTime = 1 / (1 + Redshift);
//Size of FFT
const size_t Nmesh = config.PopValue<int>("Nmesh");
//Unused unless CAMB spectrum
const auto FileWithInputSpectrum = config.PopValue<std::string>("FileWithInputSpectrum");
const auto FileWithTransfer = config.PopValue<std::string>("FileWithTransfer");
const auto InputSpectrum_UnitLength_in_cm = config.PopValue<double>("InputSpectrum_UnitLength_in_cm", 3.085678e24);
//Output filenames
const auto OutputDir = config.PopValue<std::string>("OutputDir");
const auto FileBase = config.PopValue<std::string>("FileBase");
//Random number seed
const auto Seed = config.PopValue<int>("Seed");
//Various boolean flags
const auto ReNormalizeInputSpectrum = config.PopValue<bool>("ReNormalizeInputSpectrum", false);
const auto RayleighScatter = config.PopValue<bool>("RayleighScatter", true);
//Power spectrum to use. Default to CAMB
const auto WhichSpectrum = config.PopValue<int>("WhichSpectrum", 2);
//Is twolpt on?
const auto twolpt = config.PopValue<bool>("TWOLPT",true);
//Unit system
const auto UnitLength_in_cm = config.PopValue<double>("UnitLength_in_cm", 3.085678e21);
const auto UnitVelocity_in_cm_per_s = config.PopValue<double>("UnitVelocity_in_cm_per_s", 1e5);
const auto UnitMass_in_g = config.PopValue<double>("UnitMass_in_g", 1.989e43);
const double UnitTime_in_s = UnitLength_in_cm / UnitVelocity_in_cm_per_s;
//WDM options
bool WDM_Vtherm_On = config.PopValue<bool>("WDM_Vtherm_On",false);
const auto WDM_PartMass_in_kev = config.PopValue<double>("WDM_PartMass_in_kev", 0);
//Neutrino options
//Add thermal velocities to type 2 particles
bool NU_Vtherm_On = config.PopValue<bool>("NU_Vtherm_On",false);
//This triggers the use of neutrinos via an altered transfer function
//Should be on only if you are faking neutrinos by combining them with the dark matter,
//and changing the transfer function, which is a terrible way of simulating neutrinos. So leave it off.
const auto combined_neutrinos = config.PopValue<bool>("NU_in_DM",false);
//Changes whether we have two heavy and one light neutrino or one heavy two light.
const auto InvertedHierarchy = config.PopValue<bool>("InvertedHierarchy",false);
//Total neutrino mass
const auto NU_PartMass_in_ev = config.PopValue<double>("NU_PartMass_in_ev",0);
//Parameter for the Efstathiou power spectrum. Generally does nothing.
const auto ShapeGamma = config.PopValue<double>("ShapeGamma",0.201);
//Needed if ReNormaliseInputSpectrum is on. Otherwise unused
const auto PrimordialIndex = config.PopValue<double>("PrimordialIndex",1.);
const auto Sigma8 = config.PopValue<double>("Sigma8",0.8);
//Number of particles desired
std::valarray<int64_t> npart((int64_t)0,(size_t)N_TYPE);
int CbRtNpart[6] = {0};
CbRtNpart[BARYON_TYPE] = config.PopValue<int>("NBaryon", 0);
CbRtNpart[DM_TYPE] = config.PopValue<int>("NCDM", 0);
CbRtNpart[NEUTRINO_TYPE] = config.PopValue<int>("NNeutrino", 0);
for(int type=0; type<N_TYPES; ++type)
npart[type] = static_cast<int64_t>(CbRtNpart[type])*CbRtNpart[type]*CbRtNpart[type];
printf("Particle numbers: %ld %ld %ld\n",npart[BARYON_TYPE], npart[DM_TYPE], npart[NEUTRINO_TYPE]);
assert(npart[BARYON_TYPE] > 0 || npart[DM_TYPE] > 0 || npart[NEUTRINO_TYPE] > 0);
if (Nmesh % 2 != 0){
printf("Nmesh must be even or correct output is not guaranteed.\n");
exit(1);
}
std::vector<std::string> unexpected = config.GetRemainingKeys();
if(unexpected.size() > 0){
std::cerr<<"Config file contained the following unexpected keys:"<<std::endl;
for(auto unex: unexpected)
std::cerr<<unex<<std::endl;
exit(1);
}
DisplacementFields displace(Nmesh, Seed, Box, twolpt);
/*Set particle numbers*/
if(npart.sum() == 0)
exit(1);
//Initialise a power spectrum
PowerSpec * PSpec;
switch(WhichSpectrum)
{
case 1:
PSpec = new PowerSpec_EH(HubbleParam, Omega, OmegaBaryon, UnitLength_in_cm);
break;
case 2:
PSpec = new PowerSpec_Tabulated(FileWithTransfer, FileWithInputSpectrum, Omega, OmegaLambda, OmegaBaryon, OmegaDM_2ndSpecies,InputSpectrum_UnitLength_in_cm, UnitLength_in_cm, !npart[BARYON_TYPE], combined_neutrinos);
break;
default:
PSpec = new PowerSpec_Efstathiou(ShapeGamma, UnitLength_in_cm);
}
//Make a cosmology
Cosmology cosmo(HubbleParam, Omega, OmegaLambda, NU_PartMass_in_ev, InvertedHierarchy);
//If normalisation or WDM are on, decorate the base power spectrum
//to do that
if (ReNormalizeInputSpectrum) {
PSpec = new NormalizedPowerSpec(PSpec, Sigma8, PrimordialIndex, cosmo.GrowthFactor(InitTime, 1.0), UnitLength_in_cm);
}
if(WDM_Vtherm_On)
PSpec = new WDMPowerSpec(PSpec, WDM_PartMass_in_kev, Omega, OmegaBaryon, HubbleParam, UnitLength_in_cm);
std::string extension("");
if (ICFormat > 4 || ICFormat < 2) {
fprintf(stderr, "Supported ICFormats:\n 2: Gadget 2 format files\n 3: HDF5\n 4: BigFile\n");
exit(1);
}
if (ICFormat == 3){
printf("Outputting HDF5 ICs\n");
extension=".hdf5";
}
GadgetWriter::GWriteBaseSnap *osnap;
#ifdef HAVE_BGFL
if(ICFormat == 4) {
osnap = new GadgetWriter::GWriteBigSnap(OutputDir+std::string("/")+FileBase+extension, npart, NumFiles);
}
else
#endif
osnap = new GadgetWriter::GWriteSnap(OutputDir+std::string("/")+FileBase+extension, npart,NumFiles, sizeof(id_type));
assert(osnap);
/*Write headers*/
gadget_header header = generate_header(npart, Omega, OmegaBaryon, OmegaDM_2ndSpecies, OmegaLambda, HubbleParam, Box, InitTime, UnitMass_in_g, UnitLength_in_cm, UnitVelocity_in_cm_per_s, combined_neutrinos);
//Generate regular particle grid
part_grid Pgrid(CbRtNpart, header.mass, Box);
if(osnap->WriteHeaders(header)) {
fprintf(stderr, "Could not write headers to snapshot\n");
exit(1);
}
int64_t FirstId=1;
//Compute the factors to go from velocity to displacement
const double hubble_a = cosmo.Hubble(InitTime)*UnitTime_in_s;
const double vel_prefac = InitTime * hubble_a * cosmo.F_Omega(InitTime) /sqrt(InitTime);
//Only used if twolpt is on
//This is slightly approximate: we are assuming that D2 ~ -3/7 Da^2 Omega_m^{-1/143} (Bouchet, F 1995, A&A 296)
const double vel_prefac2 = -3./7.*pow(Omega, -1./143)*InitTime * hubble_a * cosmo.F2_Omega(InitTime) /sqrt(InitTime);
printf("vel_prefac= %g hubble_a=%g fom=%g Omega=%g \n", vel_prefac, hubble_a, cosmo.F_Omega(InitTime), Omega);
for(int type=0; type<N_TYPE;type++){
if(npart[type] == 0)
continue;
FermiDiracVel * therm_vels = NULL;
//For WDM thermal velocities
if(WDM_Vtherm_On && type == 1){
const double wdm_vth = WDM_V0(Redshift, WDM_PartMass_in_kev, Omega-OmegaBaryon, HubbleParam, UnitVelocity_in_cm_per_s);
therm_vels = new FermiDiracVel (wdm_vth);
printf("\nWarm dark matter rms velocity dispersion at starting redshift = %g km/sec\n\n",3.59714 * wdm_vth);
}
#ifdef NEUTRINOS
//Neutrino thermal velocities
if(NU_Vtherm_On && type == 2) {
//Init structure for neutrino velocities
const double v_th = NU_V0(Redshift, NU_PartMass_in_ev, UnitVelocity_in_cm_per_s);
therm_vels = new FermiDiracVel (v_th);
printf("\nNeutrino rms vel. dispersion %g (km/s)\n\n",v_th/sqrt(1+Redshift));
}
#endif //NEUTRINOS
lpt_data outdata = displace.displacement_fields(type, Pgrid, PSpec, RayleighScatter);
outdata.SetVelPrefac(vel_prefac, vel_prefac2);
FirstId = write_particle_data(*osnap, type,&outdata, Pgrid, therm_vels, FirstId);
delete therm_vels;
}
delete PSpec;
printf("Initial scale factor = %g\n", InitTime);
}
catch(std::ios_base::failure& e) {
std::cerr<<e.what();
return 4;
}
catch(std::runtime_error& e) {
std::cerr<<e.what();
return 1;
}
catch(std::invalid_argument& e) {
std::cerr<<e.what();
return 2;
}
catch(std::domain_error& e) {
std::cerr<<e.what();
return 3;
}
return 0;
}
<|endoftext|> |
<commit_before>
#include <iostream>
#include <cstring>
#include <cassert>
#include "csprot.hpp"
using csprot::operator"" _S;
using csprot::operator"" _XS;
#define TEST(...) \
static_assert(__VA_ARGS__, #__VA_ARGS__)
/**************************************************************************/
void test_prop() {
TEST("1"_S.plain() == true);
TEST("1"_S.xored() == false);
TEST("1"_XS.plain() == false);
TEST("1"_XS.xored() == true);
}
void test_size() {
TEST(""_S.size() == 0 && ""_S.length() == 0 && ""_S.empty() == true);
TEST("1"_S.size() == 1 && "1"_S.length() == 1 && "1"_S.empty() == false);
}
void test_cat() {
struct {
constexpr int operator()(const char *a, const char *b) const {
return
*a == 0 && *b == 0 ? 0 :
*a == 0 ? -1 :
*b == 0 ? 1 :
*a < *b ? -1 :
*a > *b ? 1 :
*a == *b ? operator()(a+1, b+1) : throw "compare::operator(a, b) error";
}
} compare{};
auto s0 = "1"_S + "2"_S;
TEST(compare(s0.c_str(), "12") == 0);
}
void test_compare() {
TEST("1"_S == "1"_S);
TEST("1"_XS == "1"_XS);
TEST("1"_S != "1"_XS);
TEST("1"_S == "1"_S);
TEST("1"_S != "2"_S);
TEST(""_S == ""_S);
}
void test_xored_string() {
TEST("1"_S.data()[0] == '1');
TEST("1"_XS.data()[0] != '1');
}
/**************************************************************************/
int main() {
test_prop();
test_size();
test_cat();
test_compare();
test_xored_string();
auto s0 = "some xor`ed string 0"_XS;
assert(std::strcmp(s0.data (), "some xor`ed string 0") != 0);
assert(std::strcmp(s0.c_str(), "some xor`ed string 0") == 0);
std::cout << "s0.data()=" << s0.data() << std::endl;
std::cout << "s0.c_str()=" << s0.c_str() << std::endl;
auto s1 = "some plain string 0"_S;
assert(std::strcmp(s1.data (), "some plain string 0") == 0);
assert(std::strcmp(s1.c_str(), "some plain string 0") == 0);
std::cout << "s1.data()=" << s1.data() << std::endl;
std::cout << "s1.c_str()=" << s1.c_str() << std::endl;
}
/**************************************************************************/
<commit_msg>fixes<commit_after>
#include <iostream>
#include <cstring>
#include <cassert>
#include "csprot.hpp"
using csprot::operator"" _S;
using csprot::operator"" _XS;
#define TEST(...) \
static_assert(__VA_ARGS__, #__VA_ARGS__)
/**************************************************************************/
void test_prop() {
TEST("1"_S.is_plain() == true);
TEST("1"_S.is_xored() == false);
TEST("1"_XS.is_plain() == false);
TEST("1"_XS.is_xored() == true);
}
void test_size() {
TEST(""_S.size() == 0 && ""_S.length() == 0 && ""_S.empty() == true);
TEST("1"_S.size() == 1 && "1"_S.length() == 1 && "1"_S.empty() == false);
}
void test_cat() {
struct {
constexpr int operator()(const char *a, const char *b) const {
return
*a == 0 && *b == 0 ? 0 :
*a == 0 ? -1 :
*b == 0 ? 1 :
*a < *b ? -1 :
*a > *b ? 1 :
*a == *b ? operator()(a+1, b+1) : throw "compare::operator(a, b) error";
}
} compare{};
auto s0 = "1"_S + "2"_S;
TEST(compare(s0.c_str(), "12") == 0);
}
void test_compare() {
TEST("1"_S == "1"_S);
TEST("1"_XS == "1"_XS);
TEST("1"_S != "1"_XS);
TEST("1"_S == "1"_S);
TEST("1"_S != "2"_S);
TEST(""_S == ""_S);
}
void test_xored_string() {
TEST("1"_S.data()[0] == '1');
TEST("1"_XS.data()[0] != '1');
}
/**************************************************************************/
template<typename>
struct impl;
template<>
struct impl<decltype("posix implementation"_XS)> {
std::string name() const { return "posix implementation"_XS.c_str(); }
};
template<>
struct impl<decltype("win32 implementation"_XS)> {
std::string name() const { return "win32 implementation"_XS.c_str(); }
};
int main() {
test_prop();
test_size();
test_cat();
test_compare();
test_xored_string();
auto s0 = "some xor`ed string 0"_XS;
assert(std::strcmp(s0.data (), "some xor`ed string 0") != 0);
assert(std::strcmp(s0.c_str(), "some xor`ed string 0") == 0);
std::cout << "s0.data()=" << s0.data() << std::endl;
std::cout << "s0.c_str()=" << s0.c_str() << std::endl;
auto s1 = "some plain string 0"_S;
assert(std::strcmp(s1.data (), "some plain string 0") == 0);
assert(std::strcmp(s1.c_str(), "some plain string 0") == 0);
std::cout << "s1.data()=" << s1.data() << std::endl;
std::cout << "s1.c_str()=" << s1.c_str() << std::endl;
impl<decltype("win32 implementation"_XS)> impl;
const auto name = impl.name();
assert(name == "win32 implementation");
}
/**************************************************************************/
<|endoftext|> |
<commit_before>6e3bb7ee-2e4f-11e5-bff9-28cfe91dbc4b<commit_msg>6e46a7ee-2e4f-11e5-8e56-28cfe91dbc4b<commit_after>6e46a7ee-2e4f-11e5-8e56-28cfe91dbc4b<|endoftext|> |
<commit_before>6ad85524-2fa5-11e5-9227-00012e3d3f12<commit_msg>6ada29e4-2fa5-11e5-b8b9-00012e3d3f12<commit_after>6ada29e4-2fa5-11e5-b8b9-00012e3d3f12<|endoftext|> |
<commit_before>d2603c8c-2e4e-11e5-bb77-28cfe91dbc4b<commit_msg>d26842eb-2e4e-11e5-865b-28cfe91dbc4b<commit_after>d26842eb-2e4e-11e5-865b-28cfe91dbc4b<|endoftext|> |
<commit_before>// main.cpp
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
#include <map>
#include <ctime>
#include <chrono>
#include <cstdlib>
#include <cassert>
typedef long myint;
myint atoisimple(const char *b)
{
myint res = 0; // Initialize result
int sgn = 1;
// Skip whitespace
// TODO: recognize not only spaces
for (; *b == ' '; ++b);
if (*b == '-')
{
sgn = -1;
++b;
}
else if (*b == '+')
{
++b;
}
// Iterate through all characters of input string and update result
for (; *b != 0; ++b)
{
if (*b < '0' || *b > '9')
{
return sgn * res;
}
res = res * 10 + *b - '0';
}
// return result.
return sgn * res;
}
myint fastatoi(const char *b)
{
myint res = 0; // Initialize result
int sgn = 1;
// Skip whitespace
// TODO: recognize not only spaces
for (; *b == ' '; ++b);
if (*b == '-')
{
sgn = -1;
++b;
}
else if (*b == '+')
{
++b;
}
// Iterate through all characters of input string and update result
for (; *b != 0; ++b)
{
unsigned d = static_cast<unsigned>(*b) - '0';
if (d > 9)
{
return sgn * res;
}
res = res * 10 + d;
}
// return result.
return sgn * res;
}
myint fastatoiadd(const char *b)
{
myint res = 0; // Initialize result
// Skip whitespace
// TODO: recognize not only spaces
for (; *b == ' '; ++b);
if (*b == '-')
{
++b;
// Iterate through all characters of input string and update result
for (; ; ++b)
{
unsigned d = static_cast<unsigned>(*b) - '0';
if (d > 9)
{
return res;
}
res = res * 10 - d;
}
}
else if (*b == '+')
{
++b;
}
// Iterate through all characters of input string and update result
for (; ; ++b)
{
unsigned d = static_cast<unsigned>(*b) - '0';
if (d > 9)
{
return res;
}
res = res * 10 + d;
}
// unreachable
return res;
}
myint fastatoiaddunr(const char *b)
{
myint res = 0; // Initialize result
// Skip whitespace
// TODO: recognize not only spaces
for (; *b == ' '; ++b);
if (*b == '-')
{
++b;
unsigned d = static_cast<unsigned>(*b) - '0';
if (d > 9)
{
return 0;
}
res = -static_cast<myint>(d);
++b;
// Iterate through all characters of input string and update result
for (; ; ++b)
{
unsigned d = static_cast<unsigned>(*b) - '0';
if (d > 9)
{
return res;
}
res = res * 10 - d;
}
}
else if (*b == '+')
{
++b;
}
unsigned d = static_cast<unsigned>(*b) - '0';
if (d > 9)
{
return 0;
}
res = d;
++b;
// Iterate through all characters of input string and update result
for (; ; ++b)
{
unsigned d = static_cast<unsigned>(*b) - '0';
if (d > 9)
{
return res;
}
res = res * 10 + d;
}
// unreachable
return res;
}
myint zero(const char *b)
{
volatile myint res = (*b == 0); // Initialize result
// return result.
return res;
}
typedef std::map<std::string, unsigned long long> Name2Time;
template <typename F>
void test(unsigned long rep,
F f,
const std::vector<std::string>& v,
Name2Time& best,
const std::string& name)
{
try
{
const char* b = 0;
const char* e = 0;
myint r = 0;
auto et0 = std::chrono::system_clock::now();
std::clock_t t0 = std::clock();
for (unsigned int i = 0; i < rep; ++i)
{
unsigned int ii = i % v.size();
b = v[ii].c_str();
r += f(b);
}
std::clock_t t = std::clock();
auto et = std::chrono::system_clock::now() - et0;
std::cout << name << ":" << std::setw(18) << r << "," <<
std::setw(10) << t - t0 << ", " <<
std::setw(10) << et.count() << std::endl;
if (name.length() > 0)
{
std::string ename = "e." + name;
std::string cname = "c." + name;
auto bt = best[ename];
if (bt == 0 || bt > et.count()) { best[ename] = et.count(); }
bt = best[cname];
if (bt == 0 || bt > t - t0) { best[cname] = t - t0; }
}
}
catch(std::exception& exc)
{
std::cout << "ERROR" << std::endl;
}
}
unsigned long N = 10000000UL;
const unsigned WORD_COUNT = 10000;
const unsigned MAX_WORD_LEN = 8;
bool unit_test()
{
assert(fastatoiaddunr("-10") == atoi("-10"));
assert(fastatoiadd("-10") == atoi("-10"));
assert(fastatoi("-10") == atoi("-10"));
}
void generate_add(std::vector<std::string>& v, int count, int length, bool digits_only)
{
for (unsigned i = 0; i < count; ++i)
{
std::string s;
for (unsigned j = 0; j < length; ++j)
{
s += '0' + (i + j * 7) % 10;
}
int mode = digits_only ? 0 : (i % 5);
switch (mode)
{
case 0:
v.push_back(s);
break;
case 1:
v.push_back('-' + s);
break;
case 2:
v.push_back('+' + s);
break;
case 3:
v.push_back(" -" + s + ")))");
break;
case 4:
v.push_back(" +" + s + ".12");
break;
}
}
}
int main(int argc, char* argv[])
{
bool digits_only = false;
for (size_t L = 1; L <= MAX_WORD_LEN; ++L)
{
Name2Time best;
std::vector<std::string> v;
generate_add(v, WORD_COUNT, L, digits_only);
std::cout << "Digits per number: " << L << " The string contains"<< (digits_only ? " digits only" : " whitespace and sign" )<< std::endl;
std::cout << "Int size in bytes:" << sizeof(myint) << std::endl;
std::cout << "Ramp up:" << std::endl;
test(N, atoi, v, best, "");
for (int i = 0; i < 3; ++i)
{
test(N, zero, v, best, "zero..........");
test(N, atoi, v, best, "atoi..........");
test(N, atoisimple, v, best, "atoisimple....");
test(N, fastatoi, v, best, "fastatoi......");
test(N, fastatoiadd, v, best, "fastatoiadd...");
test(N, fastatoiaddunr, v, best, "fastatoiaddunr");
}
for (auto& kv : best)
{
std::cout << "Best: " << kv.first << " : " << std::setw(11) << kv.second << std::endl;
}
if (argc > 1)
{
std::ofstream f(argv[1], std::ios::app | std::ios::out);
if (!f.fail())
{
for (auto& kv : best)
{
f << L << "," << (digits_only ? "DO" : "WS" ) << "," << kv.first << "," << kv.second << std::endl;
}
}
}
else
{
std::cout << "No output file param" << std::endl;
}
}
return 0;
}
<commit_msg>Support other whitespace characters like tabs<commit_after>// main.cpp
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
#include <map>
#include <ctime>
#include <chrono>
#include <cstdlib>
#include <cassert>
typedef long myint;
// this definition does not work properly for tabs, newlines etc.
//#define isspace_fast(x) ((x) == ' ')
// "C" locale compatible definition
#define isspace_fast(x) ((x) == ' ' || (x) == '\t' || (x) == '\n' || (x) == '\v' || (x) == '\f' || (x) == '\r')
myint atoisimple(const char *b)
{
myint res = 0; // Initialize result
int sgn = 1;
// Skip whitespace
for (; isspace_fast(*b); ++b);
if (*b == '-')
{
sgn = -1;
++b;
}
else if (*b == '+')
{
++b;
}
// Iterate through all characters of input string and update result
for (; *b != 0; ++b)
{
if (*b < '0' || *b > '9')
{
return sgn * res;
}
res = res * 10 + *b - '0';
}
// return result.
return sgn * res;
}
myint fastatoi(const char *b)
{
myint res = 0; // Initialize result
int sgn = 1;
// Skip whitespace
for (; isspace_fast(*b); ++b);
if (*b == '-')
{
sgn = -1;
++b;
}
else if (*b == '+')
{
++b;
}
// Iterate through all characters of input string and update result
for (; *b != 0; ++b)
{
unsigned d = static_cast<unsigned>(*b) - '0';
if (d > 9)
{
return sgn * res;
}
res = res * 10 + d;
}
// return result.
return sgn * res;
}
myint fastatoiadd(const char *b)
{
myint res = 0; // Initialize result
// Skip whitespace
for (; isspace_fast(*b); ++b);
if (*b == '-')
{
++b;
// Iterate through all characters of input string and update result
for (; ; ++b)
{
unsigned d = static_cast<unsigned>(*b) - '0';
if (d > 9)
{
return res;
}
res = res * 10 - d;
}
}
else if (*b == '+')
{
++b;
}
// Iterate through all characters of input string and update result
for (; ; ++b)
{
unsigned d = static_cast<unsigned>(*b) - '0';
if (d > 9)
{
return res;
}
res = res * 10 + d;
}
// unreachable
return res;
}
myint fastatoiaddunr(const char *b)
{
myint res = 0; // Initialize result
// Skip whitespace
for (; isspace_fast(*b); ++b);
if (*b == '-')
{
++b;
unsigned d = static_cast<unsigned>(*b) - '0';
if (d > 9)
{
return 0;
}
res = -static_cast<myint>(d);
++b;
// Iterate through all characters of input string and update result
for (; ; ++b)
{
unsigned d = static_cast<unsigned>(*b) - '0';
if (d > 9)
{
return res;
}
res = res * 10 - d;
}
}
else if (*b == '+')
{
++b;
}
unsigned d = static_cast<unsigned>(*b) - '0';
if (d > 9)
{
return 0;
}
res = d;
++b;
// Iterate through all characters of input string and update result
for (; ; ++b)
{
unsigned d = static_cast<unsigned>(*b) - '0';
if (d > 9)
{
return res;
}
res = res * 10 + d;
}
// unreachable
return res;
}
myint zero(const char *b)
{
volatile myint res = (*b == 0); // Initialize result
// return result.
return res;
}
typedef std::map<std::string, unsigned long long> Name2Time;
template <typename F>
void test(unsigned long rep,
F f,
const std::vector<std::string>& v,
Name2Time& best,
const std::string& name)
{
try
{
const char* b = 0;
const char* e = 0;
myint r = 0;
auto et0 = std::chrono::system_clock::now();
std::clock_t t0 = std::clock();
for (unsigned int i = 0; i < rep; ++i)
{
unsigned int ii = i % v.size();
b = v[ii].c_str();
r += f(b);
}
std::clock_t t = std::clock();
auto et = std::chrono::system_clock::now() - et0;
std::cout << name << ":" << std::setw(18) << r << "," <<
std::setw(10) << t - t0 << ", " <<
std::setw(10) << et.count() << std::endl;
if (name.length() > 0)
{
std::string ename = "e." + name;
std::string cname = "c." + name;
auto bt = best[ename];
if (bt == 0 || bt > et.count()) { best[ename] = et.count(); }
bt = best[cname];
if (bt == 0 || bt > t - t0) { best[cname] = t - t0; }
}
}
catch(std::exception& exc)
{
std::cout << "ERROR" << std::endl;
}
}
unsigned long N = 10000000UL;
const unsigned WORD_COUNT = 10000;
const unsigned MAX_WORD_LEN = 8;
bool unit_test()
{
assert(fastatoiaddunr("-10") == atoi("-10"));
assert(fastatoiadd("-10") == atoi("-10"));
assert(fastatoi("-10") == atoi("-10"));
}
void generate_add(std::vector<std::string>& v, int count, int length, bool digits_only)
{
for (unsigned i = 0; i < count; ++i)
{
std::string s;
for (unsigned j = 0; j < length; ++j)
{
s += '0' + (i + j * 7) % 10;
}
int mode = digits_only ? 0 : (i % 5);
switch (mode)
{
case 0:
v.push_back(s);
break;
case 1:
v.push_back('-' + s);
break;
case 2:
v.push_back('+' + s);
break;
case 3:
v.push_back(" -" + s + ")))");
break;
case 4:
v.push_back(" +" + s + ".12");
break;
}
}
}
int main(int argc, char* argv[])
{
bool digits_only = false;
for (size_t L = 1; L <= MAX_WORD_LEN; ++L)
{
Name2Time best;
std::vector<std::string> v;
generate_add(v, WORD_COUNT, L, digits_only);
std::cout << "Digits per number: " << L << " The string contains"<< (digits_only ? " digits only" : " whitespace and sign" )<< std::endl;
std::cout << "Int size in bytes:" << sizeof(myint) << std::endl;
std::cout << "Ramp up:" << std::endl;
test(N, atoi, v, best, "");
for (int i = 0; i < 3; ++i)
{
test(N, zero, v, best, "zero..........");
test(N, atoi, v, best, "atoi..........");
test(N, atoisimple, v, best, "atoisimple....");
test(N, fastatoi, v, best, "fastatoi......");
test(N, fastatoiadd, v, best, "fastatoiadd...");
test(N, fastatoiaddunr, v, best, "fastatoiaddunr");
}
for (auto& kv : best)
{
std::cout << "Best: " << kv.first << " : " << std::setw(11) << kv.second << std::endl;
}
if (argc > 1)
{
std::ofstream f(argv[1], std::ios::app | std::ios::out);
if (!f.fail())
{
for (auto& kv : best)
{
f << L << "," << (digits_only ? "DO" : "WS" ) << "," << kv.first << "," << kv.second << std::endl;
}
}
}
else
{
std::cout << "No output file param" << std::endl;
}
}
return 0;
}
<|endoftext|> |
<commit_before>54d4f1f4-2e3a-11e5-bf3a-c03896053bdd<commit_msg>54e5218a-2e3a-11e5-9325-c03896053bdd<commit_after>54e5218a-2e3a-11e5-9325-c03896053bdd<|endoftext|> |
<commit_before>45898766-2e4f-11e5-8b65-28cfe91dbc4b<commit_msg>45919e6b-2e4f-11e5-a414-28cfe91dbc4b<commit_after>45919e6b-2e4f-11e5-a414-28cfe91dbc4b<|endoftext|> |
<commit_before>622f7d80-ad5c-11e7-a23c-ac87a332f658<commit_msg>Gapjgjchguagdmg<commit_after>62b8d0bd-ad5c-11e7-a639-ac87a332f658<|endoftext|> |
<commit_before>e62dd0ee-2e4e-11e5-97da-28cfe91dbc4b<commit_msg>e6360e75-2e4e-11e5-b534-28cfe91dbc4b<commit_after>e6360e75-2e4e-11e5-b534-28cfe91dbc4b<|endoftext|> |
<commit_before>9cd20308-35ca-11e5-b2b7-6c40088e03e4<commit_msg>9cda5e8c-35ca-11e5-bcff-6c40088e03e4<commit_after>9cda5e8c-35ca-11e5-bcff-6c40088e03e4<|endoftext|> |
<commit_before>d095147a-2e4e-11e5-b85b-28cfe91dbc4b<commit_msg>d09d7eab-2e4e-11e5-affa-28cfe91dbc4b<commit_after>d09d7eab-2e4e-11e5-affa-28cfe91dbc4b<|endoftext|> |
<commit_before>771ca434-5216-11e5-8beb-6c40088e03e4<commit_msg>77235fe8-5216-11e5-8c5b-6c40088e03e4<commit_after>77235fe8-5216-11e5-8c5b-6c40088e03e4<|endoftext|> |
<commit_before>d4cc22d7-2e4e-11e5-8071-28cfe91dbc4b<commit_msg>d4d3c0eb-2e4e-11e5-a781-28cfe91dbc4b<commit_after>d4d3c0eb-2e4e-11e5-a781-28cfe91dbc4b<|endoftext|> |
<commit_before>781add46-2d53-11e5-baeb-247703a38240<commit_msg>781b5bfe-2d53-11e5-baeb-247703a38240<commit_after>781b5bfe-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>cf31c806-35ca-11e5-a198-6c40088e03e4<commit_msg>cf39d1b6-35ca-11e5-82c6-6c40088e03e4<commit_after>cf39d1b6-35ca-11e5-82c6-6c40088e03e4<|endoftext|> |
<commit_before>46b4a558-2e3a-11e5-b4fe-c03896053bdd<commit_msg>46c3ea5c-2e3a-11e5-afa4-c03896053bdd<commit_after>46c3ea5c-2e3a-11e5-afa4-c03896053bdd<|endoftext|> |
<commit_before>7b868a1e-2e4f-11e5-910a-28cfe91dbc4b<commit_msg>7b8dde7a-2e4f-11e5-8c39-28cfe91dbc4b<commit_after>7b8dde7a-2e4f-11e5-8c39-28cfe91dbc4b<|endoftext|> |
<commit_before>39b168f0-2e4f-11e5-b07f-28cfe91dbc4b<commit_msg>39ba0e45-2e4f-11e5-8c4c-28cfe91dbc4b<commit_after>39ba0e45-2e4f-11e5-8c4c-28cfe91dbc4b<|endoftext|> |
<commit_before>bf8807f5-2e4f-11e5-8be2-28cfe91dbc4b<commit_msg>bf8eb66e-2e4f-11e5-8e90-28cfe91dbc4b<commit_after>bf8eb66e-2e4f-11e5-8e90-28cfe91dbc4b<|endoftext|> |
<commit_before>#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include "GameApp.h"
int main(){
GameApp villainTycoon;
villainTycoon.run();
return 0;
}
/*
// Declare a window object
sf::RenderWindow window(sf::VideoMode(800, 600), "My window");
// Spawn our asset manager, the service that will load our textures and assets
AssetManager myManager;
//Here is code for our animated sprite test.
AnimatedSprite animSprite(12, 50, 99);
animSprite.setTexture(*myManager.getTexture("AnimateTest.png"));
animSprite.setPosition(0, 200);
// Here we create the dungeon data structure that we're going to be storing our dungeon in.
// We pass in the texture that we want to be the default 'empty room' texture.
Dungeon dungeon(*myManager.getTexture("DefaultTile.png"));
// This is where we spawn the "free floating" dungeon tile that we can select
// and then drop into our dungeon data structure.
DungeonNode * spriteSpawn = new DungeonNode(0);
spriteSpawn->setTexture(*myManager.getTexture("DungeonTile.png"));
// Load up the test hero that's going to navigate around the dungeon and drop him into
// the first room.
Hero myHero;
myHero.setTexture(*myManager.getTexture("Hero.png"));
myHero.move(dungeon.getEntrance());
// This is our sprite offset, so that the sprite's corner doesn't jump to the
// location of the mouse when it's clicked on.
sf::Vector2i offset;
offset.x = 100;
offset.y = 100;
// We're starting the nodeID at 9 because there are nine nodes already in the dungeon
// (nodes 0 - 8)
int nodeID = 9;
// Check to make sure things are linked correctly
dungeon.soundOff();
// This tracks whether our floater tile is currently selected and held by the mouse.
bool held = false;
// Here we set up our clock so that we can draw the screen at a specific framerate
sf::Clock myClock;
int framesPerSecond = 24;
sf::Time fps = sf::milliseconds(1000 / framesPerSecond);
// Run the program for as long as the window is open
while (window.isOpen())
{
// check all the window's events that were triggered since the last
// iteration of the loop
sf::Event event;
while (window.pollEvent(event))
{
// On "close requested" event we close the window.
if (event.type == sf::Event::Closed){
window.close();
}
// When we click the mouse on the sprite we change the status to held
if (event.type == sf::Event::MouseButtonPressed &&
spriteSpawn->getGlobalBounds().contains(sf::Mouse::getPosition(window).x, sf::Mouse::getPosition(window).y))
{
held = true;
}
// This happens if an event is received and the mouse is pressed:
if (held)
{
if (event.type == sf::Event::MouseMoved)
{
spriteSpawn->setPosition(sf::Mouse::getPosition(window).x - offset.x, sf::Mouse::getPosition(window).y - offset.y);
}
// If the mouse is inside the sprite and currently held down, then released,
// try to drop the currently held sprite into the appropriate array slot
if (event.type == sf::Event::MouseButtonReleased)
{
// If it drops into an array slot then make a new node
if(dungeon.add(spriteSpawn))
{
spriteSpawn = new DungeonNode(nodeID);
nodeID++;
spriteSpawn->setTexture(*myManager.getTexture("DungeonTile.png"));
std::cout << "Creating a new sprite." << std::endl;
dungeon.soundOff();
}
// Irregardless if this is a new node (because the old node was dropped
// into the dungeon sucessfully) or not (because the old node didn't drop in) we put
// the sprite back up into the corner.
spriteSpawn->setPosition(0,0);
held = false;
}
}
// This event manages our keyboard input. This is mainly to manually test some
// movement stuff, once the game is live most movement things will be handled
// by automation.
// First we check to see if a key was pressed
if(event.type == sf::Event::KeyPressed){
// Then we check to see WHICH key was pressed when the KeyPressed event was fired
if(event.key.code == sf::Keyboard::Up){
// We check to see if there's actually a node in the desired direction
if(myHero.getLocation()->getLink(u)){
// And if there is we move the hero to that node.
myHero.move(myHero.getLocation()->getLink(u));
}
}
if(event.key.code == sf::Keyboard::Down){
if(myHero.getLocation()->getLink(d)){
myHero.move(myHero.getLocation()->getLink(d));
}
}
if(event.key.code == sf::Keyboard::Left){
if(myHero.getLocation()->getLink(r)){
myHero.move(myHero.getLocation()->getLink(r));
}
}
if(event.key.code == sf::Keyboard::Right){
if(myHero.getLocation()->getLink(l)){
myHero.move(myHero.getLocation()->getLink(l));
}
}
}
if(event.type == sf::Event::KeyPressed){
if(event.key.code == sf::Keyboard::D){
animSprite.nextFrame();
}
}
//Draw draw everything
} //if(window.PollEvents)
// This draws everything on screen. We only draw at our framerate, even though the
// game logic executes much faster than that.
if (myClock.getElapsedTime() > fps){
// Basic call to clear the window before re-drawing
window.clear();
// Draw the objects to our buffering frame
dungeon.draw(window);
spriteSpawn->draw(window);
myHero.draw(window);
animSprite.draw(window);
// Display the items that we've drawn to our buffering frame
window.display();
// Reset the clock to count up to our target framerate again
myClock.restart();
}
}
return 0;
}
*/<commit_msg>:Deleted some old, commented out code<commit_after>#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include "GameApp.h"
int main(){
GameApp villainTycoon;
villainTycoon.run();
return 0;
}<|endoftext|> |
<commit_before>a455f359-2e4f-11e5-8467-28cfe91dbc4b<commit_msg>a45c6966-2e4f-11e5-9305-28cfe91dbc4b<commit_after>a45c6966-2e4f-11e5-9305-28cfe91dbc4b<|endoftext|> |
<commit_before>8431fc1f-2d15-11e5-af21-0401358ea401<commit_msg>8431fc20-2d15-11e5-af21-0401358ea401<commit_after>8431fc20-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>f1e36423-2747-11e6-94fc-e0f84713e7b8<commit_msg>Initial commit.13<commit_after>f2170b07-2747-11e6-9718-e0f84713e7b8<|endoftext|> |
<commit_before>b3328ac0-2747-11e6-a313-e0f84713e7b8<commit_msg>Did a thing<commit_after>b34be4ca-2747-11e6-baa5-e0f84713e7b8<|endoftext|> |
<commit_before>#include "parser.h"
#include "node.h"
#include <fstream>
#include <iostream>
struct Vec3 {
float x, y, z;
friend std::ostream& operator << (std::ostream& out, const Vec3& v) {
out << v.x << " " << v.y << " " << v.z;
return out;
}
};
void operator >> (const YAML::Node& node, Vec3& v)
{
node[0] >> v.x;
node[1] >> v.y;
node[2] >> v.z;
}
struct Room {
std::string name;
Vec3 pos, size;
float height;
friend std::ostream& operator << (std::ostream& out, const Room& room) {
out << "Name: " << room.name << std::endl;
out << "Pos: " << room.pos << std::endl;
out << "Size: " << room.size << std::endl;
out << "Height: " << room.height << std::endl;
return out;
}
};
void operator >> (const YAML::Node& node, Room& room)
{
node["name"] >> room.name;
node["pos"] >> room.pos;
node["size"] >> room.size;
node["height"] >> room.height;
}
struct Level {
std::vector <Room> rooms;
friend std::ostream& operator << (std::ostream& out, const Level& level) {
for(unsigned i=0;i<level.rooms.size();i++) {
out << level.rooms[i];
out << "---------------------------------------\n";
}
return out;
}
};
void operator >> (const YAML::Node& node, Level& level)
{
const YAML::Node& rooms = node["rooms"];
for(unsigned i=0;i<rooms.size();i++) {
Room room;
rooms[i] >> room;
level.rooms.push_back(room);
}
}
int main()
{
std::ifstream fin("test.yaml");
try {
YAML::Parser parser(fin);
if(!parser)
return 0;
YAML::Node doc;
parser.GetNextDocument(doc);
Level level;
doc >> level;
std::cout << level;
} catch(YAML::Exception&) {
std::cout << "Error parsing the yaml!\n";
}
getchar();
return 0;
}<commit_msg><commit_after>#include "parser.h"
#include <fstream>
#include <iostream>
struct Vec3 {
float x, y, z;
friend std::ostream& operator << (std::ostream& out, const Vec3& v) {
out << v.x << " " << v.y << " " << v.z;
return out;
}
};
void operator >> (const YAML::Node& node, Vec3& v)
{
node[0] >> v.x;
node[1] >> v.y;
node[2] >> v.z;
}
struct Room {
std::string name;
Vec3 pos, size;
float height;
friend std::ostream& operator << (std::ostream& out, const Room& room) {
out << "Name: " << room.name << std::endl;
out << "Pos: " << room.pos << std::endl;
out << "Size: " << room.size << std::endl;
out << "Height: " << room.height << std::endl;
return out;
}
};
void operator >> (const YAML::Node& node, Room& room)
{
node["name"] >> room.name;
node["pos"] >> room.pos;
node["size"] >> room.size;
node["height"] >> room.height;
}
struct Level {
std::vector <Room> rooms;
friend std::ostream& operator << (std::ostream& out, const Level& level) {
for(unsigned i=0;i<level.rooms.size();i++) {
out << level.rooms[i];
out << "---------------------------------------\n";
}
return out;
}
};
void operator >> (const YAML::Node& node, Level& level)
{
const YAML::Node& rooms = node["rooms"];
for(unsigned i=0;i<rooms.size();i++) {
Room room;
rooms[i] >> room;
level.rooms.push_back(room);
}
}
int main()
{
std::ifstream fin("test.yaml");
try {
YAML::Parser parser(fin);
if(!parser)
return 0;
YAML::Node doc;
parser.GetNextDocument(doc);
Level level;
doc >> level;
std::cout << level;
} catch(YAML::Exception&) {
std::cout << "Error parsing the yaml!\n";
}
getchar();
return 0;
}<|endoftext|> |
<commit_before>df502161-2747-11e6-8f93-e0f84713e7b8<commit_msg>Does anyone even read these anymore???<commit_after>df597fb3-2747-11e6-8be8-e0f84713e7b8<|endoftext|> |
<commit_before>43d5be38-5216-11e5-8efa-6c40088e03e4<commit_msg>43dd30f8-5216-11e5-8ec3-6c40088e03e4<commit_after>43dd30f8-5216-11e5-8ec3-6c40088e03e4<|endoftext|> |
<commit_before>83f69b3d-2749-11e6-9453-e0f84713e7b8<commit_msg>more bug fix<commit_after>84033b57-2749-11e6-980e-e0f84713e7b8<|endoftext|> |
<commit_before>#include "opencv2/opencv.hpp"
#include <stdio.h> /* defines FILENAME_MAX */
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
using namespace cv;
void clampRectangleToVideoDemensions(Rect &searchFrame,const Size &videoDimensions)
{
if(searchFrame.x <= 0)
searchFrame.x = 0;
if(searchFrame.x >= videoDimensions.width-searchFrame.width)
searchFrame.x = videoDimensions.width-searchFrame.width;
if(searchFrame.y <= 0)
searchFrame.y = 0;
if(searchFrame.y >= videoDimensions.height-searchFrame.height)
searchFrame.y = videoDimensions.height-searchFrame.height;
}
Rect crateOuterFrameFromInnerFrame(const Rect ®ionOfInterest,const Size &videoDimensions, int factor = 2)
{
Rect searchFrame(
regionOfInterest.x-((factor*regionOfInterest.width)/2-regionOfInterest.width/2),
regionOfInterest.y-((factor*regionOfInterest.height)/2-regionOfInterest.height/2),
factor*regionOfInterest.width,
factor*regionOfInterest.height);
clampRectangleToVideoDemensions(searchFrame, videoDimensions);
return searchFrame;
}
void DrawPoint( Mat &img,const Point ¢er,const Scalar &Color)
{
int thickness = -1;
int lineType = 1;
double radius = 0.5;
circle( img,
center,
radius,
Color,
thickness,
lineType );
}
void drawRectangle(const Rect &rectangleToDraw,Mat &matrixToDrawTheRectangleIn,const Scalar &color)
{
line(matrixToDrawTheRectangleIn,
Point(rectangleToDraw.x,rectangleToDraw.y),
Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y),
color,
0,1);
line(matrixToDrawTheRectangleIn,
Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y),
Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y+rectangleToDraw.height),
color,
0,1);
line(matrixToDrawTheRectangleIn,
Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y+rectangleToDraw.height),
Point(rectangleToDraw.x,rectangleToDraw.y+rectangleToDraw.height),
color,
0,1);
line(matrixToDrawTheRectangleIn,
Point(rectangleToDraw.x,rectangleToDraw.y+rectangleToDraw.height),
Point(rectangleToDraw.x,rectangleToDraw.y),
color,
0,1);
}
Point match(const Mat &outerFrameMatrix,const Mat &innerFrameMatrix, Mat &result)
{
int match_method = CV_TM_CCOEFF;
int resultCols = outerFrameMatrix.cols - innerFrameMatrix.cols + 1;
int resultRows = outerFrameMatrix.rows - innerFrameMatrix.rows + 1;
result = Mat(resultCols,resultRows,CV_32FC1);
/// Do the Matching and Normalize
matchTemplate( outerFrameMatrix, innerFrameMatrix, result, match_method );
normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat());
double minVal, maxVal;
Point minLoc, maxLoc, matchLoc;
minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc);
/// For SQDIFF and SQDIFF_NORMED, the best matches are lower values. For all the other methods, the higher the better
if( match_method == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED )
{
matchLoc = minLoc;
rectangle( result, Point( matchLoc.x - result.cols/10 , matchLoc.y - result.rows/10 ), Point( matchLoc.x + result.cols/10 , matchLoc.y + result.rows/10 ), Scalar::all(255), 1, 1, 0 );
}
else
{
matchLoc = maxLoc;
rectangle( result, Point( matchLoc.x - result.cols/10 , matchLoc.y - result.rows/10 ), Point( matchLoc.x + result.cols/10 , matchLoc.y + result.rows/10 ), Scalar::all(0), 1, 1, 0 );
}
//printf("matchLoc: = (%d,%d)",matchLoc.x,matchLoc.y);
//printf("matchLoc: = (%f,%f)",double(SearchFrameMatrix.cols - result.cols)/2.0,double(SearchFrameMatrix.rows-result.rows)/2.0);
Point diff((outerFrameMatrix.cols - result.cols)/2 + 1 ,(outerFrameMatrix.rows-result.rows)/2 + 1);
Point retVal(matchLoc + diff);
return retVal;
}
Point match_2(const Mat &OuterFrameMatrix,const Mat &InnerFrameMatrix, Mat &outResult)
{
int outerX = OuterFrameMatrix.cols;
int outerY = OuterFrameMatrix.rows;
int innerX = InnerFrameMatrix.cols;
int innerY = InnerFrameMatrix.rows;
int resultCols = OuterFrameMatrix.cols - InnerFrameMatrix.cols + 1;
int resultRows = OuterFrameMatrix.rows - InnerFrameMatrix.rows + 1;
float result[resultCols * resultRows];
float minDifference = FLT_MAX;
Point posMinDifferenceInOuterFrame;
for(int leftUpperY = 0; leftUpperY < outerY - innerY; leftUpperY++)
{
for(int leftUpperX = 0; leftUpperX < outerX - innerX; leftUpperX++)
{
float difference = 0;
for(int offsetX = 0; offsetX <= innerX; offsetX++)
{
for(int offsetY = 0; offsetY <= innerY; offsetY++)
{
Point posInOuterFrame = Point(leftUpperX + offsetX, leftUpperY + offsetY);
Point posInInnerFrame = Point(offsetX, offsetY);
difference += OuterFrameMatrix.at<int>(posInOuterFrame) - InnerFrameMatrix.at<int>(posInInnerFrame);
}
}
if(difference < minDifference)
{
minDifference = difference;
// get the mid-Point of the innerFrame in outerFrame-Coordinates
posMinDifferenceInOuterFrame = Point(leftUpperX + innerX/2, leftUpperY + innerY/2);
}
result[leftUpperX + leftUpperY * resultCols] = difference;
}
}
//minDifference, result hold additional information
outResult = Mat(resultCols, resultRows, CV_32FC1, result);
normalize( outResult, outResult, 0, 1, NORM_MINMAX, -1, Mat());
return posMinDifferenceInOuterFrame;
}
void createNewInnerFrameFromMatchLocation(const Point &matchLoc,Rect ®ionOfInterest,const Size &videoDimensions)
{
regionOfInterest = Rect(
matchLoc.x-regionOfInterest.width/2,
matchLoc.y-regionOfInterest.height/2,
regionOfInterest.width,
regionOfInterest.height);
clampRectangleToVideoDemensions(regionOfInterest,videoDimensions);
}
void mouseCallBack(int event, int x, int y, int flags, void* userdata)
{
if ( event == EVENT_LBUTTONDOWN )
{
Rect* innerFrame = (Rect*)userdata;
innerFrame->x = x - innerFrame->width / 2;
innerFrame->y = y - innerFrame->height / 2;
}
}
VideoCapture webcam(const int cameraIndex = 0)
{
printf ("Successfully opened Camera with Index: %d\n",cameraIndex);
return VideoCapture(cameraIndex);
}
VideoCapture videoFile(const std::string &videoFileName)
{
char cCurrentPath[FILENAME_MAX];
if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
{
exit(-1);
}
cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; /* not really required */
VideoCapture videoHandle = VideoCapture(videoFileName); // open the default camera
if(!videoHandle.isOpened()) // check if we succeeded
{
printf ("Could not find File: %s/%s\n", cCurrentPath,videoFileName.c_str());
exit(-1);
}else{
printf ("Successfully loaded File: %s/%s\n", cCurrentPath,videoFileName.c_str());
}
return videoHandle;
}
int main(int, char**)
{
//diable printf() buffering
setbuf(stdout, NULL);
printf("press 'c' to close\n");
bool useWebcam = false;
VideoCapture videoHandle;
if(useWebcam)
{videoHandle = webcam();}
else
{
std::string videoFileName = "videos/video_mitBahn.mp4";
videoHandle = videoFile(videoFileName);
}
Size videoDimensions = Size((int) videoHandle.get(CV_CAP_PROP_FRAME_WIDTH),
(int) videoHandle.get(CV_CAP_PROP_FRAME_HEIGHT));
printf("VideoWidth: %d, VideoHeight: %d\n",videoDimensions.width,videoDimensions.height);
int numberOfVideoFrames;
if(!useWebcam)
{
numberOfVideoFrames = videoHandle.get(CV_CAP_PROP_FRAME_COUNT);
printf("number of Frames: %d\n",numberOfVideoFrames);
}
std::string drawFrameWindowName("drawFrame"),outerFrameWindowName("outerFrame"),matchingWindowName("resultOfMatching");
namedWindow(drawFrameWindowName,CV_WINDOW_AUTOSIZE);
namedWindow(outerFrameWindowName,CV_WINDOW_AUTOSIZE);
namedWindow(matchingWindowName,CV_WINDOW_AUTOSIZE);
// define location of sub matrices in image
Rect innerFrame( videoDimensions.width/2-100, videoDimensions.height/2-50, 16, 16 );
Scalar outerFrame(255,0,0);
Rect searchFrame;
Scalar searchFrameColor(0,255,0);
cv::Point *bestMatchPositionsByFrame;
if(!useWebcam)
{bestMatchPositionsByFrame = new cv::Point[numberOfVideoFrames];}
// Mouse Callback
setMouseCallback(drawFrameWindowName, mouseCallBack, (void*)&innerFrame);
// Mat edges;
double oldMinVal, oldMaxVal;
Point oldMinLoc, oldMaxLoc, oldMatchLocation;
bool stopTheProgramm = false;
for(unsigned int i = 0; useWebcam ? true :i < numberOfVideoFrames; ++i)
{
Mat frame;
// get a new frame from camera
videoHandle >> frame;
// create Matrix we can draw into without overwriting data of the original image
Mat drawFrame;
frame.copyTo(drawFrame);
GaussianBlur(frame,frame,Size(3,3),0,0);
DrawPoint(drawFrame,oldMatchLocation,Scalar(0,255,255));
drawRectangle(innerFrame,drawFrame,outerFrame);
Mat innerFrameMatrix(frame,innerFrame);
searchFrame = crateOuterFrameFromInnerFrame(innerFrame,videoDimensions);
drawRectangle(searchFrame,drawFrame,searchFrameColor);
Mat outerFrameMatrix(frame,searchFrame);
Mat result;
Point matchLocation = match_2(outerFrameMatrix,innerFrameMatrix, result);
// the returned matchLocation is in the wrong Coordinate System, we need to transform it back
matchLocation.x += searchFrame.x;
matchLocation.y += searchFrame.y;
oldMatchLocation = matchLocation;
DrawPoint(drawFrame,matchLocation,Scalar(0,0,255));
//
createNewInnerFrameFromMatchLocation(matchLocation, innerFrame, videoDimensions);
Mat outerFrameZoomed(Point(256,256));
resize(Mat(drawFrame,searchFrame),outerFrameZoomed,Size(256,256));
imshow(outerFrameWindowName,outerFrameZoomed);
Mat resultZoomed(Point(256,256));
resize(result,resultZoomed,Size(256,256));
imshow(matchingWindowName,resultZoomed);
imshow(drawFrameWindowName,drawFrame);
if(!useWebcam)
{
int key = waitKey(0);
switch(key)
{
case ' ':
continue;
break;
case 'c':
stopTheProgramm = true;
break;
}
}else
{
int key = waitKey(1);
switch(key)
{
case 'c':
stopTheProgramm = true;
break;
}
}
if(stopTheProgramm) break;
}
if(!useWebcam)
{delete[] bestMatchPositionsByFrame;}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}
<commit_msg>Gnaarfs killer feature<commit_after>#include "opencv2/opencv.hpp"
#include <stdio.h> /* defines FILENAME_MAX */
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
using namespace cv;
void clampRectangleToVideoDemensions(Rect &searchFrame,const Size &videoDimensions)
{
if(searchFrame.x <= 0)
searchFrame.x = 0;
if(searchFrame.x >= videoDimensions.width-searchFrame.width)
searchFrame.x = videoDimensions.width-searchFrame.width;
if(searchFrame.y <= 0)
searchFrame.y = 0;
if(searchFrame.y >= videoDimensions.height-searchFrame.height)
searchFrame.y = videoDimensions.height-searchFrame.height;
}
Rect crateOuterFrameFromInnerFrame(const Rect ®ionOfInterest,const Size &videoDimensions, int factor = 2)
{
Rect searchFrame(
regionOfInterest.x-((factor*regionOfInterest.width)/2-regionOfInterest.width/2),
regionOfInterest.y-((factor*regionOfInterest.height)/2-regionOfInterest.height/2),
factor*regionOfInterest.width,
factor*regionOfInterest.height);
clampRectangleToVideoDemensions(searchFrame, videoDimensions);
return searchFrame;
}
void DrawPoint( Mat &img,const Point ¢er,const Scalar &Color)
{
int thickness = -1;
int lineType = 1;
double radius = 0.5;
circle( img,
center,
radius,
Color,
thickness,
lineType );
}
void drawRectangle(const Rect &rectangleToDraw,Mat &matrixToDrawTheRectangleIn,const Scalar &color)
{
line(matrixToDrawTheRectangleIn,
Point(rectangleToDraw.x,rectangleToDraw.y),
Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y),
color,
0,1);
line(matrixToDrawTheRectangleIn,
Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y),
Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y+rectangleToDraw.height),
color,
0,1);
line(matrixToDrawTheRectangleIn,
Point(rectangleToDraw.x+rectangleToDraw.width,rectangleToDraw.y+rectangleToDraw.height),
Point(rectangleToDraw.x,rectangleToDraw.y+rectangleToDraw.height),
color,
0,1);
line(matrixToDrawTheRectangleIn,
Point(rectangleToDraw.x,rectangleToDraw.y+rectangleToDraw.height),
Point(rectangleToDraw.x,rectangleToDraw.y),
color,
0,1);
}
Point match(const Mat &outerFrameMatrix,const Mat &innerFrameMatrix, Mat &result)
{
int match_method = CV_TM_CCOEFF;
int resultCols = outerFrameMatrix.cols - innerFrameMatrix.cols + 1;
int resultRows = outerFrameMatrix.rows - innerFrameMatrix.rows + 1;
result = Mat(resultCols,resultRows,CV_32FC1);
/// Do the Matching and Normalize
matchTemplate( outerFrameMatrix, innerFrameMatrix, result, match_method );
normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat());
double minVal, maxVal;
Point minLoc, maxLoc, matchLoc;
minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc);
/// For SQDIFF and SQDIFF_NORMED, the best matches are lower values. For all the other methods, the higher the better
if( match_method == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED )
{
matchLoc = minLoc;
rectangle( result, Point( matchLoc.x - result.cols/10 , matchLoc.y - result.rows/10 ), Point( matchLoc.x + result.cols/10 , matchLoc.y + result.rows/10 ), Scalar::all(255), 1, 1, 0 );
}
else
{
matchLoc = maxLoc;
rectangle( result, Point( matchLoc.x - result.cols/10 , matchLoc.y - result.rows/10 ), Point( matchLoc.x + result.cols/10 , matchLoc.y + result.rows/10 ), Scalar::all(0), 1, 1, 0 );
}
//printf("matchLoc: = (%d,%d)",matchLoc.x,matchLoc.y);
//printf("matchLoc: = (%f,%f)",double(SearchFrameMatrix.cols - result.cols)/2.0,double(SearchFrameMatrix.rows-result.rows)/2.0);
Point diff((outerFrameMatrix.cols - result.cols)/2 + 1 ,(outerFrameMatrix.rows-result.rows)/2 + 1);
Point retVal(matchLoc + diff);
return retVal;
}
Point match_2(const Mat &OuterFrameMatrix,const Mat &InnerFrameMatrix, Mat &outResult)
{
int outerX = OuterFrameMatrix.cols;
int outerY = OuterFrameMatrix.rows;
int innerX = InnerFrameMatrix.cols;
int innerY = InnerFrameMatrix.rows;
int resultCols = OuterFrameMatrix.cols - InnerFrameMatrix.cols + 1;
int resultRows = OuterFrameMatrix.rows - InnerFrameMatrix.rows + 1;
float result[resultCols * resultRows];
float minDifference = FLT_MAX;
Point posMinDifferenceInOuterFrame;
for(int leftUpperY = 0; leftUpperY < outerY - innerY; leftUpperY++)
{
for(int leftUpperX = 0; leftUpperX < outerX - innerX; leftUpperX++)
{
float difference = 0;
for(int offsetX = 0; offsetX <= innerX; offsetX++)
{
for(int offsetY = 0; offsetY <= innerY; offsetY++)
{
Point posInOuterFrame = Point(leftUpperX + offsetX, leftUpperY + offsetY);
Point posInInnerFrame = Point(offsetX, offsetY);
difference += OuterFrameMatrix.at<int>(posInOuterFrame) - InnerFrameMatrix.at<int>(posInInnerFrame);
}
}
if(difference < minDifference)
{
minDifference = difference;
// get the mid-Point of the innerFrame in outerFrame-Coordinates
posMinDifferenceInOuterFrame = Point(leftUpperX + innerX/2, leftUpperY + innerY/2);
}
result[leftUpperX + leftUpperY * resultCols] = difference;
}
}
//minDifference, result hold additional information
outResult = Mat(resultCols, resultRows, CV_32FC1, result);
normalize( outResult, outResult, 0, 1, NORM_MINMAX, -1, Mat());
return posMinDifferenceInOuterFrame;
}
void createNewInnerFrameFromMatchLocation(const Point &matchLoc,Rect ®ionOfInterest,const Size &videoDimensions)
{
regionOfInterest = Rect(
matchLoc.x-regionOfInterest.width/2,
matchLoc.y-regionOfInterest.height/2,
regionOfInterest.width,
regionOfInterest.height);
clampRectangleToVideoDemensions(regionOfInterest,videoDimensions);
}
void mouseCallBack(int event, int x, int y, int flags, void* userdata)
{
if ( event == EVENT_LBUTTONDOWN )
{
Rect* innerFrame = (Rect*)userdata;
innerFrame->x = x - innerFrame->width / 2;
innerFrame->y = y - innerFrame->height / 2;
}
}
VideoCapture webcam(const int cameraIndex = 0)
{
printf ("Successfully opened Camera with Index: %d\n",cameraIndex);
return VideoCapture(cameraIndex);
}
VideoCapture videoFile(const std::string &videoFileName)
{
char cCurrentPath[FILENAME_MAX];
if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
{
exit(-1);
}
cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; /* not really required */
VideoCapture videoHandle = VideoCapture(videoFileName); // open the default camera
if(!videoHandle.isOpened()) // check if we succeeded
{
printf ("Could not find File: %s/%s\n", cCurrentPath,videoFileName.c_str());
exit(-1);
}else{
printf ("Successfully loaded File: %s/%s\n", cCurrentPath,videoFileName.c_str());
}
return videoHandle;
}
int main(int, char**)
{
//diable printf() buffering
setbuf(stdout, NULL);
printf("press 'c' to close\n");
bool useWebcam = false;
VideoCapture videoHandle;
if(useWebcam)
{videoHandle = webcam();}
else
{
std::string videoFileName = "videos/video_mitBahn.mp4";
videoHandle = videoFile(videoFileName);
}
Size videoDimensions = Size((int) videoHandle.get(CV_CAP_PROP_FRAME_WIDTH),
(int) videoHandle.get(CV_CAP_PROP_FRAME_HEIGHT));
printf("VideoWidth: %d, VideoHeight: %d\n",videoDimensions.width,videoDimensions.height);
int numberOfVideoFrames;
if(!useWebcam)
{
numberOfVideoFrames = videoHandle.get(CV_CAP_PROP_FRAME_COUNT);
printf("number of Frames: %d\n",numberOfVideoFrames);
}
std::string drawFrameWindowName("drawFrame"),outerFrameWindowName("outerFrame"),matchingWindowName("resultOfMatching");
namedWindow(drawFrameWindowName,CV_WINDOW_AUTOSIZE);
namedWindow(outerFrameWindowName,CV_WINDOW_AUTOSIZE);
namedWindow(matchingWindowName,CV_WINDOW_AUTOSIZE);
moveWindow(outerFrameWindowName, videoDimensions.width+55, 50);
moveWindow(matchingWindowName, videoDimensions.width+55, 100 + 256);
// define location of sub matrices in image
Rect innerFrame( videoDimensions.width/2-100, videoDimensions.height/2-50, 16, 16 );
Scalar outerFrame(255,0,0);
Rect searchFrame;
Scalar searchFrameColor(0,255,0);
cv::Point *bestMatchPositionsByFrame;
if(!useWebcam)
{bestMatchPositionsByFrame = new cv::Point[numberOfVideoFrames];}
// Mouse Callback
setMouseCallback(drawFrameWindowName, mouseCallBack, (void*)&innerFrame);
// Mat edges;
double oldMinVal, oldMaxVal;
Point oldMinLoc, oldMaxLoc, oldMatchLocation;
bool stopTheProgramm = false;
for(unsigned int i = 0; useWebcam ? true :i < numberOfVideoFrames; ++i)
{
Mat frame;
// get a new frame from camera
videoHandle >> frame;
// create Matrix we can draw into without overwriting data of the original image
Mat drawFrame;
frame.copyTo(drawFrame);
GaussianBlur(frame,frame,Size(3,3),0,0);
DrawPoint(drawFrame,oldMatchLocation,Scalar(0,255,255));
drawRectangle(innerFrame,drawFrame,outerFrame);
Mat innerFrameMatrix(frame,innerFrame);
searchFrame = crateOuterFrameFromInnerFrame(innerFrame,videoDimensions);
drawRectangle(searchFrame,drawFrame,searchFrameColor);
Mat outerFrameMatrix(frame,searchFrame);
Mat result;
Point matchLocation = match_2(outerFrameMatrix,innerFrameMatrix, result);
// the returned matchLocation is in the wrong Coordinate System, we need to transform it back
matchLocation.x += searchFrame.x;
matchLocation.y += searchFrame.y;
oldMatchLocation = matchLocation;
DrawPoint(drawFrame,matchLocation,Scalar(0,0,255));
//
createNewInnerFrameFromMatchLocation(matchLocation, innerFrame, videoDimensions);
Mat outerFrameZoomed(Point(256,256));
resize(Mat(drawFrame,searchFrame),outerFrameZoomed,Size(256,256));
imshow(outerFrameWindowName,outerFrameZoomed);
Mat resultZoomed(Point(256,256));
resize(result,resultZoomed,Size(256,256));
imshow(matchingWindowName,resultZoomed);
imshow(drawFrameWindowName,drawFrame);
if(!useWebcam)
{
int key = waitKey(0);
switch(key)
{
case ' ':
continue;
break;
case 'c':
stopTheProgramm = true;
break;
}
}else
{
int key = waitKey(1);
switch(key)
{
case 'c':
stopTheProgramm = true;
break;
}
}
if(stopTheProgramm) break;
}
if(!useWebcam)
{delete[] bestMatchPositionsByFrame;}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}
<|endoftext|> |
<commit_before>c36be368-35ca-11e5-9a80-6c40088e03e4<commit_msg>c3734706-35ca-11e5-80df-6c40088e03e4<commit_after>c3734706-35ca-11e5-80df-6c40088e03e4<|endoftext|> |
<commit_before>1ce67ef4-585b-11e5-b11b-6c40088e03e4<commit_msg>1ced2790-585b-11e5-8093-6c40088e03e4<commit_after>1ced2790-585b-11e5-8093-6c40088e03e4<|endoftext|> |
<commit_before>690ff134-2fa5-11e5-9889-00012e3d3f12<commit_msg>6911ed06-2fa5-11e5-aa9c-00012e3d3f12<commit_after>6911ed06-2fa5-11e5-aa9c-00012e3d3f12<|endoftext|> |
<commit_before>8e9fac21-2d14-11e5-af21-0401358ea401<commit_msg>8e9fac22-2d14-11e5-af21-0401358ea401<commit_after>8e9fac22-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>8b33260b-2d14-11e5-af21-0401358ea401<commit_msg>8b33260c-2d14-11e5-af21-0401358ea401<commit_after>8b33260c-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>b12e3b78-2d3f-11e5-bd95-c82a142b6f9b<commit_msg>b1ab61ab-2d3f-11e5-9318-c82a142b6f9b<commit_after>b1ab61ab-2d3f-11e5-9318-c82a142b6f9b<|endoftext|> |
<commit_before>// Std. Includes
#include <string>
// GLEW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
// GL includes
#include "Shader.h"
// GLM Mathemtics
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
// Other Libs
#include <SOIL.h>
// Define the max array number
#define MAX_ARRAY_NUMBER 100
// Properties
GLuint screenWidth = 800, screenHeight = 600;
// Function prototypes
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
//void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods);
//void Do_Movement();
// Global variable
// Record the key state
GLint keys[1024];
// Record the current x,y position(the normalized coordinate)
GLfloat xCurPos = 0;
GLfloat yCurPos = 0;
GLint vertexCount = 0;
// Set up our vertex data (and buffer(s)) and attribute pointers
GLfloat vertices[3 * 100] = { 0 };
GLboolean LastVertex = false;
// The MAIN function, from here we start our application and run our Game loop
int main()
{
// Init GLFW
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
glfwWindowHint(GLFW_SAMPLES, 4);
GLFWwindow* window = glfwCreateWindow(screenWidth, screenHeight, "LearnOpenGL", nullptr, nullptr); // Windowed
glfwMakeContextCurrent(window);
// Set the required callback functions
glfwSetKeyCallback(window, key_callback);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetMouseButtonCallback(window, mouse_button_callback);
//glfwSetScrollCallback(window, scroll_callback);
//// Options
//glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
// Initialize GLEW to setup the OpenGL Function pointers
glewExperimental = GL_TRUE;
glewInit();
// Define the viewport dimensions
glViewport(0, 0, screenWidth, screenHeight);
// Setup some OpenGL options
glEnable(GL_DEPTH_TEST);
// Setup and compile our shaders
Shader ourShader("06test.vs", "06test.frag");
GLuint VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
// Bind our Vertex Array Object first, then bind and set our buffers and pointers.
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
// Prepare the buffer to recieve the data
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 3 * MAX_ARRAY_NUMBER, nullptr, GL_STATIC_DRAW);
// Position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
glBindVertexArray(0); // Unbind VAO
glBindBuffer(GL_ARRAY_BUFFER, 0); // Unbind VBO
// Paint loop
while (!glfwWindowShouldClose(window))
{
// Check and call events
glfwPollEvents();
// Clear the colorbuffer
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Activate the shader
ourShader.Use();
/* std::cout<<"while:" << xCurPos << "," << yCurPos << std::endl;
vertices[0] = 0.5f;
vertices[1] = 0.5f;
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(VAO);
glDrawArrays(GL_POINTS, 0, 1);
glBindVertexArray(0);*/
// Update the buffer
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// Paint the first vertex
if (vertexCount == 1)
{
glBindVertexArray(VAO);
glDrawArrays(GL_POINTS, 0, vertexCount);
glBindVertexArray(0);
}
// Paint the uncompleted polygon
if (vertexCount >= 2 && LastVertex == false)
{
//paint
glBindVertexArray(VAO);
glDrawArrays(GL_LINE_STRIP, 0, vertexCount);
glBindVertexArray(0);
}
// Complete the polygon
else if(vertexCount >= 2 && LastVertex == true)
{
//paint
glBindVertexArray(VAO);
glDrawArrays(GL_LINE_LOOP, 0, vertexCount);
glBindVertexArray(0);
}
// Swap the buffers
glfwSwapBuffers(window);
}
// Properly de-allocate all resources once they've outlived their purpose
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glfwTerminate();
return 0;
}
// Is called whenever a key is pressed/released via GLFW
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
//cout << key << endl;
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
if (key >= 0 && key < 1024)
{
if (action == GLFW_PRESS)
keys[key] = true;
else if (action == GLFW_RELEASE)
keys[key] = false;
}
}
//
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
xCurPos = (xpos - 400) /400;
yCurPos = (300 - ypos)/300;
//std::cout << xCurPos << "," << yCurPos << std::endl;
}
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS && LastVertex == false)
{
//std::cout << "Left" << std::endl;
// Record the current vertex position
vertices[vertexCount * 3] = xCurPos;
vertices[vertexCount * 3 + 1] = yCurPos;
vertexCount++;
}
if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS && LastVertex == false)
{
if(vertexCount >= 3) LastVertex = true;
}
}
//
//
//void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
//{
// camera.ProcessMouseScroll(yoffset);
//}<commit_msg>v1.01<commit_after><|endoftext|> |
<commit_before>809e9251-2d15-11e5-af21-0401358ea401<commit_msg>809e9252-2d15-11e5-af21-0401358ea401<commit_after>809e9252-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>#define WIN32_LEAN_AND_MEAN
#define STRICT_GS_ENABLED
#define _ATL_NO_AUTOMATIC_NAMESPACE
#include <windows.h>
#include <pathcch.h>
#include <atlalloc.h>
#include <atlbase.h>
#include <atlconv.h>
#include <fcntl.h>
#include <io.h>
#include <cstdio>
#include <cstdlib>
#include <crtdbg.h>
#include "lxsstat.hpp"
#include "fileopen.hpp"
ATL::CHeapPtr<WCHAR> GetWindowsError(ULONG error_code = GetLastError())
{
ATL::CHeapPtr<WCHAR> msg;
ATLENSURE(msg.Allocate(USHRT_MAX));
ATLENSURE(FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, error_code, 0, msg, USHRT_MAX, nullptr));
return msg;
}
int __cdecl wmain(int argc, wchar_t* argv[])
{
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
_setmode(_fileno(stdout), _O_U8TEXT);
_setmode(_fileno(stderr), _O_U8TEXT);
if (argc <= 1)
{
fputws(L"lxsstat {POSIX_PATH|Windows_PATH} [...]\n", stderr);
return EXIT_FAILURE;
}
for (int i = 1; i < argc; ++i)
{
auto windows_path = Lxss::realpath(argv[i]);
struct Lxss::stat buf;
if (Lxss::stat(windows_path.c_str(), &buf) != 0)
{
ULONG error = GetLastError();
if (error == STATUS_NO_EAS_ON_FILE)
{
fwprintf(stderr, L"%ls\nThis file is not under the control of the Ubuntu on Windows\n", windows_path.c_str());
}
else
{
fwprintf(stderr, L"%ls\n%ls", windows_path.c_str(), (PCWSTR)GetWindowsError(error));
}
}
else
{
wprintf(L" File: '%ls'", argv[i]);
if (Lxss::S_ISLNK(buf.st_mode))
{
if (buf.st_size <= PATHCCH_MAX_CCH)
{
ATL::CTempBuffer<CHAR> buffer(buf.st_size + 1);
ULONG read_size;
ATL::CHandle h(OpenFileCaseSensitive(windows_path.c_str()));
if (h && ReadFile(h, buffer, (ULONG)buf.st_size + 1, &read_size, nullptr))
{
if (read_size == buf.st_size)
{
buffer[read_size] = '\0';
ATL::CA2W path(buffer, CP_UTF8);
wprintf(L" -> '%.*ls'\n", (int)wcslen(path), (PCWSTR)path);
}
else
{
wprintf(L" -> ?\?\?\?\?\?\?\?");
}
}
else
{
wprintf(L" -> ?\?\?\?\?\?\?\?\n%ls", (PCWSTR)GetWindowsError());
}
}
else
{
_putws(L" -> symlink too long");
}
}
else
{
_putws(L"");
}
wprintf(
L" Size: %-15llu Blocks: %-10llu IO Block: %-6u ",
buf.st_size,
buf.st_blocks,
buf.st_blksize
);
if (Lxss::S_ISLNK(buf.st_mode))
{
_putws(L"symbolic link");
}
else if (Lxss::S_ISDIR(buf.st_mode))
{
_putws(L"directory");
}
else if (Lxss::S_ISREG(buf.st_mode))
{
if (buf.st_size)
{
_putws(L"regular file");
}
else
{
_putws(L"regular empty file");
}
}
else if (Lxss::S_ISCHR(buf.st_mode))
{
_putws(L"character special file");
}
else if (Lxss::S_ISFIFO(buf.st_mode))
{
_putws(L"fifo");
}
else
{
_putws(L"unknown");
}
wprintf(
!Lxss::S_ISCHR(buf.st_mode)
? L"Device: %xh/%ud Inode: %llu Links: %u\n"
: L"Device: %xh/%ud Inode: %llu Links: %-5u Device type: %x,%x\n",
buf.st_dev,
buf.st_dev,
buf.st_ino,
buf.st_nlink,
HIBYTE(buf.st_rdev),
LOBYTE(buf.st_rdev)
);
wprintf(
L"Access: (%04o/%hs) Uid: (% 5u/% 8hs) Gid: (% 5u/% 8hs)\n",
buf.st_mode & 07777,
Lxss::mode_tostring(buf.st_mode).data(),
buf.st_uid,
Lxss::UserNameFromUID(buf.st_uid),
buf.st_gid,
Lxss::GroupNameFromGID(buf.st_gid)
);
const struct _timespec64(&mactime)[3] = { buf.st_atim, buf.st_mtim ,buf.st_ctim };
const PCSTR mactime_string[] = { "Access", "Modify", "Change" };
for (int j = 0; j < _countof(mactime); ++j)
{
char str[80];
strftime(
str,
sizeof str,
"%F %T",
__pragma(warning(suppress:4996)) gmtime(&mactime[j].tv_sec)
);
wprintf(L"%hs: %hs.%09lu +0000\n", mactime_string[j], str, mactime[j].tv_nsec);
}
}
}
}<commit_msg>fix not include null terminator<commit_after>#define WIN32_LEAN_AND_MEAN
#define STRICT_GS_ENABLED
#define _ATL_NO_AUTOMATIC_NAMESPACE
#include <windows.h>
#include <pathcch.h>
#include <atlalloc.h>
#include <atlbase.h>
#include <atlconv.h>
#include <fcntl.h>
#include <io.h>
#include <cstdio>
#include <cstdlib>
#include <crtdbg.h>
#include "lxsstat.hpp"
#include "fileopen.hpp"
ATL::CHeapPtr<WCHAR> GetWindowsError(ULONG error_code = GetLastError())
{
ATL::CHeapPtr<WCHAR> msg;
ATLENSURE(msg.Allocate(USHRT_MAX));
ATLENSURE(FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, error_code, 0, msg, USHRT_MAX, nullptr));
return msg;
}
int __cdecl wmain(int argc, wchar_t* argv[])
{
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
_setmode(_fileno(stdout), _O_U8TEXT);
_setmode(_fileno(stderr), _O_U8TEXT);
if (argc <= 1)
{
fputws(L"lxsstat {POSIX_PATH|Windows_PATH} [...]\n", stderr);
return EXIT_FAILURE;
}
for (int i = 1; i < argc; ++i)
{
auto windows_path = Lxss::realpath(argv[i]);
struct Lxss::stat buf;
if (Lxss::stat(windows_path.c_str(), &buf) != 0)
{
ULONG error = GetLastError();
if (error == STATUS_NO_EAS_ON_FILE)
{
fwprintf(stderr, L"%ls\nThis file is not under the control of the Ubuntu on Windows\n", windows_path.c_str());
}
else
{
fwprintf(stderr, L"%ls\n%ls", windows_path.c_str(), (PCWSTR)GetWindowsError(error));
}
}
else
{
wprintf(L" File: '%ls'", argv[i]);
if (Lxss::S_ISLNK(buf.st_mode))
{
if (buf.st_size < PATHCCH_MAX_CCH)
{
ATL::CTempBuffer<CHAR> buffer(buf.st_size + 1);
ULONG read_size;
ATL::CHandle h(OpenFileCaseSensitive(windows_path.c_str()));
if (h && ReadFile(h, buffer, (ULONG)buf.st_size + 1, &read_size, nullptr))
{
if (read_size == buf.st_size)
{
buffer[read_size] = '\0';
ATL::CA2W path(buffer, CP_UTF8);
wprintf(L" -> '%.*ls'\n", (int)wcslen(path), (PCWSTR)path);
}
else
{
wprintf(L" -> ?\?\?\?\?\?\?\?");
}
}
else
{
wprintf(L" -> ?\?\?\?\?\?\?\?\n%ls", (PCWSTR)GetWindowsError());
}
}
else
{
_putws(L" -> symlink too long");
}
}
else
{
_putws(L"");
}
wprintf(
L" Size: %-15llu Blocks: %-10llu IO Block: %-6u ",
buf.st_size,
buf.st_blocks,
buf.st_blksize
);
if (Lxss::S_ISLNK(buf.st_mode))
{
_putws(L"symbolic link");
}
else if (Lxss::S_ISDIR(buf.st_mode))
{
_putws(L"directory");
}
else if (Lxss::S_ISREG(buf.st_mode))
{
if (buf.st_size)
{
_putws(L"regular file");
}
else
{
_putws(L"regular empty file");
}
}
else if (Lxss::S_ISCHR(buf.st_mode))
{
_putws(L"character special file");
}
else if (Lxss::S_ISFIFO(buf.st_mode))
{
_putws(L"fifo");
}
else
{
_putws(L"unknown");
}
wprintf(
!Lxss::S_ISCHR(buf.st_mode)
? L"Device: %xh/%ud Inode: %llu Links: %u\n"
: L"Device: %xh/%ud Inode: %llu Links: %-5u Device type: %x,%x\n",
buf.st_dev,
buf.st_dev,
buf.st_ino,
buf.st_nlink,
HIBYTE(buf.st_rdev),
LOBYTE(buf.st_rdev)
);
wprintf(
L"Access: (%04o/%hs) Uid: (% 5u/% 8hs) Gid: (% 5u/% 8hs)\n",
buf.st_mode & 07777,
Lxss::mode_tostring(buf.st_mode).data(),
buf.st_uid,
Lxss::UserNameFromUID(buf.st_uid),
buf.st_gid,
Lxss::GroupNameFromGID(buf.st_gid)
);
const struct _timespec64(&mactime)[3] = { buf.st_atim, buf.st_mtim ,buf.st_ctim };
const PCSTR mactime_string[] = { "Access", "Modify", "Change" };
for (int j = 0; j < _countof(mactime); ++j)
{
char str[80];
strftime(
str,
sizeof str,
"%F %T",
__pragma(warning(suppress:4996)) gmtime(&mactime[j].tv_sec)
);
wprintf(L"%hs: %hs.%09lu +0000\n", mactime_string[j], str, mactime[j].tv_nsec);
}
}
}
}<|endoftext|> |
<commit_before>796f9420-2d53-11e5-baeb-247703a38240<commit_msg>79701206-2d53-11e5-baeb-247703a38240<commit_after>79701206-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>9ea7aff0-35ca-11e5-92b2-6c40088e03e4<commit_msg>9eae3988-35ca-11e5-a97c-6c40088e03e4<commit_after>9eae3988-35ca-11e5-a97c-6c40088e03e4<|endoftext|> |
<commit_before>21473d6c-585b-11e5-92ab-6c40088e03e4<commit_msg>214e805c-585b-11e5-8421-6c40088e03e4<commit_after>214e805c-585b-11e5-8421-6c40088e03e4<|endoftext|> |
<commit_before>e3f82fba-ad5c-11e7-8fe2-ac87a332f658<commit_msg>Too poor for Dropbox<commit_after>e4552b51-ad5c-11e7-8804-ac87a332f658<|endoftext|> |
<commit_before>bb172d82-2e4f-11e5-9e6e-28cfe91dbc4b<commit_msg>bb1e3be8-2e4f-11e5-be87-28cfe91dbc4b<commit_after>bb1e3be8-2e4f-11e5-be87-28cfe91dbc4b<|endoftext|> |
<commit_before>77a7160e-2d53-11e5-baeb-247703a38240<commit_msg>77a795fc-2d53-11e5-baeb-247703a38240<commit_after>77a795fc-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>1b5028a6-2748-11e6-915b-e0f84713e7b8<commit_msg>this is my first commit?<commit_after>1b5b78a1-2748-11e6-ae60-e0f84713e7b8<|endoftext|> |
<commit_before>0e4a53d8-2f67-11e5-a1d3-6c40088e03e4<commit_msg>0e50ecc8-2f67-11e5-a90e-6c40088e03e4<commit_after>0e50ecc8-2f67-11e5-a90e-6c40088e03e4<|endoftext|> |
<commit_before>5113dcfa-2e4f-11e5-9722-28cfe91dbc4b<commit_msg>511a9eb3-2e4f-11e5-8d28-28cfe91dbc4b<commit_after>511a9eb3-2e4f-11e5-8d28-28cfe91dbc4b<|endoftext|> |
<commit_before>5bf673e5-2d16-11e5-af21-0401358ea401<commit_msg>5bf673e6-2d16-11e5-af21-0401358ea401<commit_after>5bf673e6-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>e1342f11-2d3d-11e5-9355-c82a142b6f9b<commit_msg>e19d26d4-2d3d-11e5-a356-c82a142b6f9b<commit_after>e19d26d4-2d3d-11e5-a356-c82a142b6f9b<|endoftext|> |
<commit_before>94da1270-4b02-11e5-860f-28cfe9171a43<commit_msg>NO CHANGES<commit_after>94e68835-4b02-11e5-905e-28cfe9171a43<|endoftext|> |
<commit_before>74d3b668-2e4f-11e5-8543-28cfe91dbc4b<commit_msg>74da3814-2e4f-11e5-b58a-28cfe91dbc4b<commit_after>74da3814-2e4f-11e5-b58a-28cfe91dbc4b<|endoftext|> |
<commit_before>78e4252e-5216-11e5-b23c-6c40088e03e4<commit_msg>78eacb1a-5216-11e5-b28d-6c40088e03e4<commit_after>78eacb1a-5216-11e5-b28d-6c40088e03e4<|endoftext|> |
<commit_before>44557230-2e4f-11e5-9155-28cfe91dbc4b<commit_msg>4461b70c-2e4f-11e5-933d-28cfe91dbc4b<commit_after>4461b70c-2e4f-11e5-933d-28cfe91dbc4b<|endoftext|> |
<commit_before>57a141f8-2e3a-11e5-bd50-c03896053bdd<commit_msg>57af271e-2e3a-11e5-b227-c03896053bdd<commit_after>57af271e-2e3a-11e5-b227-c03896053bdd<|endoftext|> |
<commit_before>c96800ee-327f-11e5-bec6-9cf387a8033e<commit_msg>c96dfad1-327f-11e5-b4a5-9cf387a8033e<commit_after>c96dfad1-327f-11e5-b4a5-9cf387a8033e<|endoftext|> |
<commit_before>d6150ba3-2d3c-11e5-a4d7-c82a142b6f9b<commit_msg>d66931b5-2d3c-11e5-a229-c82a142b6f9b<commit_after>d66931b5-2d3c-11e5-a229-c82a142b6f9b<|endoftext|> |
<commit_before>809e9211-2d15-11e5-af21-0401358ea401<commit_msg>809e9212-2d15-11e5-af21-0401358ea401<commit_after>809e9212-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>748fe623-2e4f-11e5-af7d-28cfe91dbc4b<commit_msg>7496ef14-2e4f-11e5-8f08-28cfe91dbc4b<commit_after>7496ef14-2e4f-11e5-8f08-28cfe91dbc4b<|endoftext|> |
<commit_before>3be16146-2e3a-11e5-9bf8-c03896053bdd<commit_msg>3bee34de-2e3a-11e5-8e35-c03896053bdd<commit_after>3bee34de-2e3a-11e5-8e35-c03896053bdd<|endoftext|> |
<commit_before>9b844ae1-2e4f-11e5-8390-28cfe91dbc4b<commit_msg>9b8aff8f-2e4f-11e5-8fd7-28cfe91dbc4b<commit_after>9b8aff8f-2e4f-11e5-8fd7-28cfe91dbc4b<|endoftext|> |
<commit_before>#include <QtGui/QGuiApplication>
#include <QQuickItem>
#include <QDebug>
#include <QQmlContext>
#include <QSortFilterProxyModel>
#include "qtquick2applicationviewer.h"
#include "resource.h"
void populateResourceList(ListModel * model, QFile & resourceSaveFile);
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QtQuick2ApplicationViewer viewer;
// Get the file name
QFile resourceSaveFile("C:\\Users\\jmbeck\\Desktop\\Timber and Stone pld1\\saves\\Test\\re.sav");
// Create a model that holds our resource data, and
// add the data to it.
ListModel * resourceModel = new ListModel(new Resource, qApp);
populateResourceList(resourceModel, resourceSaveFile);
// Create the proxy model that contains the results of the filter.
QSortFilterProxyModel * proxyResourceModel = new QSortFilterProxyModel();
proxyResourceModel->setSourceModel(resourceModel);
proxyResourceModel->setFilterRole(Resource::FilterStringRole);
// Enable the case insensitivity
proxyResourceModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
// Setup sorting the resources
//proxyResourceModel->setSortRole(Resource::TypeRole);
//proxyResourceModel->sort(0);
// Link the resource data to the GUI viewer
viewer.rootContext()->setContextProperty("resourceModel", proxyResourceModel);
Resource * testResource = new Resource("Test Resource", "mytype", "icon.jpg", 0, 0);
viewer.rootContext()->setContextProperty("testResource", testResource);
viewer.setMainQmlFile(QStringLiteral("qml/AxeAndPick/main.qml"));
// Show the GUI
viewer.showExpanded();
return app.exec();
}
void populateResourceList(ListModel * model, QFile & resourceSaveFile)
{
// Mask for the quantity bytes
const unsigned char MASK = 0x3F;
// Pull the save file data in.
if (resourceSaveFile.open(QIODevice::ReadWrite))
{
qDebug() << "Opened Save File: " << resourceSaveFile.fileName();
}
// Pull in the list of resource assets (name, group, etc)
QFile assetFile(QCoreApplication::applicationDirPath() + "/resource_list.txt");
if (assetFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << "Opened Asset File: " << assetFile.fileName();
QTextStream assetStream(&assetFile);
while (!resourceSaveFile.atEnd())
//for( int i=0; i<3; i++ )
{
// Grab the next section and decide the size, etc.
QString resourceString;
if (!assetStream.atEnd())
{
resourceString = assetStream.readLine();
}
else
{
resourceString = "unexpected data,unknown,resource-unknown.svg";
}
QStringList assetData;
assetData = resourceString.split(',');
// Temporary array to hold the bytes we read from the file.
quint8 byteArray[4];
char sigByte; // Most Significant Byte
resourceSaveFile.read(&sigByte, 1);
if( (unsigned char)sigByte >= 224)
{
// Pull in the middle byte, because they must be processed together.
char middleByte;
resourceSaveFile.read(&middleByte, 1);
byteArray[1] = ((middleByte&MASK) | ((sigByte&MASK) << 6)) - 2;
}
else
{
byteArray[1] = sigByte - 0xC2;
}
char leastByte;
resourceSaveFile.read(&leastByte, 1);
byteArray[0] = leastByte - 0x80;
// Build the quantity out of the read bytes.
quint32 resourceQuantity;
resourceQuantity = byteArray[0] & MASK;
resourceQuantity |= byteArray[1] << 6;
// Create a new Resource with the quantity, and use the
// data from the ResourceAssetList to flush it out.
model->appendRow(new Resource(assetData[0],
assetData[1],
assetData[2],
resourceQuantity,
0));
}
}
else
{
qDebug() << "Could not open " << assetFile.fileName();
}
// Pull in the file that contains the saved-game resources
}
<commit_msg>Fixed reading resource quantity when very large<commit_after>#include <QtGui/QGuiApplication>
#include <QQuickItem>
#include <QDebug>
#include <QQmlContext>
#include <QSortFilterProxyModel>
#include "qtquick2applicationviewer.h"
#include "resource.h"
void populateResourceList(ListModel * model, QFile & resourceSaveFile);
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QtQuick2ApplicationViewer viewer;
// Get the file name
QFile resourceSaveFile("C:\\Users\\jmbeck\\Desktop\\Timber and Stone pld1\\saves\\Test\\re.sav");
// Create a model that holds our resource data, and
// add the data to it.
ListModel * resourceModel = new ListModel(new Resource, qApp);
populateResourceList(resourceModel, resourceSaveFile);
// Create the proxy model that contains the results of the filter.
QSortFilterProxyModel * proxyResourceModel = new QSortFilterProxyModel();
proxyResourceModel->setSourceModel(resourceModel);
proxyResourceModel->setFilterRole(Resource::FilterStringRole);
// Enable the case insensitivity
proxyResourceModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
// Setup sorting the resources
//proxyResourceModel->setSortRole(Resource::TypeRole);
//proxyResourceModel->sort(0);
// Link the resource data to the GUI viewer
viewer.rootContext()->setContextProperty("resourceModel", proxyResourceModel);
Resource * testResource = new Resource("Test Resource", "mytype", "icon.jpg", 0, 0);
viewer.rootContext()->setContextProperty("testResource", testResource);
viewer.setMainQmlFile(QStringLiteral("qml/AxeAndPick/main.qml"));
// Show the GUI
viewer.showExpanded();
return app.exec();
}
void populateResourceList(ListModel * model, QFile & resourceSaveFile)
{
// Mask for the quantity bytes
const unsigned char MASK = 0x3F;
// Pull the save file data in.
if (resourceSaveFile.open(QIODevice::ReadWrite))
{
qDebug() << "Opened Save File: " << resourceSaveFile.fileName();
}
// Pull in the list of resource assets (name, group, etc)
QFile assetFile(QCoreApplication::applicationDirPath() + "/resource_list.txt");
if (assetFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << "Opened Asset File: " << assetFile.fileName();
QTextStream assetStream(&assetFile);
while (!resourceSaveFile.atEnd())
//for( int i=0; i<3; i++ )
{
// Grab the next section and decide the size, etc.
QString resourceString;
if (!assetStream.atEnd())
{
resourceString = assetStream.readLine();
}
else
{
resourceString = "unexpected data,unknown,resource-unknown.svg";
}
QStringList assetData;
assetData = resourceString.split(',');
// Temporary array to hold the bytes we read from the file.
quint8 byteArray[4];
char sigByte; // Most Significant Byte
resourceSaveFile.read(&sigByte, 1);
if( (unsigned char)sigByte >= 0xE0)
{
byteArray[2] = (sigByte - 0xE0);
// Pull in the middle byte, because they must be processed together.
char middleByte;
resourceSaveFile.read(&middleByte, 1);
byteArray[1] = (middleByte & MASK);
}
else
{
byteArray[2] = 0;
byteArray[1] = sigByte - 0xC0;
}
char leastByte;
resourceSaveFile.read(&leastByte, 1);
byteArray[0] = leastByte & MASK;
// Build the quantity out of the read bytes.
quint32 resourceQuantity;
resourceQuantity = byteArray[0];
resourceQuantity |= ((byteArray[1] | (byteArray[2]<<6)) -2) << 6;
// Create a new Resource with the quantity, and use the
// data from the ResourceAssetList to flush it out.
model->appendRow(new Resource(assetData[0],
assetData[1],
assetData[2],
resourceQuantity,
0));
}
}
else
{
qDebug() << "Could not open " << assetFile.fileName();
}
// Pull in the file that contains the saved-game resources
}
<|endoftext|> |
<commit_before>d611ff8a-2747-11e6-893c-e0f84713e7b8<commit_msg>my cat is cute<commit_after>d61c2580-2747-11e6-9104-e0f84713e7b8<|endoftext|> |
<commit_before>c7dea5fe-35ca-11e5-b5f5-6c40088e03e4<commit_msg>c7e55188-35ca-11e5-8d2b-6c40088e03e4<commit_after>c7e55188-35ca-11e5-8d2b-6c40088e03e4<|endoftext|> |
<commit_before>a2376568-2747-11e6-8657-e0f84713e7b8<commit_msg>fixed bug<commit_after>a243bde3-2747-11e6-9e1c-e0f84713e7b8<|endoftext|> |
<commit_before>83000e4d-2d15-11e5-af21-0401358ea401<commit_msg>83000e4e-2d15-11e5-af21-0401358ea401<commit_after>83000e4e-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>7e79197a-2d15-11e5-af21-0401358ea401<commit_msg>7e79197b-2d15-11e5-af21-0401358ea401<commit_after>7e79197b-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>5eff3e1c-5216-11e5-aad0-6c40088e03e4<commit_msg>5f0612f0-5216-11e5-acec-6c40088e03e4<commit_after>5f0612f0-5216-11e5-acec-6c40088e03e4<|endoftext|> |
<commit_before>e5338940-313a-11e5-831c-3c15c2e10482<commit_msg>e539bb00-313a-11e5-8f3a-3c15c2e10482<commit_after>e539bb00-313a-11e5-8f3a-3c15c2e10482<|endoftext|> |
<commit_before>8d6dfd20-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfd21-2d14-11e5-af21-0401358ea401<commit_after>8d6dfd21-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>9101adb5-2d14-11e5-af21-0401358ea401<commit_msg>9101adb6-2d14-11e5-af21-0401358ea401<commit_after>9101adb6-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>5bf67418-2d16-11e5-af21-0401358ea401<commit_msg>5bf67419-2d16-11e5-af21-0401358ea401<commit_after>5bf67419-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>2c1f78b4-2f67-11e5-bbd4-6c40088e03e4<commit_msg>2c262b3a-2f67-11e5-aa9f-6c40088e03e4<commit_after>2c262b3a-2f67-11e5-aa9f-6c40088e03e4<|endoftext|> |
<commit_before>bc0647d2-35ca-11e5-9936-6c40088e03e4<commit_msg>bc0ffb1a-35ca-11e5-bc10-6c40088e03e4<commit_after>bc0ffb1a-35ca-11e5-bc10-6c40088e03e4<|endoftext|> |
<commit_before>95b4b602-2e4f-11e5-8e49-28cfe91dbc4b<commit_msg>95bbd0e1-2e4f-11e5-86df-28cfe91dbc4b<commit_after>95bbd0e1-2e4f-11e5-86df-28cfe91dbc4b<|endoftext|> |
<commit_before>88c3a570-2d3e-11e5-a416-c82a142b6f9b<commit_msg>892f3785-2d3e-11e5-9059-c82a142b6f9b<commit_after>892f3785-2d3e-11e5-9059-c82a142b6f9b<|endoftext|> |
<commit_before>7616e184-2d53-11e5-baeb-247703a38240<commit_msg>76176096-2d53-11e5-baeb-247703a38240<commit_after>76176096-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>f44f7a75-327f-11e5-b07c-9cf387a8033e<commit_msg>f455f1a6-327f-11e5-a966-9cf387a8033e<commit_after>f455f1a6-327f-11e5-a966-9cf387a8033e<|endoftext|> |
<commit_before>2859b488-2f67-11e5-901c-6c40088e03e4<commit_msg>28609a3a-2f67-11e5-88cf-6c40088e03e4<commit_after>28609a3a-2f67-11e5-88cf-6c40088e03e4<|endoftext|> |
<commit_before>5a90ef30-5216-11e5-ac1f-6c40088e03e4<commit_msg>5a98bb22-5216-11e5-ba22-6c40088e03e4<commit_after>5a98bb22-5216-11e5-ba22-6c40088e03e4<|endoftext|> |
<commit_before>4529bb61-2e4f-11e5-92cd-28cfe91dbc4b<commit_msg>4530c175-2e4f-11e5-9fef-28cfe91dbc4b<commit_after>4530c175-2e4f-11e5-9fef-28cfe91dbc4b<|endoftext|> |
<commit_before>77ef0694-2d53-11e5-baeb-247703a38240<commit_msg>77ef86aa-2d53-11e5-baeb-247703a38240<commit_after>77ef86aa-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>11692e8a-585b-11e5-a1a6-6c40088e03e4<commit_msg>11701464-585b-11e5-b01d-6c40088e03e4<commit_after>11701464-585b-11e5-b01d-6c40088e03e4<|endoftext|> |
<commit_before>7e79193c-2d15-11e5-af21-0401358ea401<commit_msg>7e79193d-2d15-11e5-af21-0401358ea401<commit_after>7e79193d-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>d7ef45de-35ca-11e5-9cd9-6c40088e03e4<commit_msg>d7f696f6-35ca-11e5-8e0c-6c40088e03e4<commit_after>d7f696f6-35ca-11e5-8e0c-6c40088e03e4<|endoftext|> |
<commit_before>411eba46-5216-11e5-9ac5-6c40088e03e4<commit_msg>4125f200-5216-11e5-881a-6c40088e03e4<commit_after>4125f200-5216-11e5-881a-6c40088e03e4<|endoftext|> |
<commit_before>a4af1514-2e4f-11e5-82cc-28cfe91dbc4b<commit_msg>a4b5e50f-2e4f-11e5-a26d-28cfe91dbc4b<commit_after>a4b5e50f-2e4f-11e5-a26d-28cfe91dbc4b<|endoftext|> |
<commit_before>1f19fc98-2f67-11e5-9133-6c40088e03e4<commit_msg>1f207168-2f67-11e5-9549-6c40088e03e4<commit_after>1f207168-2f67-11e5-9549-6c40088e03e4<|endoftext|> |
<commit_before>86936f5b-2d15-11e5-af21-0401358ea401<commit_msg>86936f5c-2d15-11e5-af21-0401358ea401<commit_after>86936f5c-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>/*
* main.cpp
*
* Created on: Oct 13, 2017
* Author: austinhoffmann
*/
#include <iostream>
#include <unordered_map>
#include "./rapidXML/rapidxml_utils.hpp"
#include "./rapidXML/rapidxml.hpp"
#include "Object.h"
#include "Room.h"
#include "Container.hpp"
#include <sstream>
#include <iterator>
#include "helper.hpp"
int main(int argc, char* argv[]) {
if(argc != 2) {
std::cout << "Zork usage: ./Zork [filename]" << std::endl;
return 0;
}
//create a c-string that will be parsed by rapidxml using the input file
rapidxml::file<>ifile(argv[1]);
//create a DOM model of the input file that is parsed
rapidxml::xml_document<> doc;
doc.parse<0>(ifile.data());
//create an unordered map to store all of our objects
std::unordered_map<std::string, Object*> objectMap;
//Map node is the first child of the XML overall tree
rapidxml::xml_node<>* mapNode = doc.first_node("map");
//Room creation
rapidxml::xml_node<>* node = mapNode->first_node("room");
if(node == nullptr) {
std::cout << "Could not find a valid room with the XML parser" <<std::endl;
return 0;
}
//keep creating rooms while we have new ones
while(node) {
//create Room
Room* room = new Room(node);
//Add room to unordered map
objectMap.insert(std::make_pair(room->get_name(), room));
//Get next room node
node = node->next_sibling("room");
}
//End Room Creation
//Container creation
node = mapNode->first_node("container");
while(node) {
Container* container = new Container(node);
objectMap.insert(std::make_pair(container->get_name(), container));
node = node->next_sibling("container");
}
//End Container creation
//Item creation
node = mapNode->first_node("item");
while(node) {
Item* item = new Item(node);
objectMap.insert(std::make_pair(item->get_name(), item));
node = node->next_sibling("item");
}
//End item Creation
//Create the player's inventory
auto inventory = Container();
//END OF SETUP
//START OF GAMEPLAY
//Find the Entrance to start the game
auto search = objectMap.find("Entrance");
auto currentRoom = dynamic_cast<Room*>(search->second);
std::cout << currentRoom->get_description() << std::endl;
//Start game
bool exit_condition = false;
while(exit_condition == false) {
//Get user input
std::string input;
std::getline(std::cin, input);
//n, s, e, w
if(input == "n" || input == "s" || input == "e" || input == "w") {
currentRoom = currentRoom->movement(input, objectMap);
}
//open exit
else if(input == "open exit") {
exit_condition = currentRoom->exit_check();
}
//i
else if(input == "i") {
inventory.open_container();
}
//open (container)
else if(input.substr(0,4) == "open" && input.size() > 5) {
std::string containerName = input.substr(5);
bool found = currentRoom->find_container(containerName);
if(found) {
auto containerSearch = objectMap.find(containerName);
auto container = dynamic_cast<Container*>(containerSearch->second);
container->open_container();
}
else {
std::cout << "Error: that container is not in this room" << std::endl;
}
}
//put (item) in (container)
else if(input.substr(0,3) == "put" && input.size() > 3) {
std::istringstream iss{input};
std::vector<std::string> tokens{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};
if(tokens.size() == 4) {
bool found = inventory.find_item(tokens[1]);
if(found) {
bool containerFound = currentRoom->find_container(tokens[3]);
if(containerFound) {
auto containerSearch = objectMap.find(tokens[3]);
auto container = dynamic_cast<Container*>(containerSearch->second);
container->add_item(tokens[1]);
inventory.remove_item(tokens[1]);
std::cout << "Item " << tokens[1] << " added to " << tokens[3] << std::endl;
}
else {
std::cout << "Error: that container is not in this room" << std::endl;
}
}
else {
std::cout << "Error: you dont have " << tokens[1] << " in your inventory" << std::endl;
}
}
else {
std::cout << "Invalid command" << std::endl;
}
}
//take (item)
else if(input.substr(0,4) == "take" && input.size() > 4) {
std::string itemName = input.substr(5);
bool found = currentRoom->find_item(itemName, objectMap);
if(found) {
inventory.add_item(itemName);
currentRoom->remove_item(itemName, objectMap);
std::cout << "Item " << itemName << " added to inventory" << std::endl;
}
else {
std::cout << "Error: that item is not in the current room" << std::endl;
}
}
//drop (item)
else if(input.substr(0,4) == "drop" && input.size() > 5) {
std::string itemName = input.substr(5);
bool found = inventory.find_item(itemName);
if(found) {
inventory.remove_item(itemName);
currentRoom->add_item(itemName);
std::cout << itemName << " dropped" << std::endl;
}
else {
std::cout << "Error: you do not have " << itemName << " in your inventory" << std::endl;
}
}
//read (item)
else if(input.substr(0,4) == "read" && input.size() > 5) {
std::string itemName = input.substr(5);
bool found = inventory.find_item(itemName);
if(found) {
auto search = objectMap.find(itemName);
auto item = dynamic_cast<Item*>(search->second);
item->read_writing();
}
else {
std::cout << "Error: you do not have " << itemName << " in your inventory" << std::endl;
}
}
//turn on (item)
else if(input.substr(0,4) == "turn" && input.size() > 7) {
std::istringstream iss{input};
std::vector<std::string> tokens{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};
std::string itemName = tokens[2];
bool found = inventory.find_item(itemName);
if(found) {
Item* item = dynamic_cast<Item*>(objectMap[itemName]);
//Get the vector of actions to perform
auto actions = item->turn_on();
//TODO implement behind the scenes actions
for(auto action : actions) {
parse_commands(action, objectMap);
}
}
}
else {
std::cout << "Invalid Command" << std::endl;
}
}
return 0;
}
<commit_msg>Refactor input parsing to increase safety and ease of use<commit_after>/*
* main.cpp
*
* Created on: Oct 13, 2017
* Author: austinhoffmann
*/
#include <iostream>
#include <unordered_map>
#include "./rapidXML/rapidxml_utils.hpp"
#include "./rapidXML/rapidxml.hpp"
#include "Object.h"
#include "Room.h"
#include "Container.hpp"
#include <sstream>
#include <iterator>
#include "helper.hpp"
int main(int argc, char* argv[]) {
if(argc != 2) {
std::cout << "Zork usage: ./Zork [filename]" << std::endl;
return 0;
}
//create a c-string that will be parsed by rapidxml using the input file
rapidxml::file<>ifile(argv[1]);
//create a DOM model of the input file that is parsed
rapidxml::xml_document<> doc;
doc.parse<0>(ifile.data());
//create an unordered map to store all of our objects
std::unordered_map<std::string, Object*> objectMap;
//Map node is the first child of the XML overall tree
rapidxml::xml_node<>* mapNode = doc.first_node("map");
//Room creation
rapidxml::xml_node<>* node = mapNode->first_node("room");
if(node == nullptr) {
std::cout << "Could not find a valid room with the XML parser" <<std::endl;
return 0;
}
//keep creating rooms while we have new ones
while(node) {
//create Room
Room* room = new Room(node);
//Add room to unordered map
objectMap.insert(std::make_pair(room->get_name(), room));
//Get next room node
node = node->next_sibling("room");
}
//End Room Creation
//Container creation
node = mapNode->first_node("container");
while(node) {
Container* container = new Container(node);
objectMap.insert(std::make_pair(container->get_name(), container));
node = node->next_sibling("container");
}
//End Container creation
//Item creation
node = mapNode->first_node("item");
while(node) {
Item* item = new Item(node);
objectMap.insert(std::make_pair(item->get_name(), item));
node = node->next_sibling("item");
}
//End item Creation
//Create the player's inventory
auto inventory = Container();
//END OF SETUP
//START OF GAMEPLAY
//Find the Entrance to start the game
auto search = objectMap.find("Entrance");
auto currentRoom = dynamic_cast<Room*>(search->second);
std::cout << currentRoom->get_description() << std::endl;
//Start game
bool exit_condition = false;
while(exit_condition == false) {
//Get user input
std::string input;
std::getline(std::cin, input);
//parse input into separate tokens
std::istringstream iss{input};
std::vector<std::string> tokens{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};
//n, s, e, w
if(tokens[0] == "n" || tokens[0] == "s" || tokens[0] == "e" || tokens[0] == "w") {
currentRoom = currentRoom->movement(input, objectMap);
}
//open exit
else if(tokens[0] == "open exit") {
exit_condition = currentRoom->exit_check();
}
//i
else if(tokens[0] == "i") {
inventory.open_container();
}
//open (container)
else if(tokens[0] == "open" && tokens.size() == 2) {
std::string containerName = input.substr(5);
bool found = currentRoom->find_container(containerName);
if(found) {
auto containerSearch = objectMap.find(containerName);
auto container = dynamic_cast<Container*>(containerSearch->second);
container->open_container();
}
else {
std::cout << "Error: that container is not in this room" << std::endl;
}
}
//put (item) in (container)
else if(tokens[0] == "put" && tokens.size() == 4) {
std::istringstream iss{input};
std::vector<std::string> tokens{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};
bool found = inventory.find_item(tokens[1]);
if(found) {
bool containerFound = currentRoom->find_container(tokens[3]);
if(containerFound) {
auto containerSearch = objectMap.find(tokens[3]);
auto container = dynamic_cast<Container*>(containerSearch->second);
container->add_item(tokens[1]);
inventory.remove_item(tokens[1]);
std::cout << "Item " << tokens[1] << " added to " << tokens[3] << std::endl;
}
else {
std::cout << "Error: that container is not in this room" << std::endl;
}
}
else {
std::cout << "Error: you dont have " << tokens[1] << " in your inventory" << std::endl;
}
}
//take (item)
else if(tokens[0] == "take" && tokens.size() == 2) {
std::string itemName = input.substr(5);
bool found = currentRoom->find_item(itemName, objectMap);
if(found) {
inventory.add_item(itemName);
currentRoom->remove_item(itemName, objectMap);
std::cout << "Item " << itemName << " added to inventory" << std::endl;
}
else {
std::cout << "Error: that item is not in the current room" << std::endl;
}
}
//drop (item)
else if(tokens[0]== "drop" && tokens.size() == 2) {
std::string itemName = input.substr(5);
bool found = inventory.find_item(itemName);
if(found) {
inventory.remove_item(itemName);
currentRoom->add_item(itemName);
std::cout << itemName << " dropped" << std::endl;
}
else {
std::cout << "Error: you do not have " << itemName << " in your inventory" << std::endl;
}
}
//read (item)
else if(tokens[0] == "read" && tokens.size() == 2) {
std::string itemName = input.substr(5);
bool found = inventory.find_item(itemName);
if(found) {
auto search = objectMap.find(itemName);
auto item = dynamic_cast<Item*>(search->second);
item->read_writing();
}
else {
std::cout << "Error: you do not have " << itemName << " in your inventory" << std::endl;
}
}
//turn on (item)
else if(tokens[0] == "turn" && tokens[1] == "on" && tokens.size() == 3) {
std::istringstream iss{input};
std::vector<std::string> tokens{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};
std::string itemName = tokens[2];
bool found = inventory.find_item(itemName);
if(found) {
Item* item = dynamic_cast<Item*>(objectMap[itemName]);
//Get the vector of actions to perform
auto actions = item->turn_on();
//TODO implement behind the scenes actions
for(auto action : actions) {
parse_commands(action, objectMap);
}
}
}
else {
std::cout << "Invalid Command" << std::endl;
}
}
return 0;
}
<|endoftext|> |
<commit_before>bb393b5e-2747-11e6-a6b0-e0f84713e7b8<commit_msg>master branch<commit_after>bb499530-2747-11e6-98ab-e0f84713e7b8<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Fakenect to PCL frame dumper
*
* Copyright (c) 2015, David Tenty
*
* Portions originally from:
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/io/pcd_grabber.h>
#include <pcl/point_types.h>
#include <pcl/common/io.h>
#include <boost/filesystem.hpp>
#include <pcl/io/image_grabber.h>
#include <pcl/visualization/cloud_viewer.h>
using namespace std;
using namespace boost::filesystem;
typedef pcl::PointXYZRGBA PointT;
typedef pcl::PointCloud<PointT> CloudT;
// Helper function for grabbing a cloud
void
cloud_callback (bool *signal_received,
CloudT::ConstPtr *ptr_to_fill,
const CloudT::ConstPtr &input_cloud)
{
*signal_received = true;
*ptr_to_fill = input_cloud;
}
void usage(const char *progname) {
printf("Usage: %s [path_to_fakenect_dump]\n", progname);
cout << endl << "Note: this program non-destructively modifies the target dir" << endl;
}
int main (int argc,char *argv[])
{
if (argc !=2 ){
usage(argv[0]);
return 1;
}
// prepare the directory for grabber
path p (argv[1]);
if (!exists(p)) {
cerr << "Dump directory does not exist" << endl;
return 3;
}
// boost::filesystem::directory_iterator end_itr;
// for (boost::filesystem::directory_iterator itr (p); itr != end_itr; ++itr) {
//#if BOOST_FILESYSTEM_VERSION == 3
// extension = boost::algorithm::to_upper_copy(boost::filesystem::extension(itr->path()));
// pathname = itr->path().string();
// basename = boost::filesystem::basename(itr->path());
//#else
// extension = boost::algorithm::to_upper_copy (boost::filesystem::extension (itr->leaf ()));
// pathname = itr->path ().filename ();
// basename = boost::filesystem::basename (itr->leaf ());
//#endif
// }
// Get all clouds from the grabber
pcl::ImageGrabber<PointT> grabber (argv[1], 0, false, false);
vector<CloudT::ConstPtr> fakenect_clouds;
CloudT::ConstPtr cloud_buffer;
bool signal_received = false;
boost::function<void (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr&)>
fxn = boost::bind (cloud_callback, &signal_received, &cloud_buffer, _1);
grabber.registerCallback (fxn);
//grabber.setCameraIntrinsics (525., 525., 320., 240.); // Setting old intrinsics which were used to generate these tests
grabber.start ();
for (size_t i = 0; i < grabber.size (); i++)
{
grabber.trigger ();
size_t niter = 0;
while (!signal_received)
{
boost::this_thread::sleep (boost::posix_time::microseconds (10000));
if (++niter > 100)
{
cerr << "Stopped receiving frames from grabber" << endl;
return 2;
}
}
fakenect_clouds.push_back (cloud_buffer);
signal_received = false;
}
clog << "Got " << grabber.size() << " frames from grabber" << endl;
// write the clouds
// FIXME: check float to ASCII conversion for imprecision
for (vector<CloudT::ConstPtr>::iterator itr=fakenect_clouds.begin(); itr != fakenect_clouds.end(); itr++) {
string timestamp=to_string((*itr)->header.stamp);
pcl::io::savePCDFileASCII(string("frame_")+timestamp+string(".pcd"),**itr);
}
return 0;
}
<commit_msg>Fixed depth negation<commit_after>/*
* Software License Agreement (BSD License)
*
* Fakenect to PCL frame dumper
*
* Copyright (c) 2015, David Tenty
*
* Portions originally from:
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/io/pcd_grabber.h>
#include <pcl/point_types.h>
#include <pcl/common/io.h>
#include <boost/filesystem.hpp>
#include <pcl/io/image_grabber.h>
#include <pcl/visualization/cloud_viewer.h>
using namespace std;
using namespace boost::filesystem;
typedef pcl::PointXYZRGBA PointT;
typedef pcl::PointCloud<PointT> CloudT;
// Helper function for grabbing a cloud
void
cloud_callback (bool *signal_received,
CloudT::ConstPtr *ptr_to_fill,
const CloudT::ConstPtr &input_cloud)
{
*signal_received = true;
*ptr_to_fill = input_cloud;
}
void usage(const char *progname) {
printf("Usage: %s [path_to_fakenect_dump]\n", progname);
cout << endl << "Note: this program non-destructively modifies the target dir" << endl;
}
int main (int argc,char *argv[])
{
if (argc !=2 ){
usage(argv[0]);
return 1;
}
// prepare the directory for grabber
path p (argv[1]);
if (!exists(p)) {
cerr << "Dump directory does not exist" << endl;
return 3;
}
// boost::filesystem::directory_iterator end_itr;
// for (boost::filesystem::directory_iterator itr (p); itr != end_itr; ++itr) {
//#if BOOST_FILESYSTEM_VERSION == 3
// extension = boost::algorithm::to_upper_copy(boost::filesystem::extension(itr->path()));
// pathname = itr->path().string();
// basename = boost::filesystem::basename(itr->path());
//#else
// extension = boost::algorithm::to_upper_copy (boost::filesystem::extension (itr->leaf ()));
// pathname = itr->path ().filename ();
// basename = boost::filesystem::basename (itr->leaf ());
//#endif
// }
// Get all clouds from the grabber
pcl::ImageGrabber<PointT> grabber (argv[1], 0, false, false);
vector<CloudT::ConstPtr> fakenect_clouds;
CloudT::ConstPtr cloud_buffer;
bool signal_received = false;
boost::function<void (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr&)>
fxn = boost::bind (cloud_callback, &signal_received, &cloud_buffer, _1);
grabber.registerCallback (fxn);
//grabber.setCameraIntrinsics (525., 525., 320., 240.); // Setting old intrinsics which were used to generate these tests
grabber.setDepthImageUnits(-0.001);
grabber.start ();
for (size_t i = 0; i < grabber.size (); i++)
{
grabber.trigger ();
size_t niter = 0;
while (!signal_received)
{
boost::this_thread::sleep (boost::posix_time::microseconds (10000));
if (++niter > 100)
{
cerr << "Stopped receiving frames from grabber" << endl;
return 2;
}
}
fakenect_clouds.push_back (cloud_buffer);
signal_received = false;
}
clog << "Got " << grabber.size() << " frames from grabber" << endl;
// write the clouds
// FIXME: check float to ASCII conversion for imprecision
for (vector<CloudT::ConstPtr>::iterator itr=fakenect_clouds.begin(); itr != fakenect_clouds.end(); itr++) {
string timestamp=to_string((*itr)->header.stamp);
pcl::io::savePCDFileASCII(string("frame_")+timestamp+string(".pcd"),**itr);
}
return 0;
}
<|endoftext|> |
<commit_before>66f57ed0-5216-11e5-86c4-6c40088e03e4<commit_msg>66fdeed2-5216-11e5-a3fa-6c40088e03e4<commit_after>66fdeed2-5216-11e5-a3fa-6c40088e03e4<|endoftext|> |
<commit_before>b3fd57fd-327f-11e5-a60a-9cf387a8033e<commit_msg>b4048747-327f-11e5-945c-9cf387a8033e<commit_after>b4048747-327f-11e5-945c-9cf387a8033e<|endoftext|> |
<commit_before>af2f7150-35ca-11e5-a960-6c40088e03e4<commit_msg>af362f70-35ca-11e5-843b-6c40088e03e4<commit_after>af362f70-35ca-11e5-843b-6c40088e03e4<|endoftext|> |
<commit_before>ab8ffddc-35ca-11e5-9257-6c40088e03e4<commit_msg>ab96bc92-35ca-11e5-b20a-6c40088e03e4<commit_after>ab96bc92-35ca-11e5-b20a-6c40088e03e4<|endoftext|> |
<commit_before>fba0c630-585a-11e5-9184-6c40088e03e4<commit_msg>fba79a98-585a-11e5-b516-6c40088e03e4<commit_after>fba79a98-585a-11e5-b516-6c40088e03e4<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.