<commit_before>/*
 ---------------------------------------------------------------------------
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org>
---------------------------------------------------------------------------
*/
/*
Made By: Patrick J. Rye
Purpose: A game I made as an attempt to teach myself c++, just super basic, but going to try to keep improving it as my knowledge increases.
Current Revision: 3.0b-dev4
Change Log---------------------------------------------------------------------------------------------------------------------------------------------------
Date		Revision	Changed By		Changes
------  	---------   ------------	---------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
-------------------------------------------------------------------------------------------------------------------------------------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MOVED FROM ALPHA TO BETA~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-------------------------------------------------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
2015/02/24	1.0b		Patrick Rye		-Moved from V5.0-alpha to V1.0-beta
										-Fixed level up so it happens when you get to a new level.
										-Allowed exit on map.
										-Fixed opening text to reflect recent changes in the game.
										-Grammar and spelling fixes (yay, made it several revisions without having to do this. :) ).
=============================================================================================================================================================
2015/02/24	1.1b		Patrick Rye		-Attempted to allow movement on map through arrow keys.
										-Could not get this to work and broke everything. Rolling back to previous version.
										-Keeping this attempt in the record and will try to implement it again later.
=============================================================================================================================================================
2015/02/25	1.2b		Patrick Rye		-Grammar and spelling fixes. ((╯°□°)╯︵ ┻━┻)
										-Cleaned up code some more.
										-Changed some if statements to case switches.
										-Added breaks to case switches.
=============================================================================================================================================================
2015/02/26	1.3b		Patrick Rye		-Moved player movement to the room.h
=============================================================================================================================================================
2015/02/27	2.0b		Patrick Rye		-Added a save function, for testing purposes.
										-Added load function.
										-Added function to see if file exists.
=============================================================================================================================================================
2015/02/27	2.1b		Patrick Rye		-Moved save checker to basic.h
										-Renamed casechecker.h to basic.h
										-Added more comments explaining parts of the code.
										-Changed some names of functions to better reflect what they do.
										-Health is now carried between battles.
										-Moved healing to be able to happen between battles.
										-Added fail check for load function.
=============================================================================================================================================================
2015/03/02	2.2b		Patrick Rye		-Improved code a bit.
										-Added version number tracker.
										-Prompt for loading save.
										-Prompt for incorrect save version.
										-Moved saving and loading functions to its own header.
=============================================================================================================================================================
2015/03/02	2.2.1b		Patrick Rye		-Quick fix for version not being applied properly.
=============================================================================================================================================================
2015/03/03	2.3b		Patrick Rye		-Added more comments.
										-Changed some wording to better explain stuff.
										-Added a debug mode to game, detects if source code exists.
										-Grammar & spelling fixes.
=============================================================================================================================================================
2015/03/04	2.4b		Patrick Rye		-Debug mode can be set by loading a debug save.
										-Grammar & spelling fixes.
										-Improved map menu.
										-Changed save to 'V' rather than 'P'.
=============================================================================================================================================================
2015/03/06	2.5ß		Patrick Rye		-Changed some debug commands.
										-Changed change log date format from MM/DD/YY to YYYY/MM/DD because I like it better.
										-Added better opening message.
										-Replaced all system("pause") with getchar();
=============================================================================================================================================================
2015/03/06	3.0b		Patrick Rye		-Redid some calculations in battle.h
										-Added better winning message.
										-Added spells.h does nothing currently just for testing.
=============================================================================================================================================================
*/

/*********************************************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <cstdlib>
#include <cmath>
#include <locale>
#include <cstdio>
#include <ctime>
/*********************************************************************************************************/
#include "basic.h" //Functions that are simple and won't need to be changed very often.
#include "battle.h" //Functions that deal with battling, levelling up and making a player.
#include "rooms.h" //Functions that deal with generating a dungeon.
//#include "spells.h" //Functions that deal with spells and magic, a possible future addition.
/*********************************************************************************************************/
using namespace std;
Dungeon d; //Define the dungeon class as 'd' so I can use functions in there anywhere later in the code.
/*********************************************************************************************************/
//Make all the global variables that I need.
int intMainLevel; //The level of the dungeon.
int intLevelStart = 1; //The level that the game starts at. Will be 1 unless loading from a save.
bool blDebugMode = false; //If game is in debug mode or not, effects if player has access to debug commands.
const string CurrentVerison = "3.0b-dev4"; //The current version of this program, stored in a save file later on.
/*********************************************************************************************************/
//Some constant string for different messages that appear as large ASCII text.
const string OpeningMessage[16] = {"                                                             \n",
								   ",--.   ,--.       ,--.                                       \n",
								   "|  |   |  | ,---. |  | ,---. ,---. ,--,--,--. ,---.          \n",
								   "|  |.'.|  || .-. :|  || .--'| .-. ||        || .-. :         \n",
								   "|   ,'.   |\\   --.|  |\\ `--.' '-' '|  |  |  |\\   --.         \n",
								   "'--'   '--' `----'`--' `---' `---' `--`--`--' `----'         \n",
								   "  ,--.                                                       \n",
								   ",-'  '-. ,---.                                               \n",
								   "'-.  .-'| .-. |                                              \n",
								   "  |  |  ' '-' '                                              \n",
								   "  `--'   `---'                                               \n",
								   "  ,---.    ,--.    ,--.                ,--.                  \n",
								   " /  O  \\ ,-'  '-.,-'  '-. ,--,--. ,---.|  |,-. ,---. ,--.--. \n",
								   "|  .-.  |'-.  .-''-.  .-'' ,-.  || .--'|     /| .-. :|  .--' \n",
								   "|  | |  |  |  |    |  |  \\ '-'  |\\ `--.|  \\  \\\\   --.|  |    \n",
								   "`--' `--'  `--'    `--'   `--`--' `---'`--'`--'`----'`--'    \n"};

const string WinningMessage[6] = {"__   __            _    _ _       _ _ \n",
								 "\\ \\ / /           | |  | (_)     | | |\n",
								 " \\ V /___  _   _  | |  | |_ _ __ | | |\n",
								 "  \\ // _ \\| | | | | |/\\| | | '_ \\| | |\n",
								 "  | | (_) | |_| | \\  /\\  / | | | |_|_|\n",
								 "  \\_/\\___/ \\__,_|  \\/  \\/|_|_| |_(_|_)\n"};

/*********************************************************************************************************/
//These functions have to be up here as functions in save.h use them.
//These values are used to pass values to the save header so that they may be saved.
//Or to set values from a load.
int getmainvalue(int intvalue)
{
	if(intvalue == 0 ) {return intMainLevel;}
	else if (intvalue == 1) {return intLevelStart;}
	else {return 1;}
}
void setmainvalue(int intlocation, int intvalue) {if (intlocation == 0) {intLevelStart = intvalue;}}
void setdebugmode(bool blsetdebugmode) {blDebugMode = blsetdebugmode;}
#include "save.h" //A header to hold functions related to saving and loading.
/*********************************************************************************************************/

int main()
{
	PassProgramVerison(CurrentVerison); //Pass current program version into the save header.
	cout << string(48, '\n');
	char charPlayerDirection;
	bool blBattleEnding = false;
	char charExitFind;
	bool blOldSave = false;
	char chrPlayerMade = 'F';

	char chrSaveSuccess = 'N'; //N means that save has not been run.

	//If game is not already in debug mode, checks if source code exists then put it in debug mode if it does.
	if (!(blDebugMode)) {blDebugMode = fileexists("main.cpp"); }

	if (blDebugMode) {SetBattleDebugMode(true); SetRoomDebugMode(true);} //Sets debug mode for both rooms.h & battle.h

	for (int i = 0; i < 16; i++){cout<<OpeningMessage[i];}
	getchar();
	cout<<string(50,'\n');

	if (fileexists("save.bif")) //Check if there is a save present.
	{
		blOldSave = LoadOldSave();
		if (blOldSave) {chrPlayerMade = 'T';}
	//End of if save exists.
	}
	else {cout<<string(50, '\n');}

	if(!blOldSave) //If it is not an old save show welcome message.
	{
		cout<<endl<<"Your objective is to go through 10 randomly generated dungeons."<<endl;
		cout<<"You are looking for the stairs down ( > ). While you are represented by † ."<<endl;
		cout<<"Every step brings you closer to your goal, but there might be a monster there as well."<<endl;
		cout<<"Each level is harder than the last, do you have what it takes to win?"<<endl;
		cout<<"Good luck!"<<endl<<endl<<endl<<endl;
		while (chrPlayerMade != 'T') {chrPlayerMade = PlayerInitialize();}; //Repeat initialization until player is made.
	}

	for(intMainLevel = intLevelStart; intMainLevel <= 10; intMainLevel++)
	{
		//Do level up if new level.
		if (intMainLevel > intLevelStart) {LevelUpFunction();}
		charExitFind = 'F';
		cout<<endl;
		if (blOldSave && intMainLevel == intLevelStart) {/*d.playerfind();*/ d.showDungeon();} //If old save and the level of that save, just load old dungeon.
		else {Dungeon d;/*Generates dungeon.*/} //If it is not old game OR a different level of old game, make new dungeon.

		do
		{
			cout << string(50, '\n');
			d.showDungeon();
			cout<<"Level "<<intMainLevel<<" of 10."<<endl;
			cout<<"Please enter a direction you would like to go: "<<endl;
			cout<<"[N]orth,  [E]ast,  [S]outh,  [W]est  "<<endl;
			cout<<"E[X]it,   [C]heck your health, [H]eal,   Sa[V]e  "<<endl;
			if (blDebugMode) {cout<<"[L]evel up, or [M]onster."<<endl;}
			cout<<"> ";
			cin>>charPlayerDirection;
			charPlayerDirection = CharConvertToUpper(charPlayerDirection);

			charExitFind = d.PlayerMovement(charPlayerDirection);
			if (charExitFind == 'E') {return 0;} //If we get an error exit program.
			if (charExitFind == 'S') {chrSaveSuccess = savefunction();} //Save the game.
			switch (chrSaveSuccess)
			{
				case 'T' :
					cout<<endl<<"Save succeeded."<<endl;
					getchar();
					chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
					break;
				case 'F' :
					cout<<endl<<"Save failed!"<<endl;
					getchar();
					chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
					break;
			}
			if (!(charExitFind=='S') && !(charPlayerDirection == 'C')) //If player did not save or did not check himself, see if player runs into monster.
			{
				if(rand() % 101 <= 10 || charExitFind == 'M') //Random chance to encounter monster, or debug code to force monster encounter.
				{
					cout << string(50, '\n');
					blBattleEnding = startbattle(intMainLevel); //Starts battle.
					if(!blBattleEnding) {return 0;} //Player lost battle.
				}
			}
		}while (charExitFind != 'T'); //Repeat until player finds exit.
	//End of FOR levels.
	}
	cout << string(50, '\n');
	for (int i = 0; i < 6; i++) {cout<<WinningMessage[i];}
	getchar();
	return 0;
//End of main
}
<commit_msg>Update main to V3.0b<commit_after>/*
 ---------------------------------------------------------------------------
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org>
---------------------------------------------------------------------------
*/
/*
Made By: Patrick J. Rye
Purpose: A game I made as an attempt to teach myself c++, just super basic, but going to try to keep improving it as my knowledge increases.
Current Revision: 3.0b
Change Log---------------------------------------------------------------------------------------------------------------------------------------------------
Date		Revision	Changed By		Changes
------  	---------   ------------	---------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
-------------------------------------------------------------------------------------------------------------------------------------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MOVED FROM ALPHA TO BETA~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-------------------------------------------------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
2015/02/24	1.0b		Patrick Rye		-Moved from V5.0-alpha to V1.0-beta
										-Fixed level up so it happens when you get to a new level.
										-Allowed exit on map.
										-Fixed opening text to reflect recent changes in the game.
										-Grammar and spelling fixes (yay, made it several revisions without having to do this. :) ).
=============================================================================================================================================================
2015/02/24	1.1b		Patrick Rye		-Attempted to allow movement on map through arrow keys.
										-Could not get this to work and broke everything. Rolling back to previous version.
										-Keeping this attempt in the record and will try to implement it again later.
=============================================================================================================================================================
2015/02/25	1.2b		Patrick Rye		-Grammar and spelling fixes. ((╯°□°)╯︵ ┻━┻)
										-Cleaned up code some more.
										-Changed some if statements to case switches.
										-Added breaks to case switches.
=============================================================================================================================================================
2015/02/26	1.3b		Patrick Rye		-Moved player movement to the room.h
=============================================================================================================================================================
2015/02/27	2.0b		Patrick Rye		-Added a save function, for testing purposes.
										-Added load function.
										-Added function to see if file exists.
=============================================================================================================================================================
2015/02/27	2.1b		Patrick Rye		-Moved save checker to basic.h
										-Renamed casechecker.h to basic.h
										-Added more comments explaining parts of the code.
										-Changed some names of functions to better reflect what they do.
										-Health is now carried between battles.
										-Moved healing to be able to happen between battles.
										-Added fail check for load function.
=============================================================================================================================================================
2015/03/02	2.2b		Patrick Rye		-Improved code a bit.
										-Added version number tracker.
										-Prompt for loading save.
										-Prompt for incorrect save version.
										-Moved saving and loading functions to its own header.
=============================================================================================================================================================
2015/03/02	2.2.1b		Patrick Rye		-Quick fix for version not being applied properly.
=============================================================================================================================================================
2015/03/03	2.3b		Patrick Rye		-Added more comments.
										-Changed some wording to better explain stuff.
										-Added a debug mode to game, detects if source code exists.
										-Grammar & spelling fixes.
=============================================================================================================================================================
2015/03/04	2.4b		Patrick Rye		-Debug mode can be set by loading a debug save.
										-Grammar & spelling fixes.
										-Improved map menu.
										-Changed save to 'V' rather than 'P'.
=============================================================================================================================================================
2015/03/06	2.5ß		Patrick Rye		-Changed some debug commands.
										-Changed change log date format from MM/DD/YY to YYYY/MM/DD because I like it better.
										-Added better opening message.
										-Replaced all system("pause") with getchar();
=============================================================================================================================================================
2015/03/06	3.0b		Patrick Rye		-Redid some calculations in battle.h
										-Added better winning message.
										-Added spells.h does nothing currently just for testing.
=============================================================================================================================================================
*/

/*********************************************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <cstdlib>
#include <cmath>
#include <locale>
#include <cstdio>
#include <ctime>
/*********************************************************************************************************/
#include "basic.h" //Functions that are simple and won't need to be changed very often.
#include "battle.h" //Functions that deal with battling, levelling up and making a player.
#include "rooms.h" //Functions that deal with generating a dungeon.
//#include "spells.h" //Functions that deal with spells and magic, a possible future addition.
/*********************************************************************************************************/
using namespace std;
Dungeon d; //Define the dungeon class as 'd' so I can use functions in there anywhere later in the code.
/*********************************************************************************************************/
//Make all the global variables that I need.
int intMainLevel; //The level of the dungeon.
int intLevelStart = 1; //The level that the game starts at. Will be 1 unless loading from a save.
bool blDebugMode = false; //If game is in debug mode or not, effects if player has access to debug commands.
const string CurrentVerison = "3.0b"; //The current version of this program, stored in a save file later on.
/*********************************************************************************************************/
//Some constant string for different messages that appear as large ASCII text.
const string OpeningMessage[16] = {"                                                             \n",
								   ",--.   ,--.       ,--.                                       \n",
								   "|  |   |  | ,---. |  | ,---. ,---. ,--,--,--. ,---.          \n",
								   "|  |.'.|  || .-. :|  || .--'| .-. ||        || .-. :         \n",
								   "|   ,'.   |\\   --.|  |\\ `--.' '-' '|  |  |  |\\   --.         \n",
								   "'--'   '--' `----'`--' `---' `---' `--`--`--' `----'         \n",
								   "  ,--.                                                       \n",
								   ",-'  '-. ,---.                                               \n",
								   "'-.  .-'| .-. |                                              \n",
								   "  |  |  ' '-' '                                              \n",
								   "  `--'   `---'                                               \n",
								   "  ,---.    ,--.    ,--.                ,--.                  \n",
								   " /  O  \\ ,-'  '-.,-'  '-. ,--,--. ,---.|  |,-. ,---. ,--.--. \n",
								   "|  .-.  |'-.  .-''-.  .-'' ,-.  || .--'|     /| .-. :|  .--' \n",
								   "|  | |  |  |  |    |  |  \\ '-'  |\\ `--.|  \\  \\\\   --.|  |    \n",
								   "`--' `--'  `--'    `--'   `--`--' `---'`--'`--'`----'`--'    \n"};

const string WinningMessage[6] = {"__   __            _    _ _       _ _ \n",
								 "\\ \\ / /           | |  | (_)     | | |\n",
								 " \\ V /___  _   _  | |  | |_ _ __ | | |\n",
								 "  \\ // _ \\| | | | | |/\\| | | '_ \\| | |\n",
								 "  | | (_) | |_| | \\  /\\  / | | | |_|_|\n",
								 "  \\_/\\___/ \\__,_|  \\/  \\/|_|_| |_(_|_)\n"};

/*********************************************************************************************************/
//These functions have to be up here as functions in save.h use them.
//These values are used to pass values to the save header so that they may be saved.
//Or to set values from a load.
int getmainvalue(int intvalue)
{
	if(intvalue == 0 ) {return intMainLevel;}
	else if (intvalue == 1) {return intLevelStart;}
	else {return 1;}
}
void setmainvalue(int intlocation, int intvalue) {if (intlocation == 0) {intLevelStart = intvalue;}}
void setdebugmode(bool blsetdebugmode) {blDebugMode = blsetdebugmode;}
#include "save.h" //A header to hold functions related to saving and loading.
/*********************************************************************************************************/

int main()
{
	PassProgramVerison(CurrentVerison); //Pass current program version into the save header.
	cout << string(48, '\n');
	char charPlayerDirection;
	bool blBattleEnding = false;
	char charExitFind;
	bool blOldSave = false;
	char chrPlayerMade = 'F';

	char chrSaveSuccess = 'N'; //N means that save has not been run.

	//If game is not already in debug mode, checks if source code exists then put it in debug mode if it does.
	if (!(blDebugMode)) {blDebugMode = fileexists("main.cpp"); }

	if (blDebugMode) {SetBattleDebugMode(true); SetRoomDebugMode(true);} //Sets debug mode for both rooms.h & battle.h

	for (int i = 0; i < 16; i++){cout<<OpeningMessage[i];}
	getchar();
	cout<<string(50,'\n');

	if (fileexists("save.bif")) //Check if there is a save present.
	{
		blOldSave = LoadOldSave();
		if (blOldSave) {chrPlayerMade = 'T';}
	//End of if save exists.
	}
	else {cout<<string(50, '\n');}

	if(!blOldSave) //If it is not an old save show welcome message.
	{
		cout<<endl<<"Your objective is to go through 10 randomly generated dungeons."<<endl;
		cout<<"You are looking for the stairs down ( > ). While you are represented by † ."<<endl;
		cout<<"Every step brings you closer to your goal, but there might be a monster there as well."<<endl;
		cout<<"Each level is harder than the last, do you have what it takes to win?"<<endl;
		cout<<"Good luck!"<<endl<<endl<<endl<<endl;
		while (chrPlayerMade != 'T') {chrPlayerMade = PlayerInitialize();}; //Repeat initialization until player is made.
	}

	for(intMainLevel = intLevelStart; intMainLevel <= 10; intMainLevel++)
	{
		//Do level up if new level.
		if (intMainLevel > intLevelStart) {LevelUpFunction();}
		charExitFind = 'F';
		cout<<endl;
		if (blOldSave && intMainLevel == intLevelStart) {/*d.playerfind();*/ d.showDungeon();} //If old save and the level of that save, just load old dungeon.
		else {Dungeon d;/*Generates dungeon.*/} //If it is not old game OR a different level of old game, make new dungeon.

		do
		{
			cout << string(50, '\n');
			d.showDungeon();
			cout<<"Level "<<intMainLevel<<" of 10."<<endl;
			cout<<"Please enter a direction you would like to go: "<<endl;
			cout<<"[N]orth,  [E]ast,  [S]outh,  [W]est  "<<endl;
			cout<<"E[X]it,   [C]heck your health, [H]eal,   Sa[V]e  "<<endl;
			if (blDebugMode) {cout<<"[L]evel up, or [M]onster."<<endl;}
			cout<<"> ";
			cin>>charPlayerDirection;
			charPlayerDirection = CharConvertToUpper(charPlayerDirection);

			charExitFind = d.PlayerMovement(charPlayerDirection);
			if (charExitFind == 'E') {return 0;} //If we get an error exit program.
			if (charExitFind == 'S') {chrSaveSuccess = savefunction();} //Save the game.
			switch (chrSaveSuccess)
			{
				case 'T' :
					cout<<endl<<"Save succeeded."<<endl;
					getchar();
					chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
					break;
				case 'F' :
					cout<<endl<<"Save failed!"<<endl;
					getchar();
					chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
					break;
			}
			if (!(charExitFind=='S') && !(charPlayerDirection == 'C')) //If player did not save or did not check himself, see if player runs into monster.
			{
				if(rand() % 101 <= 10 || charExitFind == 'M') //Random chance to encounter monster, or debug code to force monster encounter.
				{
					cout << string(50, '\n');
					blBattleEnding = startbattle(intMainLevel); //Starts battle.
					if(!blBattleEnding) {return 0;} //Player lost battle.
				}
			}
		}while (charExitFind != 'T'); //Repeat until player finds exit.
	//End of FOR levels.
	}
	cout << string(50, '\n');
	for (int i = 0; i < 6; i++) {cout<<WinningMessage[i];}
	getchar();
	return 0;
//End of main
}
<|endoftext|>


<commit_before>int
main(void)
{
  return 0;
}
<commit_msg>Add beginnings of CLI<commit_after>#include <cstdio>
#include <cstring>

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

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

static int
handle_filepath(const char *filepath);

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

  for (const char *off = argv; *off; off += 1) {

    int ch;
    const char *arg = off;

    ch = arg[0];
    if (ch != '-')
      continue;

    /* handle -h */
    ch = arg[1];
    if (ch == 'h') {
      print_usage(stdout);
      exit(EXIT_SUCCESS);
    }

    /* handle --help*/
    if (ch == '-' && !strcmp(arg + 2, "help")) {
      print_usage(stdout);
      exit(EXIT_SUCCESS);
    }

  }

  for (const char *off = argv; *off; off += 1)
    handle_filepath(off);

  return 0;
}
<|endoftext|>


<commit_before>/*
Made By: Patrick J. Rye
Purpose: A game I made as an attempt to teach myself c++, just super basic, but going to try to keep improving it as my knowledge increases.
Current Revision: 1.2c
Change Log---------------------------------------------------------------------------------------------------------------------------------------------------
Date		Revision	Changed By		Changes
------  	---------   ------------	---------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
-------------------------------------------------------------------------------------------------------------------------------------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MOVED FROM BETA TO GAMMA~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-------------------------------------------------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
2015/03/13	1.0c		Patrick Rye		-Move from beta revisions to gamma revisions.
										-Changed some int to smaller variables because they don't need to be that big.
										-Fixed bug where new dungeon wasn't generating properly. (This is what happens when you don't play test changes for a while).
										-Made it so you have to be in debug mode to force a monster (Don't know why you would want this otherwise)
										-General code improvement.
=============================================================================================================================================================
2015/03/17	1.1c		Patrick Rye		-Grammar & spelling fixes.
										-Updated save.h with more values.
										-Implemented mana system.
=============================================================================================================================================================
2015/03/18	1.2c		Patrick Rye		-Removed unneeded libraries.
=============================================================================================================================================================
*/

/*********************************************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <stdio.h>
#include <cstdlib>
/*********************************************************************************************************/
#include "basic.h" //Functions that are simple, referenced many places and/or won't need to be changed very often.
#include "battle.h" //Functions that deal with battling, levelling up and making a player.
#include "rooms.h" //Functions that deal with generating a dungeon, and moving through it.
#include "spells.h" //Functions that deal with spells and magic.
/*********************************************************************************************************/
using namespace std;
Dungeon d; //Define the dungeon class as 'd' so I can use functions in there anywhere later in the code.
/*********************************************************************************************************/
//Make all the global variables that I need.
unsigned char intMainLevel = 1; //The level of the dungeon.
unsigned char intLevelStart = 1; //The level that the game starts at. Will be 1 unless loading from a save.
bool blDebugMode = false; //If game is in debug mode or not, effects if player has access to debug commands.
const string CurrentVerison = "1.2c"; //The current version of this program, stored in a save file later on.
/*********************************************************************************************************/
//These functions have to be up here as functions in save.h use them.
//These values are used to pass values to the save header so that they may be saved.
//Or to set values from a load.
int getmainvalue(unsigned char intvalue)
{
	if(intvalue == 0 ) {return intMainLevel;}
	else if (intvalue == 1) {return intLevelStart;}
	else {return 1;}
}
void setmainvalue(unsigned char intlocation, unsigned int intvalue) {if (intlocation == 0) {intLevelStart = intvalue;}}
void setdebugmode(bool blsetdebugmode) {blDebugMode = blsetdebugmode;}
#include "save.h" //A header to hold functions related to saving and loading.
/*********************************************************************************************************/

int main()
{
	PassProgramVerison(CurrentVerison); //Pass current program version into the save header.
	cout << string(48, '\n');
	char charPlayerDirection;
	bool blBattleEnding = false;
	char charExitFind;
	bool blOldSave = false;
	char chrPlayerMade = 'F';
	char chrSaveSuccess = 'N'; //N means that save has not been run.
	//If game is not already in debug mode, checks if source code exists then put it in debug mode if it does.
	if (!(blDebugMode)) {blDebugMode = fileexists("main.cpp"); }
	//Sets debug mode for rooms.h, battle.h, & spells.h
	if (blDebugMode) {SetBattleDebugMode(true); SetRoomDebugMode(true); SetSpellDebugMode(true);}
	ShowOpeningMessage();
	getchar();
	cout<<string(50,'\n');

	if (fileexists("save.bif")) //Check if there is a save present.
	{
		blOldSave = LoadOldSave();
		if (blOldSave) {chrPlayerMade = 'T';}
	//End of if save exists.
	}
	else {cout<<string(50, '\n');}

	if(!blOldSave) //If it is not an old save show welcome message.
	{
		cout<<endl<<"Your objective is to go through 10 randomly generated dungeons."<<endl;
		cout<<"You are looking for the stairs down ( > ). While you are represented by @ ."<<endl;
		cout<<"Every step brings you closer to your goal, but there might be a monster there as well."<<endl;
		cout<<"Each level is harder than the last, do you have what it takes to win?"<<endl;
		cout<<"Good luck!"<<endl<<endl<<endl<<endl;
		while (chrPlayerMade != 'T') {chrPlayerMade = PlayerInitialize();}; //Repeat initialization until player is made.
	}

	for(intMainLevel = intLevelStart; intMainLevel <= 10; intMainLevel++)
	{
		//Do level up if new level.
		if (intMainLevel > intLevelStart) {LevelUpFunction();}
		charExitFind = 'F';
		cout<<endl;
		if (blOldSave && intMainLevel == intLevelStart) {/*d.playerfind();*/ d.showDungeon();} //If old save and the level of that save, just load old dungeon.
		else {d.cmain();/*Generates dungeon.*/} //If it is not old game OR a different level of old game, make new dungeon.

		do
		{
			cout << string(50, '\n');
			d.showDungeon();
			cout<<"Level "<<(int)intMainLevel<<" of 10."<<endl;
			cout<<"Please enter a direction you would like to go: "<<endl;
			cout<<"[N]orth,  [E]ast,  [S]outh,  [W]est  "<<endl;
			cout<<"E[X]it,   [C]heck your health, [H]eal,   Sa[V]e  "<<endl;
			if (blDebugMode) {cout<<"[L]evel up, or [M]onster."<<endl;}
			cout<<"> ";
			cin>>charPlayerDirection;
			charPlayerDirection = CharConvertToUpper(charPlayerDirection);
			charExitFind = d.PlayerMovement(charPlayerDirection);
			if (charExitFind == 'E') {return 0;} //If we get an error exit program.
			if (charExitFind == 'S') {chrSaveSuccess = savefunction();} //Save the game.
			switch (chrSaveSuccess)
			{
				case 'T' :
					cout<<endl<<"Save succeeded."<<endl;
					getchar();
					chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
					break;
				case 'F' :
					cout<<endl<<"Save failed!"<<endl;
					getchar();
					chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
					break;
			}
			if (!(charExitFind=='S') && !(charPlayerDirection == 'C')) //If player did not save or did not check himself, see if player runs into monster.
			{
				if(rand() % 101 <= 10 || (charExitFind == 'M' && blDebugMode)) //Random chance to encounter monster, or debug code to force monster encounter.
				{
					cout << string(50, '\n');
					blBattleEnding = startbattle(intMainLevel); //Starts battle.
					setbattlevalue(statKeys,getbattlevalue(statKeys) + getmonstervalue(statKeys)); //Give player a key if monster had one.
					if(!blBattleEnding) {return 0;} //Player lost battle.
				}
			}
		}while (charExitFind != 'T'); //Repeat until player finds exit.
	//End of FOR levels.
	}
	cout << string(50, '\n');
	ShowWinningMessage();
	getchar();
	return 0;
//End of main
}
<commit_msg>Update Main to V1.4c-dev1<commit_after>/*
Made By: Patrick J. Rye
Purpose: A game I made as an attempt to teach myself c++, just super basic, but going to try to keep improving it as my knowledge increases.
Current Revision: 1.4c-dev1
Change Log---------------------------------------------------------------------------------------------------------------------------------------------------
Date		Revision	Changed By		Changes
------  	---------   ------------	---------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
-------------------------------------------------------------------------------------------------------------------------------------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MOVED FROM BETA TO GAMMA~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-------------------------------------------------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
2015/03/13	1.0c		Patrick Rye		-Move from beta revisions to gamma revisions.
										-Changed some int to smaller variables because they don't need to be that big.
										-Fixed bug where new dungeon wasn't generating properly. (This is what happens when you don't play test changes for a while).
										-Made it so you have to be in debug mode to force a monster (Don't know why you would want this otherwise)
										-General code improvement.
=============================================================================================================================================================
2015/03/17	1.1c		Patrick Rye		-Grammar & spelling fixes.
										-Updated save.h with more values.
										-Implemented mana system.
=============================================================================================================================================================
2015/03/18	1.2c		Patrick Rye		-Removed unneeded libraries.
=============================================================================================================================================================
2015/04/25	1.3c		Patrick Rye		-Attempted to correct my misunderstanding of how headers work, broken everything had to revert back.
=============================================================================================================================================================
2015/04/25	1.4c		Patrick Rye		-
=============================================================================================================================================================
*/

/*********************************************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <stdio.h>
#include <cstdlib>
/*********************************************************************************************************/
#include "basic.h" //Functions that are simple, referenced many places and/or won't need to be changed very often.
#include "battle.h" //Functions that deal with battling, levelling up and making a player.
#include "rooms.h" //Functions that deal with generating a dungeon, and moving through it.
#include "spells.h" //Functions that deal with spells and magic.
/*********************************************************************************************************/
using namespace std;
Dungeon d; //Define the dungeon class as 'd' so I can use functions in there anywhere later in the code.
/*********************************************************************************************************/
//Make all the global variables that I need.
unsigned char intMainLevel = 1; //The level of the dungeon.
unsigned char intLevelStart = 1; //The level that the game starts at. Will be 1 unless loading from a save.
bool blDebugMode = false; //If game is in debug mode or not, effects if player has access to debug commands.
const string CurrentVerison = "1.4c-dev1"; //The current version of this program, stored in a save file later on.
/*********************************************************************************************************/
//These functions have to be up here as functions in save.h use them.
//These values are used to pass values to the save header so that they may be saved.
//Or to set values from a load.
int getmainvalue(unsigned char intvalue)
{
	if(intvalue == 0 ) {return intMainLevel;}
	else if (intvalue == 1) {return intLevelStart;}
	else {return 1;}
}
void setmainvalue(unsigned char intlocation, unsigned int intvalue) {if (intlocation == 0) {intLevelStart = intvalue;}}
void setdebugmode(bool blsetdebugmode) {blDebugMode = blsetdebugmode;}
#include "save.h" //A header to hold functions related to saving and loading.
/*********************************************************************************************************/

int main()
{
	PassProgramVerison(CurrentVerison); //Pass current program version into the save header.
	cout << string(48, '\n');
	char charPlayerDirection;
	bool blBattleEnding = false;
	char charExitFind;
	bool blOldSave = false;
	char chrPlayerMade = 'F';
	char chrSaveSuccess = 'N'; //N means that save has not been run.
	//If game is not already in debug mode, checks if source code exists then put it in debug mode if it does.
	if (!(blDebugMode)) {blDebugMode = fileexists("main.cpp"); }
	//Sets debug mode for rooms.h, battle.h, & spells.h
	if (blDebugMode) {SetBattleDebugMode(true); SetRoomDebugMode(true); SetSpellDebugMode(true);}
	ShowOpeningMessage();
	getchar();
	cout<<string(50,'\n');

	if (fileexists("save.bif")) //Check if there is a save present.
	{
		blOldSave = LoadOldSave();
		if (blOldSave) {chrPlayerMade = 'T';}
	//End of if save exists.
	}
	else {cout<<string(50, '\n');}

	if(!blOldSave) //If it is not an old save show welcome message.
	{
		cout<<endl<<"Your objective is to go through 10 randomly generated dungeons."<<endl;
		cout<<"You are looking for the stairs down ( > ). While you are represented by @ ."<<endl;
		cout<<"Every step brings you closer to your goal, but there might be a monster there as well."<<endl;
		cout<<"Each level is harder than the last, do you have what it takes to win?"<<endl;
		cout<<"Good luck!"<<endl<<endl<<endl<<endl;
		while (chrPlayerMade != 'T') {chrPlayerMade = PlayerInitialize();}; //Repeat initialization until player is made.
	}

	for(intMainLevel = intLevelStart; intMainLevel <= 10; intMainLevel++)
	{
		//Do level up if new level.
		if (intMainLevel > intLevelStart) {LevelUpFunction();}
		charExitFind = 'F';
		cout<<endl;
		if (blOldSave && intMainLevel == intLevelStart) {/*d.playerfind();*/ d.showDungeon();} //If old save and the level of that save, just load old dungeon.
		else {d.cmain();/*Generates dungeon.*/} //If it is not old game OR a different level of old game, make new dungeon.

		do
		{
			cout << string(50, '\n');
			d.showDungeon();
			cout<<"Level "<<(int)intMainLevel<<" of 10."<<endl;
			cout<<"Please enter a direction you would like to go: "<<endl;
			cout<<"[N]orth,  [E]ast,  [S]outh,  [W]est  "<<endl;
			cout<<"E[X]it,   [C]heck your health, [H]eal,   Sa[V]e  "<<endl;
			if (blDebugMode) {cout<<"[L]evel up, or [M]onster."<<endl;}
			cout<<"> ";
			cin>>charPlayerDirection;
			charPlayerDirection = CharConvertToUpper(charPlayerDirection);
			charExitFind = d.PlayerMovement(charPlayerDirection);
			if (charExitFind == 'E') {return 0;} //If we get an error exit program.
			if (charExitFind == 'S') {chrSaveSuccess = savefunction();} //Save the game.
			switch (chrSaveSuccess)
			{
				case 'T' :
					cout<<endl<<"Save succeeded."<<endl;
					getchar();
					chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
					break;
				case 'F' :
					cout<<endl<<"Save failed!"<<endl;
					getchar();
					chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
					break;
			}
			if (!(charExitFind=='S') && !(charPlayerDirection == 'C')) //If player did not save or did not check himself, see if player runs into monster.
			{
				if(rand() % 101 <= 10 || (charExitFind == 'M' && blDebugMode)) //Random chance to encounter monster, or debug code to force monster encounter.
				{
					cout << string(50, '\n');
					blBattleEnding = startbattle(intMainLevel); //Starts battle.
					setbattlevalue(statKeys,getbattlevalue(statKeys) + getmonstervalue(statKeys)); //Give player a key if monster had one.
					if(!blBattleEnding) {return 0;} //Player lost battle.
				}
			}
		}while (charExitFind != 'T'); //Repeat until player finds exit.
	//End of FOR levels.
	}
	cout << string(50, '\n');
	ShowWinningMessage();
	getchar();
	return 0;
//End of main
}
<|endoftext|>


<commit_before>c07c601c-4b02-11e5-9a90-28cfe9171a43<commit_msg>Fix that bug where things didn't work but now they should<commit_after>c08b5b1c-4b02-11e5-8120-28cfe9171a43<|endoftext|>


<commit_before>#include <iostream>
#include <unistd.h>
#include <string.h>
#include <string>
#include <stdio.h>
#include <sys/unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/param.h>
#include <stdlib.h>
#include <vector>

using namespace std;

void string_parsing(string String,vector<string> & char_array){
	char *token_1;
	token_1 = strtok(&String[0], " ");
	while(token_1 !=NULL){
	char_array.push_back(token_1);
	token_1 = strtok(NULL, " ");
	}
}

int main(){

	vector<string> char_array;
	vector<string> pars_array;
	char *login_name;
	int n;
	int i;
	int pid;
	login_name = getlogin();
	char host_name[MAXHOSTNAMELEN];
	gethostname(host_name,sizeof host_name);
	string usr_input;
	string usr_input2;

	while(usr_input != "exit"){
	cout << login_name << "@" << host_name << "$";
	getline(cin, usr_input);
	char * token;
	token = strtok(&usr_input[0], "#");
	usr_input = token;
	string usr_input2;

	int trav_str = usr_input.size();
	int str_ctr  = 0;
	for(str_ctr=0;str_ctr < trav_str;++str_ctr){

		if(usr_input == "exit"){
		cout << "Exiting..."<< endl;
		goto end_of_while;
		}

		if(usr_input[str_ctr] == ';'){
			token = strtok(&usr_input[0], ";");
				while(token != NULL){
					pars_array.push_back(token);
					token = strtok(NULL,";");
				}
			int pars_size = pars_array.size()-1;
			int pars_ctr  = 0;

			for(pars_ctr =0; pars_ctr <= pars_size; pars_ctr++){
				usr_input2 = pars_array[pars_ctr];
				string_parsing(usr_input2,char_array);
				int i = char_array.size();
				char * argv[100];
				int n = 0;
					for(n = 0; n <= i-1; ++n){
						argv[n] = new char[char_array[n].size()+1];
					}
			for(n = 0; n < i; ++n){
				strcpy(argv[n], char_array[n].c_str());
			}
			argv[n] = NULL;
			int pid = fork();
			if(pid == -1){
				perror("there was error with fork().");
				exit(1);}
			else if(pid == 0){
				if(-1 == execvp(argv[0],argv)){
					perror("there was an error");
				}
				exit(1);
			}
			else if(pid > 0){
				if(-1 == wait(0)){perror("there was an error with wait().");}
			}
			char_array.clear();
			}

		pars_array.clear();
		goto end_of_while;
		}

		else if(usr_input[str_ctr] == '&' && usr_input[str_ctr+1] == '&'){
			token = strtok(&usr_input[0], "&&");
				while(token != NULL){
					pars_array.push_back(token);
					token = strtok(NULL,"&&");
				}
			int pars_size = pars_array.size();
			int pars_ctr  = 0;

			for(pars_ctr =0; pars_ctr < pars_size; pars_ctr++){
				usr_input2 = pars_array[pars_ctr];
				string_parsing(usr_input2,char_array);
				int i = char_array.size();
				char * argv[100];
				int n = 0;
					for(n = 0; n <= i-1; ++n){
						argv[n] = new char[char_array[n].size()+1];
					}
			for(n = 0; n < i; ++n){
				strcpy(argv[n], char_array[n].c_str());
			}
			argv[n] = NULL;
			int pid = fork();
			if(pid == -1){
				perror("there was error with fork().");
				exit(1);}
			else if(pid == 0){
				if(-1 == execvp(argv[0],argv)){
					perror("there was an error");
					goto end_of_while;
					}
				exit(1);
			}
			else if(pid > 0){
				if(-1 == wait(0)){perror("there was an error with wait().");}
			}
			char_array.clear();
			}

		pars_array.clear();
		goto end_of_while;
		}

		else if(usr_input[str_ctr] == '|' && usr_input[str_ctr+1] == '|'){
			token = strtok(&usr_input[0], "||");
				while(token != NULL){
					pars_array.push_back(token);
					token = strtok(NULL,"||");
				}

				int pars_size = pars_array.size()-1;
				int pars_ctr  = 0;

			for(pars_ctr =0; pars_ctr <= pars_size; pars_ctr++){
				usr_input2 = pars_array[pars_ctr];
				string_parsing(usr_input2,char_array);
				int i = char_array.size();
				char * argv[100];
				int n = 0;
					for(n = 0; n <= i-1; ++n){
						argv[n] = new char[char_array[n].size()+1];
					}
			for(n = 0; n < i; ++n){
				strcpy(argv[n], char_array[n].c_str());
			}
			argv[n] = NULL;
			int pid = fork();
			if(pid == -1){
				perror("there was error with fork().");
				exit(1);}
			else if(pid == 0){
				if(-1 == execvp(argv[0],argv)){
					perror("there was an error");
				}
				exit(1);
			}
			else if(pid > 0){
				if(-1 == wait(0)){perror("there was an error with wait().");}
			}
			char_array.clear();
			}

		pars_array.clear();
		goto end_of_while;
		}
		}
			string_parsing(usr_input,char_array);

			i = char_array.size();
			char * argv[100];
			n = 0;
			for(n = 0; n <= i-1; ++n){
				argv[n] = new char[char_array[n].size()+1];
			}
			for(n = 0; n < i; ++n){
				strcpy(argv[n], char_array[n].c_str());
			}
			argv[n] = NULL;
			pid = fork();
			if(pid == -1){
				perror("there was error with fork().");
				exit(1);}
			else if(pid == 0){
				if(-1 == execvp(argv[0],argv)){
					perror("there was an error");
				}
				exit(1);
			}
			else if(pid > 0){
				if(-1 == wait(0)){perror("there was an error with wait().");}
			}
			char_array.clear();
			pars_array.clear();
	end_of_while:
	char_array.clear();

}

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


<commit_before>#include "eval.hpp"

#include <iostream>

using klmr::lisp::value;
using klmr::lisp::environment;

auto read(std::string const& input) -> value {
    (void) input;
    using namespace klmr::lisp;

    return list{
        symbol{"define"},
        symbol{"double"},
        list{
            symbol{"lambda"},
            list{symbol{"n"}},
            list{
                symbol{"*"},
                symbol{"n"},
                symbol{"n"}
            }
        }
    }; // FIXME placeholder
}

auto get_global_environment() -> environment {
    using namespace klmr::lisp;
    auto env = environment{};
    env.set(symbol{"lambda"},
        macro{env, {"args", "expr"},
        [] (environment& env) {
            auto&& args = as_list(env["args"]);
            auto formals = std::vector<symbol>(length(args));
            std::transform(begin(args), end(args), begin(formals), as_symbol);
            auto expr = env["expr"];
            // FIXME Capture by value incurs expensive copy. Solved in C++14.
            return call{env, formals, [expr](environment& frame) {
                return eval(expr, frame);
            }};
        }}
    );
    env.set(symbol{"define"},
        macro{env, {"name", "expr"}, [] (environment& env) {
            auto&& name = as_symbol(env["name"]);
            env.set(name, eval(env["expr"], env));
            return nil;
        }}
    );
    return env;
}

auto repl(std::string prompt) -> void {
    auto input = std::string{};
    auto global_env = get_global_environment();
    for (;;) {
        std::cout << prompt << std::flush;
        if (not getline(std::cin, input))
            return;
        auto&& result = eval(read(input), global_env);
        std::cout << result << '\n';
    }
}

auto main() -> int
try {
    repl(">>> ");
} catch (klmr::lisp::name_error const& msg) {
    std::cerr << msg.what() << '\n';
    return 1;
}
<commit_msg>Add test case: evaluate call<commit_after>#include "eval.hpp"

#include <iostream>

using klmr::lisp::value;
using klmr::lisp::environment;

auto read(std::string const& input) -> value {
    (void) input;
    using namespace klmr::lisp;

    static auto items = std::vector<value> {
        list{
            symbol{"define"},
            symbol{"double"},
            list{
                symbol{"lambda"},
                list{symbol{"n"}},
                list{
                    symbol{"*"},
                    symbol{"n"},
                    symbol{"n"}
                }
            }
        },

        list{
            symbol{"double"},
            literal<double>{4}
        }
    };

    static auto current = 0u;

    return current < items.size() ? items[current++] : value{nil}; // FIXME placeholder
}

auto get_global_environment() -> environment {
    using namespace klmr::lisp;
    auto env = environment{};
    env.set(symbol{"lambda"},
        macro{env, {"args", "expr"},
        [] (environment& env) {
            auto&& args = as_list(env["args"]);
            auto formals = std::vector<symbol>(length(args));
            std::transform(begin(args), end(args), begin(formals), as_symbol);
            auto expr = env["expr"];
            // FIXME Capture by value incurs expensive copy. Solved in C++14.
            return call{env, formals, [expr](environment& frame) {
                return eval(expr, frame);
            }};
        }}
    );
    env.set(symbol{"define"},
        macro{env, {"name", "expr"}, [] (environment& env) {
            auto&& name = as_symbol(env["name"]);
            env.set(name, eval(env["expr"], env));
            return nil;
        }}
    );
    return env;
}

auto repl(std::string prompt) -> void {
    auto input = std::string{};
    auto global_env = get_global_environment();
    for (;;) {
        std::cout << prompt << std::flush;
        if (not getline(std::cin, input))
            return;
        auto&& result = eval(read(input), global_env);
        std::cout << result << '\n';
    }
}

auto main() -> int
try {
    repl(">>> ");
} catch (klmr::lisp::name_error const& msg) {
    std::cerr << msg.what() << '\n';
    return 1;
}
<|endoftext|>


<commit_before>//使用链表存储相应所有正在计算的task，按用户分队列计算，每0.1s进行一次检查操作，如果发现任务已完成，则调用下一任务，如如发现任务如果发现请求资源不够，则调用扩展资源函数，如果发现当前资源利用率小于50%,调用资源减少函数

#include <iostream>
#include </usr/include/mysql/mysql.h>
//#include <sql/mysql.h>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <ctime>
#include <list>

using namespace std;
int totalcores;
int cores_available;
class calc_task;
list<calc_task> task_list;
int user_list[2048];//to simplify, as a demo, we think that our user amount won't be more than 2048
int user_numb;
std::list<calc_task>::iterator it1;

#define MTASK_WAITTING  0
#define MTASK_RUNNING   1
#define MTASK_KILLED    3
#define MTASK_ABORTED  -1
#define MTASK_FINISHED  2
#define MTASK_AHEADED   5
#define MTASK_HANGUP    6

#define MPROG_RUN       1
#define MPROG_KILL      2
#define MPROG_PACK      3
#define MPROG_FINISH    4

#define enlarge() cores_available=totalcores;//improve later
#define reduce();//cores_availabe=( (cores_available/2) > totalcores)? cores_available/2 :totalcores;

class calc_task{

    pid_t pid;
    int start_time;
    int finish_time;
    FILE *nutdf;
public:
    int status;//构造时设为MTASK_WAITTING
    int serial;
    int task_mark;
    //int predict_time;
    int cores;
    int time;
    int type;
    char name[1024];
    int user;

#define paraset(a) user_list[this->user] a 1;totalcores a this->cores;
    int change_task_status(int i)
    {
        //this requires sql;!!!!
    }
    int getcmd(int type,char *cmd)
    {
        //this program will run another programs(not the qe itself),the program will detect if the qe normally exited or not.
        //char ...;//system settings...
        switch(type)
        {
            case MPROG_RUN:     ;break;
            case MPROG_KILL:    ;break;
            case MPROG_PACK:    ;break;
            case MPROG_FINISH:  ;break;
        }
    }
    int start()
    {
        char cmd[1024];
        nutdf=popen("/usr/bin/nut","w");
        //submit message to the nut deamon.
        fprintf(nutdf,"%ld%ld%ld%ld\n",this->serial,this->cores,this->type);
        fflush(nutdf);
        //
       // this->start_time=time(0);
        paraset(+=);
        if(cores_available<totalcores)
        {
            enlarge();
        }
        this->change_task_status(MTASK_RUNNING);
    //attention:finish function is runing in the main program!
    }
    int kill()
    {
        char cmd[1024];
        //submit
        fprintf(nutdf,"c\n");
        fflush(nutdf);
        //
        paraset(-=);
        this->change_task_status(MTASK_KILLED);
        this->clean();
    }
    int unexpectabort()
    {
        paraset(-=);
        this->change_task_status(MTASK_ABORTED);
    }
    int finish()
    {
        this->clean();
        this->pack();

        this->time=this->finish_time-this->start_time;
        this->change_task_status(MTASK_FINISHED);
    }
    int pack()
    {
        //nutdeamon will finish the first step of package
        char cmd[1024];
        this->getcmd(MPROG_PACK,cmd);
        //popen("");//unfinished
    }
    int clean()
    {
        ;//this function will be written later.
    }
};

//this requires sql;
//check_finished should be earlier running than this function.
//check the current user mount, and how many users requires the calculating now.
//build a chain list for each "live" user's current task and insert the current possible task for each user,then running it.
//attention! there may will be a delay between the database server and the calculating server.
//if resources are limited, expand,or, if current resources available is 50% percent more than the resources used, call reduce function.
int get_current_task(MYSQL *mysqldb)
{
    int i;
    char sql_cmd[2048];
    list<calc_task> task_require;
    calc_task ttask;
    MYSQL_RES *sql_result;
    MYSQL_ROW *sql_result_row;
    MYSQL_FIELD *sql_result_field;
    //std::list<calc_task>::iterator it2;
    //...
    //first, any user should have at least one task running immediately after submit,
    //and it should follow the submit order.
    //second, if their is any extra cores, first, we should finish the works. if their is no extra work(all work finished, be careful), call the reduce function.
    //首先，轮询当前任务已完成的用户（user_list[i]=0）
        ///add into task_require;
        for(i=1;i<user_numb;i++)
        {
            if(user_list[i])
                continue;
            sprintf(sql_cmd,"SELECT TOP 0 * FROM task_list where user=%ld\
 and cancel_state=0 and (running_state=%ld or running_state=%ld)",i,MTASK_WAITTING,MTASK_HANGUP);
            mysql_query(mysqldb,sql_cmd);
            sql_result=mysql_store_result(mysqldb);
            sql_result_row=mysql_fetch_row(sql_result);
            ///...
            sscanf(sql_result_row[1],"%ld%ld%ld%ld",&(ttask.serial),&(ttask.user),&ttask.cores);//this has some problem
            ttask.start();
            task_list.push_back(task);
            mysql_free_result(sql_result);
        }
        //有机会的话重构这一段
        //for(it1=task_require.begin();it1!=task_require.end();it1++)
       // {
        //    it1->start();
       //     task_list.push_back(*it1);
       // }
       // task_require.clear();
        //--
    if(totalcores<cores_available)
    {
        while(totalcores<cores_available)
        {
                //int task_added=0;
                sprintf(sql_cmd,"SELECT * FROM task_list where\
 and cancel_state=0 and (running_state=%ld or running_state=%ld)\
 and cores<%ld",i,MTASK_WAITTING,MTASK_HANGUP,cores_available-totalcores);
                mysql_query(mysqldb,sql_cmd);
                sql_result=mysql_store_result(mysqldb);
                sql_result_row=mysql_fetch_row(sql_result);
                //如有空余资源，首先轮询所有可能任务并加入
                //有机会的话重构这一段
                for(it1=task_require.begin();it1!=task_require.end();it1++)
                {
                    it1->start();
                    task_list.push_back(*it1);
                    task_added++;
                }
                task_require.clear();
                //--
        }
            while(totalcores<cores_available)
            {
                sprintf(sql_cmd,"SELECT TOP 10 * FROM task_list where user=%ld and cancel_state=0 and running_state=%ld",i,MTASK_WAITTING);
                mysql_query(mysqldb,sql_cmd);
                sql_result=mysql_store_result(mysqldb);
                int i;
                while(sql_result_row=mysql_fetch_row(sql_result)&&totalcores<cores_available)
                {
                    sscanf(sql_result_ro2w[1],"%ld%ld%ld%ld",&(ttask.serial),&(ttask.user),&ttask.cores);//this has some problem;
                    ttask.start();
                    task_list.push_back(task);
                }
                mysql_free_result(sql_result);
        //如有空余资源，首先轮询所有可能任务并加入
            //有机会的话重构这一段
            }
            //--
        //如发现无任务可加入，检查是否需要缩减资源开销
        if(cores_available/2>totalcores)
        {
            reduce();
            break;
        }
    }

}

//check if there is a finished/aborted/wait_to_be_killed(!this is different with MTASK_KILLED state) program.(the aborted program will have a "failed" file)
//finish all the things should do, after that, the get_current_task() will wipe out the task variables.
int check_if_finished(MYSQL &mysqldb)
{

    //task_list *tp,*tpp;
   char s[2048],cmd[2048];
    FILE *t;
    int i,finish_type,leaf=0;
    //std::list<calc_task>::iterator it2;

    for(it1=task_list.begin();it1!=task_list.end();it1++)
   // tpp=&task_list_header;//header(the first guy in the list) will not storage the real task. because it sould not be changed.
   // while(tp=enum_task(tpp))
    {
        sprintf(s,"//tmp//nutd//%ld.finish",it1->serial);
        if(t=fopen(s,"r"))

        {
            leaf=1;
            //it means that the nut has already finished
            fscanf(t,"%d",&finish_type);
            fclose(t);
            switch(finish_type)
            {
                case MTASK_ABORTED:it1->unexpectabort();break;
                case MTASK_FINISHED:it1->finish();break;
            }
            it1->finish();
            task_list.erase(it1);
        }
      //  else tpp=tp;
    }

    //停止所有waitting_to_be_cancelled 任务。首先检测任务是否已经开始，是否已经结束，然后...
    //wait_to_be_cancelled 与运行状态属于两个字段，不阻塞
    //
    //查出所有已经运行了的需要取消的任务
     sprintf(sql_cmd,"SELECT * FROM task_list where\
 and cancel_state=1 and running_state=%ld or running_state=%ld)"
 ,i,MTASK_WAITTING,MTASK_HANGUP);
    mysql_query(mysqldb,sql_cmd);
    sql_result=mysql_store_result(mysqldb);
    sql_result_row=mysql_fetch_row(sql_result);
    ///...

    //查出所有未运行需要取消的任务
    sprintf(sql_cmd,"SELECT * FROM task_list where\
 and cancel_state=1 and running_state=%ld or running_state=%ld)"
 ,i,MTASK_WAITTING,MTASK_HANGUP);
    mysql_query(mysqldb,sql_cmd);
    sql_result=mysql_store_result(mysqldb);
    sql_result_row=mysql_fetch_row(sql_result);
    //...

    return leaf;
}

int main(int argc, char **argv)
{
    int i;

    const char *host = "localhost";
    const char *user = "root";
    const char *pass = "123456";
    const char *db   = "test";

    MYSQL mysqldb;
    MYSQL_RES *result;
    MYSQL_ROW sql_row;
    MYSQL_FIELD *fd;

    mysql_init(&mysqldb);

    if (!mysql_real_connect(&mysqldb, host, user, pass, db, 0, NULL, 0))
    {
        printf("%s", mysql_error(&mysqldb));
    }
    while(1)
    {
        sleep(1000);
        if(check_if_finished(&mysqldb))
            get_current_task(&mysqldb);
    }
   // printf("HelloWorld!");
    return 0;
}

<commit_msg>change the main core<commit_after>//使用链表存储相应所有正在计算的task，按用户分队列计算，每0.1s进行一次检查操作，如果发现任务已完成，则调用下一任务，如如发现任务如果发现请求资源不够，则调用扩展资源函数，如果发现当前资源利用率小于50%,调用资源减少函数

#include <iostream>
#include </usr/include/mysql/mysql.h>
//#include <sql/mysql.h>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <ctime>
#include <list>

using namespace std;
int totalcores;
int cores_available;
class calc_task;
list<calc_task> task_list;
int user_list[2048];//to simplify, as a demo, we think that our user amount won't be more than 2048
int user_numb;
std::list<calc_task>::iterator it1;

#define MTASK_WAITTING  0
#define MTASK_RUNNING   1
#define MTASK_KILLED    3
#define MTASK_ABORTED  -1
#define MTASK_FINISHED  2
#define MTASK_AHEADED   5
#define MTASK_HANGUP    6

#define MPROG_RUN       1
#define MPROG_KILL      2
#define MPROG_PACK      3
#define MPROG_FINISH    4

#define enlarge() cores_available=totalcores;//improve later
#define reduce();//cores_availabe=( (cores_available/2) > totalcores)? cores_available/2 :totalcores;

class calc_task{

    pid_t pid;
    int start_time;
    int finish_time;
    FILE *nutdf;
public:
    int status;//构造时设为MTASK_WAITTING
    int serial;
    int task_mark;
    //int predict_time;
    int cores;
    int time;
    int type;
    char name[1024];
    int user;

#define paraset(a) user_list[this->user] a 1;totalcores a this->cores;
    int change_task_status(int i)
    {
        //this requires sql;!!!!
    }
    int getcmd(int type,char *cmd)
    {
        //this program will run another programs(not the qe itself),the program will detect if the qe normally exited or not.
        //char ...;//system settings...
        switch(type)
        {
            case MPROG_RUN:     ;break;
            case MPROG_KILL:    ;break;
            case MPROG_PACK:    ;break;
            case MPROG_FINISH:  ;break;
        }
    }
    int start()
    {
        char cmd[1024];
        nutdf=popen("/usr/bin/nut","w");
        //submit message to the nut deamon.
        fprintf(nutdf,"%ld%ld%ld%ld\n",this->type,this->cores,this->serial);
        fflush(nutdf);
        //
       // this->start_time=time(0);
        paraset(+=);
        if(cores_available<totalcores)
        {
            enlarge();
        }
        this->change_task_status(MTASK_RUNNING);
    //attention:finish function is runing in the main program!
    }
    int kill()
    {
        char cmd[1024];
        //submit
        fprintf(nutdf,"c\n");
        fflush(nutdf);
        //
        paraset(-=);
        this->change_task_status(MTASK_KILLED);
        this->clean();
    }
    int unexpectabort()
    {
        paraset(-=);
        this->change_task_status(MTASK_ABORTED);
    }
    int finish()
    {
        this->clean();
        this->pack();

        this->time=this->finish_time-this->start_time;
        this->change_task_status(MTASK_FINISHED);
    }
    int pack()
    {
        //nutdeamon will finish the first step of package
        char cmd[1024];
        this->getcmd(MPROG_PACK,cmd);
        //popen("");//unfinished
    }
    int clean()
    {
        ;//this function will be written later.
    }
};

//this requires sql;
//check_finished should be earlier running than this function.
//check the current user mount, and how many users requires the calculating now.
//build a chain list for each "live" user's current task and insert the current possible task for each user,then running it.
//attention! there may will be a delay between the database server and the calculating server.
//if resources are limited, expand,or, if current resources available is 50% percent more than the resources used, call reduce function.
int get_current_task(MYSQL *mysqldb)
{
    int i;
    char sql_cmd[2048];
    list<calc_task> task_require;
    calc_task ttask;
    MYSQL_RES *sql_result;
    MYSQL_ROW *sql_result_row;
    MYSQL_FIELD *sql_result_field;
    //std::list<calc_task>::iterator it2;
    //...
    //first, any user should have at least one task running immediately after submit,
    //and it should follow the submit order.
    //second, if their is any extra cores, first, we should finish the works. if their is no extra work(all work finished, be careful), call the reduce function.
    //首先，轮询当前任务已完成的用户（user_list[i]=0）
        ///add into task_require;
        for(i=1;i<user_numb;i++)
        {
            if(user_list[i])
                continue;
            sprintf(sql_cmd,"SELECT TOP 0 * FROM task_list where user=%ld\
 and cancel_state=0 and (running_state=%ld or running_state=%ld)",i,MTASK_WAITTING,MTASK_HANGUP);
            mysql_query(mysqldb,sql_cmd);
            sql_result=mysql_store_result(mysqldb);
            sql_result_row=mysql_fetch_row(sql_result);
            ///...
            sscanf(sql_result_row[1],"%ld%ld%ld%ld",&(ttask.serial),&(ttask.user),&ttask.cores);//this has some problem
            ttask.type=1;
            ttask.start();
            task_list.push_back(task);
            mysql_free_result(sql_result);
        }
        //有机会的话重构这一段
        //for(it1=task_require.begin();it1!=task_require.end();it1++)
       // {
        //    it1->start();
       //     task_list.push_back(*it1);
       // }
       // task_require.clear();
        //--
    if(totalcores<cores_available)
    {
        while(totalcores<cores_available)
        {
                //int task_added=0;
                sprintf(sql_cmd,"SELECT * FROM task_list where\
 and cancel_state=0 and (running_state=%ld or running_state=%ld)\
 and cores<%ld",i,MTASK_WAITTING,MTASK_HANGUP,cores_available-totalcores);
                mysql_query(mysqldb,sql_cmd);
                sql_result=mysql_store_result(mysqldb);
                sql_result_row=mysql_fetch_row(sql_result);

                sscanf(sql_result_row[1],"%ld%ld%ld%ld",&(ttask.serial),&(ttask.user),&ttask.cores);//this has some problem
                ttask.type=1;
                ttask.start();
                task_list.push_back(task);
                mysql_free_result(sql_result);

                //如有空余资源，首先轮询所有可能任务并加入
                //有机会的话重构这一段
               // for(it1=task_require.begin();it1!=task_require.end();it1++)
                {
                  //  it1->start();
                   // task_list.push_back(*it1);
                   // task_added++;
                }
                task_require.clear();
                //--
        }
            while(totalcores<cores_available)
            {
                sprintf(sql_cmd,"SELECT TOP 10 * FROM task_list where user=%ld and cancel_state=0 and running_state=%ld",i,MTASK_WAITTING);
                mysql_query(mysqldb,sql_cmd);
                sql_result=mysql_store_result(mysqldb);
                int i;
                while(sql_result_row=mysql_fetch_row(sql_result)&&totalcores<cores_available)
                {
                    sscanf(sql_result_ro2w[1],"%ld%ld%ld%ld",&(ttask.serial),&(ttask.user),&ttask.cores);//this has some problem;
                    ttask.start();
                    task_list.push_back(task);
                }
                mysql_free_result(sql_result);
        //如有空余资源，首先轮询所有可能任务并加入
            //有机会的话重构这一段
            }
            //--
        //如发现无任务可加入，检查是否需要缩减资源开销
        if(cores_available/2>totalcores)
        {
            reduce();
            break;
        }
    }

}

//check if there is a finished/aborted/wait_to_be_killed(!this is different with MTASK_KILLED state) program.(the aborted program will have a "failed" file)
//finish all the things should do, after that, the get_current_task() will wipe out the task variables.
int check_if_finished(MYSQL &mysqldb)
{

    //task_list *tp,*tpp;
   char s[2048],cmd[2048];
    FILE *t;
    int i,finish_type,leaf=0;
    //std::list<calc_task>::iterator it2;

    for(it1=task_list.begin();it1!=task_list.end();it1++)
   // tpp=&task_list_header;//header(the first guy in the list) will not storage the real task. because it sould not be changed.
   // while(tp=enum_task(tpp))
    {
        sprintf(s,"//tmp//nutd//%ld.finish",it1->serial);
        if(t=fopen(s,"r"))

        {
            leaf=1;
            //it means that the nut has already finished
            fscanf(t,"%d",&finish_type);
            fclose(t);
            switch(finish_type)
            {
                case MTASK_ABORTED:it1->unexpectabort();break;
                case MTASK_FINISHED:it1->finish();break;
            }
            it1->finish();
            task_list.erase(it1);
        }
      //  else tpp=tp;
    }

    //停止所有waitting_to_be_cancelled 任务。首先检测任务是否已经开始，是否已经结束，然后...
    //wait_to_be_cancelled 与运行状态属于两个字段，不阻塞
    //
    //查出所有已经运行了的需要取消的任务
     sprintf(sql_cmd,"SELECT * FROM task_list where\
 and cancel_state=1 and running_state=%ld or running_state=%ld)"
 ,i,MTASK_WAITTING,MTASK_HANGUP);
    mysql_query(mysqldb,sql_cmd);
    sql_result=mysql_store_result(mysqldb);
    sql_result_row=mysql_fetch_row(sql_result);
    ///...

    //查出所有未运行需要取消的任务
    sprintf(sql_cmd,"SELECT * FROM task_list where\
 and cancel_state=1 and running_state=%ld or running_state=%ld)"
 ,i,MTASK_WAITTING,MTASK_HANGUP);
    mysql_query(mysqldb,sql_cmd);
    sql_result=mysql_store_result(mysqldb);
    sql_result_row=mysql_fetch_row(sql_result);
    //...

    return leaf;
}

int main(int argc, char **argv)
{
    int i;

    const char *host = "localhost";
    const char *user = "root";
    const char *pass = "123456";
    const char *db   = "test";

    MYSQL mysqldb;
    MYSQL_RES *result;
    MYSQL_ROW sql_row;
    MYSQL_FIELD *fd;

    mysql_init(&mysqldb);

    if (!mysql_real_connect(&mysqldb, host, user, pass, db, 0, NULL, 0))
    {
        printf("%s", mysql_error(&mysqldb));
    }
    while(1)
    {
        sleep(1000);
        if(check_if_finished(&mysqldb))
            get_current_task(&mysqldb);
    }
   // printf("HelloWorld!");
    return 0;
}

<|endoftext|>


<commit_before>c98baaf8-4b02-11e5-8ce3-28cfe9171a43<commit_msg>more bug fix<commit_after>c99c6d85-4b02-11e5-8ab0-28cfe9171a43<|endoftext|>


<commit_before>/*

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org>

 */

#include <iostream>
#include <queue>
#include <set>

using namespace std;
int target[2][4];
bool visited[8][8][8][8][8][8][8][8];

struct config{
    int body[2][4], step;
    char ans[50];
};

bool checkv(config a)
{
    return !visited[a.body[0][0]-1][a.body[0][1]-1][a.body[0][2]-1][a.body[0][3]-1][a.body[1][0]-1][a.body[1][1]-1][a.body[1][2]-1][a.body[1][3]-1];
}

void markv(config a)
{
    visited[a.body[0][0]-1][a.body[0][1]-1][a.body[0][2]-1][a.body[0][3]-1][a.body[1][0]-1][a.body[1][1]-1][a.body[1][2]-1][a.body[1][3]-1]=true;
}

config coma(config a)
{
    int i, tem;
    for(i=0;i<4;i++)
        tem=a.body[0][i], a.body[0][i]=a.body[1][i], a.body[1][i]=tem;
    a.ans[a.step++]='A';
    return a;
}

config comb(config a)
{
    int i, tem[2];
    tem[0]=a.body[0][3], tem[1]=a.body[1][3];
    for(i=3;i>=1;i--)
        a.body[0][i]=a.body[0][i-1], a.body[1][i]=a.body[1][i-1];
    a.body[0][0]=tem[0], a.body[1][0]=tem[1];
    a.ans[a.step++]='B';
    return a;
}

config comc(config a)
{
    int tem=a.body[0][1];
    a.body[0][1]=a.body[1][1], a.body[1][1]=a.body[1][2], a.body[1][2]=a.body[0][2], a.body[0][2]=tem;
    a.ans[a.step++]='C';
    return a;
}

bool check(config a)
{
    int i, j;
    for(i=0;i<2;i++)
        for(j=0;j<4;j++)
            if(a.body[i][j]!=target[i][j])
                return false;
    return true;
}

int main()
{
    queue<config> m;
    config in, out;
    int i, j;

    for(j=0;j<4;j++)
        cin >> target[0][j];
    for(j=3;j>=0;j--)
        cin >> target[1][j];
    in.body[0][0]=1, in.body[0][1]=2, in.body[0][2]=3, in.body[0][3]=4, in.body[1][3]=5, in.body[1][2]=6, in.body[1][1]=7, in.body[1][0]=8;
    in.step=0, m.push(in), markv(in);

    while(!m.empty()){
        out=m.front(), m.pop();
        if(check(out))
            break;
        if(checkv(coma(out)))
            m.push(coma(out)), markv(coma(out));
        if(checkv(comb(out)))
            m.push(comb(out)), markv(comb(out));
        if(checkv(comc(out)))
            m.push(comc(out)), markv(comc(out));
    }

    cout << out.step << endl;
    for(i=0;i<out.step;i++)
        cout << out.ans[i];
    if(out.step!=0)
        cout << endl;

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


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>

#define MAXBUF 1024

#ifdef MASTER

#include <sys/time.h>
#include <vector>
#define HOSTPORT 31415
#define MAXCLIENTS 10

#else

#include <Mandelbrot.h>
#define HOSTPORT "31415"
#define HOSTADDR "10.3.14.15"

#endif

using namespace std;

int main()
{
    struct sockaddr_in addr;
    int sock;
    char buf[MAXBUF + 1];

    #ifdef MASTER

    int clients[MAXCLIENTS];
    fd_set fds;

    for (int i = 0; i < MAXCLIENTS; i++) clients[i] = 0;
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        printf("Could not create socket: %d\n", errno);
        return -1;
    }

    int opt = 1;
    if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(int)) < 0)
    {
        printf("Could not set socket options: %d\n", errno);
        return -1;
    }

    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(HOSTPORT);

    if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0)
    {
        printf("Could not bind port: %d\n", errno);
        return -1;
    }

    printf("Listening on port %d\n", HOSTPORT);

    if (listen(sock, 5) < 0)
    {
        printf("Could not listen: %d\n", errno);
        return -1;
    }

    int addrlen = sizeof(addr);
    printf("Waiting for connections\n");

    #else

    struct addrinfo hints, *serv;
    memset(&hints, 0, sizeof(hints));

    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;

    int ret = getaddrinfo(HOSTADDR, HOSTPORT, &hints, &serv);
    if (ret != 0)
    {
        printf("Could not get address info: %s\n", gai_strerror(ret));
        return -1;
    }

    struct addrinfo *i;
    for (i = serv; i != NULL; i = i->ai_next)
    {
        if ((sock = socket(i->ai_family, i->ai_socktype, i->ai_protocol)) == -1)
        {
            printf("Could not create socket: %d\n", errno);
            continue;
        }

        if (connect(sock, i->ai_addr, i->ai_addrlen) < 0)
        {
            close(sock);
            printf("Could not connect to host: %d\n", errno);
            continue;
        }

        break;
    }

    if (i == NULL)
    {
        printf("Could not connect\n");
        return -1;
    }

    printf("Connecting to %s:%d\n", inet_ntoa(((struct sockaddr_in*)i)->sin_addr), ntohs(((struct sockaddr_in*)i)->sin_port));

    freeaddrinfo(serv);

    #endif

    while (true)
    {
        #ifdef MASTER

        FD_ZERO(&fds);

        FD_SET(sock, &fds);
        int ms = sock;
        for (int i = 0; i < MAXCLIENTS; i++)
        {
            int s = clients[i];
            if (s > 0) FD_SET(s, &fds);
            if (s > ms) ms = s;
        }

        int activity = select(ms + 1, &fds, NULL, NULL, NULL);

        if (activity < 0 && errno != EINTR) printf("'select' error\n");

        if (FD_ISSET(sock, &fds))
        {
            int newsock = accept(sock, (struct sockaddr*)&addr, (socklen_t*)&addrlen);
            if (newsock < 0)
            {
                printf("Could not accept client\n");
                return -1;
            }

            printf("New connection from %s:%d\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));

            char* msg = "You have just connected to Master Pi!\n";
            int msglen = strlen(msg);
            if (send(newsock, msg, msglen, 0) != msglen) printf("Could not send message\n");
            else printf("Greeted %s\n", inet_ntoa(addr.sin_addr));

            for (int i = 0; i < MAXCLIENTS; i++)
            {
                if (clients[i] == 0)
                {
                    clients[i] = newsock;
                    printf("Client %d added to list\n", i);
                    break;
                }
            }
        }

        for (int i = 0; i < MAXCLIENTS; i++)
        {
            int s = clients[i];
            if (FD_ISSET(s, &fds))
            {
                int val = read(s, buf, MAXBUF);
                getpeername(s, (struct sockaddr*)&addr, (socklen_t*)&addrlen);
                if (val == 0)
                {
                    printf("Client %s disconnected\n", inet_ntoa(addr.sin_addr));
                    close(s);
                    clients[i] = 0;
                }
                else
                {
                    buf[val - 2] = 0;
                    printf("-> %s: \"%s\"\n", inet_ntoa(addr.sin_addr), buf);
                    char* msg = "Received message\n";
                    send(s, msg, strlen(msg), 0);
                }
            }
        }

        #else

        ret = recv(sock, buf, MAXBUF, 0);
        if (ret < 0)
        {
            printf("Error receiving message");
            return -1;
        }

        buf[ret] = 0;
        printf("Server: \"%s\"\n", buf);

        #endif
    }

    close(sock);
}
<commit_msg>Fixed HOSTADDR IP<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>

#define MAXBUF 1024

#ifdef MASTER

#include <sys/time.h>
#include <vector>
#define HOSTPORT 31415
#define MAXCLIENTS 10

#else

#include <Mandelbrot.h>
#define HOSTPORT "31415"
#define HOSTADDR "10.3.14.5"

#endif

using namespace std;

int main()
{
    struct sockaddr_in addr;
    int sock;
    char buf[MAXBUF + 1];

    #ifdef MASTER

    int clients[MAXCLIENTS];
    fd_set fds;

    for (int i = 0; i < MAXCLIENTS; i++) clients[i] = 0;
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        printf("Could not create socket: %d\n", errno);
        return -1;
    }

    int opt = 1;
    if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(int)) < 0)
    {
        printf("Could not set socket options: %d\n", errno);
        return -1;
    }

    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(HOSTPORT);

    if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0)
    {
        printf("Could not bind port: %d\n", errno);
        return -1;
    }

    printf("Listening on port %d\n", HOSTPORT);

    if (listen(sock, 5) < 0)
    {
        printf("Could not listen: %d\n", errno);
        return -1;
    }

    int addrlen = sizeof(addr);
    printf("Waiting for connections\n");

    #else

    struct addrinfo hints, *serv;
    memset(&hints, 0, sizeof(hints));

    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;

    int ret = getaddrinfo(HOSTADDR, HOSTPORT, &hints, &serv);
    if (ret != 0)
    {
        printf("Could not get address info: %s\n", gai_strerror(ret));
        return -1;
    }

    struct addrinfo *i;
    for (i = serv; i != NULL; i = i->ai_next)
    {
        if ((sock = socket(i->ai_family, i->ai_socktype, i->ai_protocol)) == -1)
        {
            printf("Could not create socket: %d\n", errno);
            continue;
        }

        if (connect(sock, i->ai_addr, i->ai_addrlen) < 0)
        {
            close(sock);
            printf("Could not connect to host: %d\n", errno);
            continue;
        }

        break;
    }

    if (i == NULL)
    {
        printf("Could not connect\n");
        return -1;
    }

    printf("Connecting to %s:%d\n", inet_ntoa(((struct sockaddr_in*)i)->sin_addr), ntohs(((struct sockaddr_in*)i)->sin_port));

    freeaddrinfo(serv);

    #endif

    while (true)
    {
        #ifdef MASTER

        FD_ZERO(&fds);

        FD_SET(sock, &fds);
        int ms = sock;
        for (int i = 0; i < MAXCLIENTS; i++)
        {
            int s = clients[i];
            if (s > 0) FD_SET(s, &fds);
            if (s > ms) ms = s;
        }

        int activity = select(ms + 1, &fds, NULL, NULL, NULL);

        if (activity < 0 && errno != EINTR) printf("'select' error\n");

        if (FD_ISSET(sock, &fds))
        {
            int newsock = accept(sock, (struct sockaddr*)&addr, (socklen_t*)&addrlen);
            if (newsock < 0)
            {
                printf("Could not accept client\n");
                return -1;
            }

            printf("New connection from %s:%d\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));

            char* msg = "You have just connected to Master Pi!\n";
            int msglen = strlen(msg);
            if (send(newsock, msg, msglen, 0) != msglen) printf("Could not send message\n");
            else printf("Greeted %s\n", inet_ntoa(addr.sin_addr));

            for (int i = 0; i < MAXCLIENTS; i++)
            {
                if (clients[i] == 0)
                {
                    clients[i] = newsock;
                    printf("Client %d added to list\n", i);
                    break;
                }
            }
        }

        for (int i = 0; i < MAXCLIENTS; i++)
        {
            int s = clients[i];
            if (FD_ISSET(s, &fds))
            {
                int val = read(s, buf, MAXBUF);
                getpeername(s, (struct sockaddr*)&addr, (socklen_t*)&addrlen);
                if (val == 0)
                {
                    printf("Client %s disconnected\n", inet_ntoa(addr.sin_addr));
                    close(s);
                    clients[i] = 0;
                }
                else
                {
                    buf[val - 2] = 0;
                    printf("-> %s: \"%s\"\n", inet_ntoa(addr.sin_addr), buf);
                    char* msg = "Received message\n";
                    send(s, msg, strlen(msg), 0);
                }
            }
        }

        #else

        ret = recv(sock, buf, MAXBUF, 0);
        if (ret < 0)
        {
            printf("Error receiving message");
            return -1;
        }

        buf[ret] = 0;
        printf("Server: \"%s\"\n", buf);

        #endif
    }

    close(sock);
}
<|endoftext|>


<commit_before>a9dbdbdc-ad5b-11e7-a3e6-ac87a332f658<commit_msg>Fixed that one bug<commit_after>aa45adca-ad5b-11e7-b4cd-ac87a332f658<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <pcap/pcap.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/if_ether.h>
#include <ctime>

int main(int argc, char **argv) {
    /**
     * This should not all be in the main function but I'm just trying to get
     * a POC out the door for now.
     */
    int i;
    char *dev;
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t* descr;
    const u_char *packet;
    struct pcap_pkthdr hdr;
    struct ether_header *eptr;

    u_char *ptr;

    dev = pcap_lookupdev(errbuf);

    if (getuid()) {
        printf("%s", "Arper must be run as root.\n");
        return 1;
    }

    if(dev == NULL) {
        printf("%s\n",errbuf);
        exit(1);
    }

    printf("Capturing on device: %s\n", dev);

    descr = pcap_open_live(dev,BUFSIZ,0,-1,errbuf);

    if(descr == NULL) {
        printf("pcap_open_live(): %s\n",errbuf);
        exit(1);
    }

    packet = pcap_next(descr,&hdr);

    if(packet == NULL) {
        printf("Didn't grab packet\n");
        exit(1);
    }

    printf("Grabbed packet of length %d\n", hdr.len);
    printf("Recieved at ..... %s\n", ctime((const time_t*)&hdr.ts.tv_sec));
    printf("Ethernet address length is %d\n", ETHER_HDR_LEN);

    eptr = (struct ether_header *) packet;

    if (ntohs (eptr->ether_type) == ETHERTYPE_IP) {
        printf("Ethernet type hex:%x dec:%d is an IP packet\n",
                ntohs(eptr->ether_type),
                ntohs(eptr->ether_type));
    }
    else if (ntohs (eptr->ether_type) == ETHERTYPE_ARP) {
        printf("Ethernet type hex:%x dec:%d is an ARP packet\n",
                ntohs(eptr->ether_type),
                ntohs(eptr->ether_type));
    }
    else {
        printf("Ethernet type %x not IP", ntohs(eptr->ether_type));
        exit(1);
    }

    ptr = eptr->ether_dhost;
    i = ETHER_ADDR_LEN;
    printf(" Destination Address:  ");
    do {
        printf("%s%x",(i == ETHER_ADDR_LEN) ? " " : ":",*ptr++);
    }
    while(--i>0);
    printf("\n");

    ptr = eptr->ether_shost;
    i = ETHER_ADDR_LEN;
    printf("Source Address:  ");

    do{
        printf("%s%x",(i == ETHER_ADDR_LEN) ? " " : ":",*ptr++);
    }
    while(--i>0);
    printf("\n");

    return 0;
}
<commit_msg>More recent GCC versions removed some autoloading so unistd's headers are needed<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <pcap/pcap.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/if_ether.h>
#include <ctime>
#include <unistd.h>

int main(int argc, char **argv) {
    /**
     * This should not all be in the main function but I'm just trying to get
     * a POC out the door for now.
     */
    int i;
    char *dev;
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t* descr;
    const u_char *packet;
    struct pcap_pkthdr hdr;
    struct ether_header *eptr;

    u_char *ptr;

    dev = pcap_lookupdev(errbuf);

    if (getuid()) {
        printf("%s", "Arper must be run as root.\n");
        exit(1);
    }

    if(dev == NULL) {
        printf("%s\n", errbuf);
        exit(1);
    }

    printf("Capturing on device: %s\n", dev);

    descr = pcap_open_live(dev, BUFSIZ, 0, -1, errbuf);

    if(descr == NULL) {
        printf("pcap_open_live(): %s\n", errbuf);
        exit(1);
    }

    packet = pcap_next(descr,&hdr);

    if(packet == NULL) {
        printf("Didn't grab packet\n");
        exit(1);
    }

    printf("Grabbed packet of length %d\n", hdr.len);
    printf("Recieved at ..... %s\n", ctime((const time_t*)&hdr.ts.tv_sec));
    printf("Ethernet address length is %d\n", ETHER_HDR_LEN);

    eptr = (struct ether_header *) packet;

    if (ntohs (eptr->ether_type) == ETHERTYPE_IP) {
        printf("Ethernet type hex:%x dec:%d is an IP packet\n",
                ntohs(eptr->ether_type),
                ntohs(eptr->ether_type));
    }
    else if (ntohs (eptr->ether_type) == ETHERTYPE_ARP) {
        printf("Ethernet type hex:%x dec:%d is an ARP packet\n",
                ntohs(eptr->ether_type),
                ntohs(eptr->ether_type));
    }
    else {
        printf("Ethernet type %x not IP", ntohs(eptr->ether_type));
        exit(1);
    }

    ptr = eptr->ether_dhost;
    i = ETHER_ADDR_LEN;
    printf(" Destination Address:  ");
    do {
        printf("%s%x",(i == ETHER_ADDR_LEN) ? " " : ":",*ptr++);
    }
    while(--i>0);
    printf("\n");

    ptr = eptr->ether_shost;
    i = ETHER_ADDR_LEN;
    printf("Source Address:  ");

    do{
        printf("%s%x",(i == ETHER_ADDR_LEN) ? " " : ":",*ptr++);
    }
    while(--i>0);
    printf("\n");

    return 0;
}
<|endoftext|>


<commit_before>62c05b7d-2749-11e6-b536-e0f84713e7b8<commit_msg>having coffee<commit_after>62dc00de-2749-11e6-89ef-e0f84713e7b8<|endoftext|>