Ejemplo n.º 1
0
Archivo: main.cpp Proyecto: jdG-/taquin
int				main(int argc, char ** argv)
{
	Puzzle *	puzzle = NULL;
	Display *	display = NULL;

	if (argc > 4 || argc < 3 || strcmp(argv[1], "-g"))
	{
		std::cout << "Usage " << argv[0] << " -g greedness [filename]" << std::endl;
		return (EXIT_SUCCESS);
	}
	try
	{
		srand(time(NULL));
		Puzzle::_greedness = (atoi(argv[2]) > 0) ? atoi(argv[2]) : 1;
		if (argc == 4)
			puzzle = new Puzzle(argv[3]);
		else if (argc == 3)
			puzzle = new Puzzle();
		puzzle->isSolvable();
		display = new Display(puzzle);
		display->render();
	}
	catch (std::exception & e)
	{
		std::cout << e.what() << std::endl;
	}
	if (display)
		delete display;
	return (EXIT_SUCCESS);
}
Ejemplo n.º 2
0
int manhattan(const Puzzle& state, const Puzzle& solution) {
    int result = -1;

    /*
     * These loops compare two vectors piece by piece,
     * finding the row and column indeces for corresponding
     * pieces, and adding the magnitudes of the differences.
     *
     * This is presently O(n^2).
     * TODO: investigate O(n) solution
     */
    if(state.get_width() == solution.get_width()) {
        size_t width = state.get_width();
        int i = 0;
        for(TileIt it1 = state.tiles.begin(); it1 != state.tiles.end(); it1++, i++) {
            if(*it1 != 0) {

                int j = 0;
                for(TileIt it2 = solution.tiles.begin(); *it1 != *it2; it2++, j++);

                int r1 = i / width;
                int r2 = j / width;
                int c1 = i % width;
                int c2 = j % width;

                result += abs(r2 - r1) + abs(c2 - c1);
            }
        }
    }

    return result;
}
Ejemplo n.º 3
0
Game CustomGame::createGame(int difficulty, int symmetry) {
	if (! createSKGraphObject()) {
	    return Game();
	}
	Puzzle* puzzle = new Puzzle(m_graph, true);
	puzzle->init(difficulty, symmetry);

	return Game(puzzle);
}
Ejemplo n.º 4
0
Game CustomGame::startEmpty() {
	if (! createSKGraphObject()) {
	    return Game();
	}
	Puzzle* puzzle = new Puzzle(m_graph, false);
	puzzle->init();

	return Game(puzzle);
}
Ejemplo n.º 5
0
int								main(int argc, char **argv)
{
    char Name = 'M';
    std::string taq = "TaquinA5_2.txt";
    if (argc == 3)
    {
        std::ifstream infile;
        infile.open(argv[2]);
        if (!infile.is_open())
        {
            std::cout << "Error: file <" << argv[2] << ">" << " not found" << std::endl;
            return (-1);
        }
        infile.close();
        taq = argv[2];
        FileLoader				F;
        std::string				S;
        Puzzle					P;
        SolutionGenerator		SG;
        short unsigned int**	Tab;
        clock_t					timeDeb, timeEnd;
        std::list<Puzzle>		OpenedList, ClosedList;
        int x = 0, y = 0, fg = -42;

        timeDeb = clock();
        DisplayLogo();
        F.LoadFile(taq.c_str(), S);
        std::istringstream		In(S);
        P.SetAlgo(Name);
        Tab = P.CreatePuzzle(S);
        std::list<Puzzle>::iterator FirstPuzzle;
        OpenedList.push_back(P);
        while (fg != 0 && !OpenedList.empty())
        {
            FirstPuzzle = OpenedList.begin();
            fg = Resume(FirstPuzzle, OpenedList, ClosedList, timeEnd);
            ProcessUp(FirstPuzzle, OpenedList, ClosedList);
            ProcessDown(FirstPuzzle, OpenedList, ClosedList);
            ProcessRight(FirstPuzzle, OpenedList, ClosedList);
            ProcessLeft(FirstPuzzle, OpenedList, ClosedList);

            (*FirstPuzzle).ClearListTab();
            ClosedList.push_back(*FirstPuzzle);
            OpenedList.erase(FirstPuzzle);
        }
        if (fg != 0)
            std::cout << "NO SOLUTION FOR THIS TAQUIN!!!" << std::endl;
        std::cout << "CLOSED LIST NUMBER OF CONTENTS	: \t\t[" << ClosedList.size() << "]"<< std::endl;
        std::cout << "TIME ELAPSED			: \t\t[" << static_cast<double>(timeEnd - timeDeb) << "] ms." << std::endl;
        ShowNbMoves();
        std::cout << "Cleaning..." << std::endl;
        Clean(OpenedList, ClosedList);
        std::cout << "Clean done" << std::endl;
    }
    return (0);
}
Ejemplo n.º 6
0
int main(int argc, char** argv)
{
    freopen("CON", "w", stdout); // redirects stdout because SDL redirects it to a file.

    /* Parsing the input parameters. */
    if (argc < 6)
    {
        std::cout << "Missing some input parametr. Needed at least 5 but got only " << argc - 1 << std::endl;
        return -1;
    }

	if (!initGraphics(RESX, RESY)) return -1;
	renderScene();
	displayVFB(vfb);

    try
	{
		Puzzle puzzle;
		if (!puzzle.loadMap(argv[1]))
			throw "Something is wrong with the map file!";

        puzzle.setMonsterAndFoodCoords(fromStringToInt(argv[2]), fromStringToInt(argv[3]), fromStringToInt(argv[4]), fromStringToInt(argv[5]));

        // The flag for the SDL visualization
        if (argc >= 7)
        {
            puzzle.setVisualizationFlag(fromStringToInt(argv[6]));
        }

        // The flag for the SDL visualization
        if (argc >= 8)
        {
            puzzle.setDelay(fromStringToInt(argv[7]));
        }
		puzzle.printMap(std::cout);
		puzzle.solveAndVizualize(std::cout);
		puzzle.visualizeThePath();
		puzzle.basicVisualizePath(std::cout);
		puzzle.printFormatedPath(std::cout);

	}
	catch (const char * msg)
	{
		std::cout << "Error: " << msg << std::endl;
	}
	catch (const string msg)
	{
		std::cout << "Error: " << msg << std::endl;
	}


	waitForUserExit();
	closeGraphics();
	return 0;
}
Ejemplo n.º 7
0
Game RoxdokuGame::createGame(int difficulty, int symmetry) {
	if(!m_graph) {
		m_graph = new SKGraph(m_order, TypeRoxdoku);
		m_graph->initRoxdoku();
	}

	Puzzle* puzzle = new Puzzle(m_graph, true);
	puzzle->init(difficulty, symmetry);

	return Game(puzzle);
}
Ejemplo n.º 8
0
Game RoxdokuGame::startEmpty() {
	if(!m_graph) {
		m_graph = new SKGraph(m_order, TypeRoxdoku);
		m_graph->initRoxdoku();
	}

	Puzzle* puzzle = new Puzzle(m_graph, false);
	puzzle->init();

	return Game(puzzle);
}
Ejemplo n.º 9
0
int main(int argc, char** argv)
{
    Puzzle test;
    Puzzle fit;
    srand(time(NULL));

    cin >> test;
    GeneticAlgorithm tryit(test, atoi(argv[1]), atoi(argv[2]));
    //GeneticAlgorithm tryit(test, POPSIZE, MAXGENS);
    fit = tryit.evolve();
    fit.display();
    cout << "Fitness: " << fit.fitness() << endl;

    return (EXIT_SUCCESS);
}
Ejemplo n.º 10
0
/*
 * These are the three examined heuristic functions.
 * displaced(...) counts how many tiles are out of place
 * manhattan(...) determines how far away each tile is from
 * its correct location, as specified in the solution.
 * sumdisman(...) simply sums displaced(...) and manhattan(...).
 */
int displaced(const Puzzle& state, const Puzzle& solution) {
    int result = -1;

    if(state.get_width() == solution.get_width()) {
        result = 0;

        for(TileIt it1 = state.tiles.begin(), it2 = solution.tiles.begin(); it1 != state.tiles.end(); it1++, it2++) {
            if(*it1 != 0 && *it1 != *it2) {
                result++;
            }
        }
    }

    return result;
}
Ejemplo n.º 11
0
void PuzzlesDraw(const Puzzle & pzl, const Surface & sf, s16 dstx, s16 dsty)
{
    Display & display = Display::Get();
    Cursor & cursor = Cursor::Get();

    // show all for debug
    if(IS_DEVEL()) return;

    u8 alpha = 250;
    u32 ticket = 0;
    LocalEvent & le = LocalEvent::Get();
    while(le.HandleEvents() && 0 < alpha)
    {
        if(Game::ShouldAnimateInfrequent(ticket, 1))
        {
    	    cursor.Hide();
	    display.Blit(sf, dstx, dsty);
	    for(size_t ii = 0; ii < pzl.size(); ++ii)
	    {
    		const Sprite & piece = AGG::GetICN(ICN::PUZZLE, ii);
		if(pzl.test(ii))
		{
		    Surface fade(piece.w(), piece.h());
		    fade.SetColorKey();
		    fade.Blit(piece);
		    fade.SetAlpha(alpha);
		    if(Settings::Get().QVGA())
		    display.Blit(fade, dstx + 8 + piece.x() - BORDERWIDTH, dsty + 8 + piece.y() - BORDERWIDTH);
		    else
		    display.Blit(fade, dstx + piece.x() - BORDERWIDTH, dsty + piece.y() - BORDERWIDTH);
		}
		else
		{
		    if(Settings::Get().QVGA())
		    display.Blit(piece, dstx + 8 + piece.x() - BORDERWIDTH, dsty + 8 + piece.y() - BORDERWIDTH);
		    else
		    display.Blit(piece, dstx + piece.x() - BORDERWIDTH, dsty + piece.y() - BORDERWIDTH);
		}
	    }
	    cursor.Show();
    	    display.Flip();
    	    alpha -= 10;
	}

	++ticket;
    }
    cursor.Hide();
}
Ejemplo n.º 12
0
void ZoneOpenRandomTiles(Puzzle & pzl, u8 & opens, const u8* it1, const u8* it2)
{
    std::vector<u8> values;
    values.reserve(25);
    const u8* it = NULL;

    while(opens)
    {
	values.clear();
	it = it1;
	while(it && it2 && it <= it2){ if(! pzl.test(*it)) values.push_back(*it); ++it; }
	if(values.empty()) break;
	pzl.set(*Rand::Get(values));
	--opens;
    }
}
Ejemplo n.º 13
0
void printAndSolve( Puzzle sudoku ) {

  cout << "\nThe given puzzle looks like this: \n\n";

  sudoku.printBoard();

  if (!sudoku.solve()) {
    printf("Cannot solve puzzle\n");
    exit(0);
  }
    
  cout << "\n\nThe solved puzzle looks like this: \n\n";

  sudoku.printBoard();
  cout << "\n\n";
}
Ejemplo n.º 14
0
inline GridPoint* PuzzleSolverInterface::getMostConstrainedHole(
        const int* remainingShapeList,
        int numRemainingShapes,
        bool estimate)
{
    return puzzle->getMostConstrainedHole(remainingShapeList, numRemainingShapes, estimate);
}
Ejemplo n.º 15
0
void outputExpanding(Puzzle puzzle)
{
    printf("The best state to expand is ...:\n");
    puzzle.output();
    printf("Expanding this node..\n");

}
Ejemplo n.º 16
0
void System::Reset()
{
    GameOver = false;
    GameLevel = 1;
    GameScore = 0;
    GameSpeed = GAME_STARTING_SPEED;
    s_puzzle.Reset();
}
Ejemplo n.º 17
0
int main(){
   Puzzle sudoku;
   cin >> sudoku;
   cout << "Unsolved Puzzle:" << endl;
   sudoku.display();
   cout << endl;
   //Solve returns true if solved, false if not.
   if (sudoku.solve(0, 0)) {
      cout << "Solved Puzzle:" << endl;
      sudoku.display();
      cout << endl;
   }
   else {
      cout << "Puzzle is unsolvable." << endl;
   }
   return 0;
}
Ejemplo n.º 18
0
void System::Start()
{
    if (GameOver)
    {
        System::Reset();
    }

    s_puzzle.Start();
}
Ejemplo n.º 19
0
int RunPuzzleSolver(int argc, char **argv)
{ 
    printf("usage: RunPuzzleSolver fnameBoard heuristic tmax fnameMoves\n");
    
    const char  *fnameIn = argc > 1 ? argv[1] : "puzzle.txt";
    const char  *hname   = argc > 2 ? argv[2] : NULL;
    const double tmax    = argc > 3 ? atof(argv[3]) : 3.0;
    const char  *fnameOut= argc > 4 ? argv[4] : "moves.txt";
    

    printf("..using fnameBoard = %s\n", fnameIn);
    printf("..using heuristic  = %s\n", hname);
    printf("..using tmax       = %f\n", tmax);
    printf("..using fnameMoves = %s\n", fnameOut);
     
    Puzzle puzzle;
    Puzzle::Board *b = puzzle.ReadBoard(fnameIn);
    PuzzleSolver solver;
    PuzzleHeuristic *h = NULL;
    std::vector<Puzzle::Move> moves;
    
    
    if(hname == NULL)
	h = new PuzzleHeuristic();
    else if(strcmp(hname, "H1") == 0)
	h = new PuzzleHeuristic1();
    else if(strcmp(hname, "H2") == 0)
	h = new PuzzleHeuristic2();
    else if(strcmp(hname, "H3") == 0)
	h = new PuzzleHeuristic3();
    
   
    Utils::Timer::Clock clk;

    Utils::Timer::Start(&clk);
    const bool solved = solver.Solve(&puzzle,  h, b, tmax, &moves);
    printf("..solved = %d nrMoves = %d time = %f\n", solved, (int) moves.size(), Utils::Timer::Elapsed(&clk));

    printf("..checking solution\n");
    for(int i = 0; i < (int) moves.size(); ++i)
	puzzle.MakeMove(b, moves[i]);
    if(puzzle.IsSolved(b) == false)
    {
	printf("..did not reach goal configuration, see\n");
	puzzle.PrintBoard(NULL, b);
    }
    else 
	printf("..ok\n");
    
    
    puzzle.PrintMoves(fnameOut, &moves);
    
    
    puzzle.DeleteBoard(b);
    delete h;
    
    
    return 0;
}
Ejemplo n.º 20
0
Puzzle PuzzleGenerator::GeneratePuzzle()
{
	timer.StartTimer();
	maxtime = 58.0; // to make sure we don't exceed a minute

	// Declare variables for Simulated Annealing Algorithm
	double startingTemp;
	double alpha;
	double epsilon;

	// Determine if puzzle is "large" or not (so we can adjust how the algorithm performs)
	if (nRows*nColumns >= 80 || nRows*nColumns*(maxVal - minVal - 1) > 500)
	{
		startingTemp = 100;
		alpha = 0.9999;
		epsilon = 0.001;
	}
	else 
	{
		startingTemp = 100;
		alpha = 0.999;
		epsilon = 0.001;
	}


	Puzzle startingPuzzle(nRows, nColumns, minVal, maxVal);

	Puzzle bestPuzzle = SimulatedAnnealing_Exp(startingPuzzle, startingTemp, alpha, epsilon);
	int i = 0;

	while (timer.GetElapsedTime() < maxtime)
	{
		startingPuzzle = Puzzle(nRows, nColumns, minVal, maxVal);
		Puzzle p = SimulatedAnnealing_Exp(startingPuzzle, startingTemp, alpha, epsilon);
		if (p.GetValue() > bestPuzzle.GetValue())
		{
			bestPuzzle = p;
		}
		i++;
	}

	return bestPuzzle;

}
Ejemplo n.º 21
0
Puzzle PuzzleGenerator::SimulatedAnnealing_Linear(Puzzle p, double temp_start, double delta, double epsilon)
{
	// Function that uses simulated annealing algorithm to find best value puzzle.
	// TEMP_START = initial temperature
	// DELTA = amount that temperature decreases per iteration
	// returns the best puzzle found 

	Puzzle current = p;

	// Keep track of the time so we don't exceed it.
	Timer t;
	t.StartTimer();
	
	int i = 0; // iteration counter (for debugging)
	double temperature = temp_start;

	while (temperature > epsilon)
	{
		//printf ("\nSIMULATED ANNEALING ITERATION %i\n", i);


		// get random successor
		Puzzle successor = current.GetRandomSuccessor();
		//printf ("current value = %i\n", current.GetValue());
		//printf ("successor value = %i\n", successor.GetValue());
		//printf ("temperature = %f\n", temperature);

		// if successor is a "good" move accept it
		if (successor.GetValue() > current.GetValue())
		{
			//printf("successor value > current value...ACCEPTED!\n");
			current = successor;
		}
		else // otherwise accept the move with probability of e^(deltaE/temperature)
		{
			int deltaE = successor.GetValue() - current.GetValue(); // calculate delta E
			//printf("deltaE = %i\n", deltaE);
			double randVal = (rand() % 1000) / 1000.0; // generate random value between (0,1)
			//printf("randVal = %f\n", randVal);
			double thresh = exp(deltaE/temperature);
			//printf("thresh = %f\n", thresh);
			if (randVal < thresh)
			{
				//printf("successor value randomly ACCEPTED\n");
				current = successor;
			}
		}
		

		// cool temperature each iteration
		temperature -= delta;

		// increment iteration counter
		i++;

	}
	
	return current;
}
Ejemplo n.º 22
0
int
main( int argc, char** argv )
{
  if ( argc < 2 )
  {
    std::cerr << "Usage: " << argv[0] << " <puzzle.txt>" << std::endl;
    return 1;
  }

  Puzzle* puzzle = new Puzzle( argv[1] );
  puzzle->print();

  Solver* solver = new Solver;
  solver->solve( *puzzle, true );

  delete solver;
  delete puzzle;
  return 0;
}
Ejemplo n.º 23
0
bool PartialSolver::partiallyCorrect(Puzzle& puzzle)
{
    for(int row=0; row<number; row++)
    {
        if(puzzle.row[row].first!=0)
        {
            vector<SkyScraper*> left = puzzle.getRow(row);
            if(puzzle.row[row].first<partiallyFinished(left))
            {
                return false;
            }
        }
        if(puzzle.row[row].second!=0)
        {
            vector<SkyScraper*> right = puzzle.getRow(row,true);
            if(puzzle.row[row].second<partiallyFinished(right))
            {
                return false;
            }
        }
    }
    for(int col=0; col<number; col++)
    {
        if(puzzle.col[col].first!=0)
        {
            vector<SkyScraper*> top = puzzle.getColumn(col);
            if(puzzle.col[col].first<partiallyFinished(top))
            {
                return false;
            }
        }
        if(puzzle.col[col].second!=0)
        {
            vector<SkyScraper*> bottom = puzzle.getColumn(col,true);
            if(puzzle.col[col].second<partiallyFinished(bottom))
            {
                return false;
            }
        }
    }
    return true;
}
Ejemplo n.º 24
0
void PartialSolver::solve()
{
    while(!puzzles.empty())
    {
        Puzzle& front = puzzles.front();
        ///Clear points to find points for next puzzle
        points.clear();
        findPoints(front.puzzle);
        list< pair<int,int> >::iterator it = points.begin();
        for(;it!=points.end(); it++)
        {
            int row = (*it).first;
            int col = (*it).second;
            Puzzle back = Puzzle(front);
            try
            {
                back.set(row, col, variable);
                back.solve();
                if(back.complete())
                {
                    if(back.correct())
                    {
                            solved.push_back(back);
                    }
                    else
                    {
                            incorrect.push_back(back);
                    }
                }
                else
                {
                    ///If the puzzle is still partially correct continue search
                    if(partiallyCorrect(back))
                        puzzles.push_back(back);
                }
            } catch (bool& value) {
                //incorrect.push_back(back);
            }
        }
        puzzles.pop_front();
    }
}
Ejemplo n.º 25
0
Archivo: c++.cpp Proyecto: mkut/aoj
	void d(Puzzle p)
	{
		for(int i = 0; i < p.size(); i++)
		{
			for(int j = 0; j < p[i].size(); j++)
			{
				printf("%5d", p[i][j]);
			}
			cout << endl;
		}
	}
Ejemplo n.º 26
0
// Utility for run solver and profiling
static void SolvePuzzle(Puzzle& p) {
  std::chrono::time_point<HighResClock> start, end;
  start = HighResClock::now();
  PuzzleSolver ps(p, 1);
  ps.Solve();
  end = HighResClock::now();
  auto ms = std::chrono::duration_cast<MilliSecond>(end - start);
  std::cout << p.GetName() << " solved in " << ms.count() << " ms" << std::endl;

  // Draw the first solution
  ps.GetPaths()[0].Draw();
}
Ejemplo n.º 27
0
Puzzle *Puzzle::moveLeft(){
	
	Puzzle *p = new Puzzle(*this);
	
	
   if(x0 > 0){
		
		p->board[y0][x0] = p->board[y0][x0-1];
		p->board[y0][x0-1] = 0;
		
		p->x0--;
		
		p->path = path + "L";
		p->pathLength = pathLength + 1;  
		p->depth = depth + 1; //incorrect
		
	}
	p->strBoard = p->toString();
	return p;
	
}
Ejemplo n.º 28
0
Puzzle *Puzzle::moveUp(){
	
	Puzzle *p = new Puzzle(*this);
	
	
   if(y0 > 0){
		
		p->board[y0][x0] = p->board[y0-1][x0];
		p->board[y0-1][x0] = 0;
		
		p->y0--;
		
		p->path = path + "U";
		p->pathLength = pathLength + 1;  
		p->depth = depth + 1;
		
	}
	p->strBoard = p->toString();
	return p;
	
}
Ejemplo n.º 29
0
Puzzle *Puzzle::moveDown(){
	
	Puzzle *p = new Puzzle(*this);
	
	
   if(y0 < 2){
		
		p->board[y0][x0] = p->board[y0+1][x0];
		p->board[y0+1][x0] = 0;
		
		p->y0++;
		
		p->path = path + "D";
		p->pathLength = pathLength + 1;  
		p->depth = depth + 1;
		
	}
	p->strBoard = p->toString();	
	return p;
	
}
Ejemplo n.º 30
0
void Puzzle::raiseBlocks(CCNode* sender, void* pData)
{
	Puzzle *p = (Puzzle *)pData;
	
	if (p->extraction->max >= p->numsprites) {
		for (int i = 0; i < p->numsprites; i++)
		{
			int rnumb = p->extraction->extract();
			int randX = rnumb % p->numCellX;
			int randY = rnumb / p->numCellX;
			
			p->cellpos[i].set(randX, randY);
		}
		
		for (int i = 0; i < p->numsprites; i++) {
			p->cell[i]->setDisplayFrame(p->cellframe);
			p->cell[i]->setPosition(ccp(dimX*p->cellpos[i].x, dimY*p->cellpos[i].y));
			p->layer->addChild(p->cell[i]);
			
			//action transition
			p->cell[i]->setScale(0.1);
			CCScaleTo *scaleup = CCScaleTo::actionWithDuration(0.25, 1);
			CCAction *scaleup_ = CCEaseElasticOut::actionWithAction(scaleup);
			p->cell[i]->runAction(scaleup_);
		}
		
		//schedule
		CCFiniteTimeAction *scheduled_action = CCSequence::actions(CCDelayTime::actionWithDuration(p->t_duration),
																   CCCallFuncND::actionWithTarget(p->layer, callfuncND_selector(Puzzle::lowerBlocks), pData),
																   NULL);
		p->layer->runAction(scheduled_action);
	}
	else
	{
		p->drawResultImage();
		//cells over
	}
}