Exemplo n.º 1
0
    /**
     * @brief generate
     */
    sPointer generate() const
    {
        assert(lhs && rhs);
        sPointer lcs = std::make_shared<Range>();

        //! lambda to do the real work
        using Lambda = std::function<void(SizeType, SizeType)>;
        Lambda build_lcs = [&lcs, &build_lcs, this](SizeType l, SizeType r)
        {
            //! stop condition
            if(l == 0 || r == 0)    return;

            //! recur
            if((*lhs)[l - 1]    ==  (*rhs)[r - 1])
            {
                build_lcs(l - 1, r - 1);
                lcs->push_back((*lhs)[l - 1]);
            }
            else if (maze(l - 1, r) >= maze(l, r - 1))
                build_lcs(l - 1, r);
            else
                build_lcs(l, r - 1);
        };

        //! call the lambda
        build_lcs(lhs->size(),rhs->size());
        return lcs;
    }
Exemplo n.º 2
0
MazeGen::MazeGen(void)
{
	// Seed the random number generator
	srand(time(NULL));

	// Initialize mazeArray to all unvisited cells
        for(int i = 0; i < Width; i++)
	{	
                for(int j = 0; j < Height; j++)
		{
			mazeArray[i][j].x = i;
			mazeArray[i][j].y = j;
		}
	}
	
	// Set the size and bit depth of maze
	maze.SetSize(Width, Height);
	maze.SetBitDepth(8);

	// Initialize each pixel in maze to black
	for(int i = 0; i < maze.TellWidth(); i++)
	{
		for(int j = 0; j < maze.TellHeight(); j++)
		{
			maze(i, j)->Blue = 0;
			maze(i, j)->Green = 0;
			maze(i, j)->Red = 0;
		}
	}
}
Exemplo n.º 3
0
void solve_maze()
{
    if (false == g_from_std)
    {
        if (FALSE == check_file(g_input_file)) {
            exit(1);
        }
        ifstream fin(g_input_file);
        MazeData maze(fin);
        run_search(maze);
    } else {
        MazeData maze(std::cin);
        run_search(maze);
    }
}
void Chapter9Test::Test9_2() {
  ofstream fout;
  OpenLogFile(fout,"test9_2.html", "Problem 9.2: count all possible paths that makes a robot moves from (0, 0) to (X, Y)");

  Chapter9::Maze maze({{Chapter9::Maze::path, Chapter9::Maze::path},{Chapter9::Maze::path,Chapter9::Maze::path}});
  TestBasic(fout, "X = 2, Y = 2", maze.countAllPossiblePaths(), 2ul);
  TestMatrix(fout, "Print Paths", maze.findAllPossiblePaths(), maze.findAllPossiblePaths());
  ;
  maze.GenerateMaze({{0,0,0},{0,0,0},{0,0,0}});
  TestBasic(fout, "X = 3, Y = 3", maze.countAllPossiblePaths(), 6ul);
  TestMatrix(fout, "Print Paths", maze.findAllPossiblePaths(), maze.findAllPossiblePaths());

  maze.GenerateMaze({{0,0,0},{0,1,0},{0,0,0}});
  TestBasic(fout, "X = 3, Y = 3", maze.countAllPossiblePaths(), 2ul);
  TestMatrix(fout, "Print Paths", maze.findAllPossiblePaths(), maze.findAllPossiblePaths());

  maze.GenerateMaze({{0,0,0},{0,0,1},{0,0,0}});
  TestBasic(fout, "X = 3, Y = 3", maze.countAllPossiblePaths(), 3ul);
  TestMatrix(fout, "Print Paths", maze.findAllPossiblePaths(), maze.findAllPossiblePaths());

  maze.GenerateMaze({{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}});
  TestBasic(fout, "X = 3, Y = 3", maze.countAllPossiblePaths(), 20ul);
  TestMatrix(fout, "Print Paths", maze.findAllPossiblePaths(), maze.findAllPossiblePaths());

  maze.GenerateMaze({{0,0,0,0},{0,0,0,1},{0,0,0,0},{0,0,0,0}});
  TestBasic(fout, "X = 3, Y = 3", maze.countAllPossiblePaths(), 16ul);
  TestMatrix(fout, "Print Paths", maze.findAllPossiblePaths(), maze.findAllPossiblePaths());

  CloseLogFile(fout);
}
Exemplo n.º 5
0
int main()
{
    int t;
    int m, n;
    scanf("%d", &t);
    for (int i = 0; i < t; i++)
    {
        scanf("%d %d", &m, &n);
        Maze maze(m, n);
        char line[n+1];
        for (int k = 0; k < m; k++)
        {
            scanf("%s", line);
            strcpy(maze.mz_[k], line);
        }
        maze.initMaze();
        maze.solveMaze();
        if (maze.nom == 0)
        {
            printf("Case #%d: impossible\n", i+1);
        } else
        {
            printf("Case #%d: %d\n", i+1, maze.nom - 1);
        }
        maze.printMaze();
    }
    return 0;
}
Exemplo n.º 6
0
int main (int argc, const char * argv[])
{
	int m,n,i,j;
	   	
	

	while(scanf("%d %d",&m,&n) != EOF){
		char *s1;
		int **tabela;
		int **solution;
	

		tabela = (int**) malloc(m*sizeof(int*));
		for (i = 0; i < m; i++) {
			tabela[i] = (int*)malloc((n+3)*sizeof(int));
		}

		solution = (int**) malloc(m*n*sizeof(int*));
		for (i = 0; i < m*n; i++) {
			solution[i] = (int*)malloc(4*sizeof(int));
		}

		
		
		z=0;

		for(i=0;i<m;i++){
			tabela[i][0] = 5;
			tabela[i][n+2] = 5;
		}

		for(i=0;i<m;i++){
			s1 = malloc(sizeof(char)*(n+2));
			scanf("%s",s1);
			for(j=1;j<n+1;j++){
				tabela[i][j] = (int)s1[j-1]%10;
			}			
		}

		int found;
	
		for(i=1;i<n+1;i++){
			found = maze(m-1,0,i,tabela,solution);
			if (found==1) break;
		}
		
		
		
		if (found == 1){
			for (i=z;i>1;i--)
				printf("(%d,%d),",solution[i][0]+1,solution[i][1]);
			printf("(%d,%d)",solution[1][0]+1,solution[1][1]);
			printf("\n");
		}else{
			printf("No Path!\n");
		}
    	}

    	return 0;
}
Exemplo n.º 7
0
int main(int argc, char* argv[]){

  std::string maze_file;
  if (argc < 2) {
    maze_file = "../mazes/16x16.mz";
  }
  else {
    maze_file = std::string(argv[1]);
  }

  std::fstream fs;
  fs.open(maze_file, std::fstream::in);

  if (fs.good()){
    ConsoleMaze maze(fs);
    ConsoleMouse::inst()->seedMaze(&maze);
    ConsoleTimer timer;
    Command::setTimerImplementation(&timer);
    Scheduler scheduler(new StepSolveCommand(new Flood(ConsoleMouse::inst())));

    while (true) {
      scheduler.run();
    }

    fs.close();
    return EXIT_SUCCESS;
  }
  else {
		printf("error opening maze file!\n");
    fs.close();
    return EXIT_FAILURE;
  }
}
Exemplo n.º 8
0
//---------------------------------------------------------------
void main()
{
   int i,j;
   clrscr();

   for(i=0;i<9;i++)     // flush all the arrays
      for(j=0;j<9;j++)
	 cnt = arr[i][j] = stat[i][j] = puzz[i][j] = hnt[i][j] = 0;

   int gd=DETECT,gm;
   initgraph(&gd, &gm,path);

   if(LOAD)  loading();

   clrscr();
   initgraph(&gd, &gm,path);

   setbkcolor(BLACK);
   rectangle(0,27,637,477);
   setfillstyle(1,BLUE);
   floodfill(25,30,15);
   frame(20,100,90,460,LIGHTRED,RED,GREEN);

   _1.draw();   _4.draw();   _7.draw();
   _2.draw();   _5.draw();   _8.draw();
   _3.draw();   _6.draw();   _9.draw();
   _ER.draw();

   ext_button();
   menubar();
   maze();
   fill_maze();
   Control();
}
Exemplo n.º 9
0
int main(int argc, char * argv[]) {
    MazeDefinitions::MazeEncodingName mazeName = MazeDefinitions::MAZE_CAMM_2012;
    bool pause = false;

    // Since Windows does not support getopt directly, we will
    // have to parse the command line arguments ourselves.

    // Skip the program name, start with argument index 1
    for(int i = 1; i < argc; i++) {
        if(strcmp(argv[i], "-m") == 0 && i+1 < argc) {
            int mazeOption = atoi(argv[++i]);
            if(mazeOption < MazeDefinitions::MAZE_NAME_MAX && mazeOption > 0) {
                    mazeName = (MazeDefinitions::MazeEncodingName)mazeOption;
            }
        } else if(strcmp(argv[i], "-p") == 0) {
            pause = true;
        } else {
            std::cout << "Usage: " << argv[0] << " [-m N] [-p]" << std::endl;
            std::cout << "\t-m N will load the maze corresponding to N, or 0 if invalid N or missing option" << std::endl;
            std::cout << "\t-p will wait for a newline in between cell traversals" << std::endl;
            return -1;
        }
    }

    LeftWallFollower leftWallFollower(pause);
    Maze maze(mazeName, &leftWallFollower);
    std::cout << maze.draw(5) << std::endl << std::endl;

    maze.start();
}
Exemplo n.º 10
0
int main() {//1로시작
	int i, j;
	input();
	graph[col][1] = 1; //꼭해주기!!!!!!!!!!
	enqueue((col * 10000) + 1);
	maze();
	
}
Exemplo n.º 11
0
void begin_controller() {
    MazeDefinitions::MazeEncodingName mazeName = MazeDefinitions::MAZE_CAMM_2012;
    bool pause = true;
    
    FloodFillFinder floodFill(pause);
    Maze maze(mazeName, &floodFill);
    
    maze.start();
}
Exemplo n.º 12
0
void gen_maze()
{
    if (g_from_std == false) {
        if (FALSE == check_file(g_input_file)) {
            exit(1);
        }

        FILE * fp = fopen(g_input_file, "rb");
        if (NULL == fp) {
            cerr << "read file: " << g_input_file << " failed.\n";
            exit(1);
        }
        Maze maze(fp, g_height, g_width, g_top, g_bottom, g_left, g_right);
        maze.build();
    } else {
        Maze maze(stdin, g_height, g_width, g_top, g_bottom, g_left, g_right);
        maze.build();
    }
}
Exemplo n.º 13
0
int main(int argc, char** argv)
{
    zhonxSettings.maze_end_coordinate.x = 8;
    zhonxSettings.maze_end_coordinate.y = 8;
    zhonxSettings.color_sensor_enabled = false;
    zhonxSettings.cell_cost = 5;
    zhonxSettings.wall_know_cost = 2;
    zhonxSettings.start_orientation = 0;

    // initialize SDL videolabel
    if (SDL_Init( SDL_INIT_VIDEO) < 0)
    {
        printf("Unable to init SDL: %s\n", SDL_GetError());
        return 1;
    }

    // make sure SDL cleans up before exit
    atexit(SDL_Quit);

    // create a new window
    screen = SDL_SetVideoMode(128 * multiplicateur, 64 * multiplicateur, 16,
            SDL_HWSURFACE | SDL_DOUBLEBUF);
    if (!screen)
    {
        printf("Unable to set 640x480 video: %s\n", SDL_GetError());
        return 1;
    }

    // load an image
    SDL_Surface* bmp = SDL_LoadBMP("PacaBot-2.bmp");
    if (!bmp)
    {
        printf("Unable to load bitmap: %s\n", SDL_GetError());
        return 1;
    }

    // centre the bitmap on screen
    SDL_Rect dstrect;
    dstrect.x = (screen->w - bmp->w) / 2;
    dstrect.y = (screen->h - bmp->h) / 2;
    SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 0, 0, 0));

    // draw bitmap
    SDL_SetColorKey(bmp, SDL_SRCCOLORKEY,
            SDL_MapRGB(bmp->format, 255, 255, 255));
    SDL_BlitSurface(bmp, 0, screen, &dstrect);
    SDL_FreeSurface(bmp);
    SDL_Flip(screen);
    pause();
    maze();
    SDL_Quit();
    // all is well ;)
    printf("Exited cleanly\n");
    return 0;
}
int main(void){
	maze_t maze(40,40);
	agent_t robot(maze);
	std::cout << "Using strategy: breadth" << std::endl;
	unsigned seed = common::random();
	//unsigned seed = 742982606;
	std::cout << "Using seed: " << seed << std::endl;
	maze.generate(seed);
	robot.solve(algorithm::breadth);
	std::cout << maze << std::endl;
}
Exemplo n.º 15
0
int main(int argc, const char *argv[]) {
    if( argc != 2 ){ //checks for the input file name
		std::cerr << "Error: no input file name" << std::endl;
		std::cerr << "Usage: ./" << argv[0] << " someinput.txt" << std::endl;
		return 1;
	}

	std::ifstream mazeInputFile ( argv[1] );	// open the input file
	int numberOfMazes = 0;
    mazeInputFile >> numberOfMazes; 			// read the number of mazes
    
    for (int currentMaze = 0; currentMaze < numberOfMazes; currentMaze++ ) {
        int mazeSize = 0;
        mazeInputFile >> mazeSize;				// read the maze size from the input file
        
        Utils mazeUtils(mazeSize, mazeInputFile); // helper class for testing, output
        if (mazeSize < 10 || mazeSize > 30) {
            std::cerr << "Error: invalid maze size " << mazeSize << " read from " << argv[1] << std::endl;
            std::cerr << "Maze sizes must be between 10 and 30" << std::endl;
            return 1;
        }
        
		// Create a new maze object of the given size
		Maze maze(mazeSize);
        
		// Initialize the maze
		maze.readFromFile(mazeInputFile);

		int row, col;
        
        do {
            
            // Get current location of 'x' in the maze
            maze.getCurrentPosition(row, col);

            // Advance one step in the maze
            maze.step();
            
        } while ( ! maze.atExit() );

        mazeUtils.reset();
        
    } // currentMaze
    
    
};
Exemplo n.º 16
0
int main(void) {
	factorial_recursive();
	fib_main();
	combinator_main();
	fn_main();
	gcd_main();
	gcd_main2();
	generate_perm();
	generate_perm2();
	hanoi_main();
	hanoi_main2();
	maze();
	maze2();
	maze3();
	maze4();
	quick_main();
	quick_main2();
    printf("end");
	return EXIT_SUCCESS;
}
Exemplo n.º 17
0
int build_world()
{
//  fill(0,5,BLACK);
//  fill(8,8,COAL);
//  fill(11,11,COAL);
//  fill(14,14,STONE);
  fill(17, 17,STONE);
  fill(21, 21,STONE);
  perlin(21, 30,STONE);
  perlin(25, 75,DIRT);
  cover(GREEN);
  fill_lakes(40);
  mark(45, 44,RED);
  mark(44, 45,RED); 
  mark(46, 45,RED);
  mark(45, 46,RED);
  maze(18, 20);
  cut(45, 45, 18);  
  return 0;
}
Exemplo n.º 18
0
int main(int argc,char *argv[]) {

    png::rgb_pixel black = png::rgb_pixel(0,0,0);

    //default resolution
    int xres=1920;
    int yres=1080;
    //default size of the pixel
    int pixsize=10;
    // 0 - Original colors, 100 - Complete desaturation
    int saturation=0;
    //Color multiplier value
    int colormult=1;
    //seed
    int seed=time(NULL);

    //if wallstrue equals zero then there will be no walls, else there will be walls
    int wallstrue=1;
    char * name="maze.png";
    //true if user picks the colors
    bool setColor=false;
    std::string userColor;

    for (int i=1;i<argc;i++)
    {
	std::string flag=argv[i];
	if (flag=="-w"||flag=="--width")
	    xres=std::stoi(argv[i+1]);
	if (flag=="-h"||flag=="--height")
	    yres=std::stoi(argv[i+1]);
	if (flag=="-p"||flag=="--pixel-size")
	    pixsize=std::stoi(argv[i+1]);
	if (flag=="-b"||flag=="--walls")
	    wallstrue=std::stoi(argv[i+1]);
	if (flag=="-n"||flag=="--file-name")
	    name=argv[i+1];
	if (flag=="-d"||flag=="--desaturation")
	    saturation=std::stoi(argv[i+1]);
	if (flag=="-t"||flag=="--color-multiplier")
	    colormult=std::stoi(argv[i+1]);
	if (flag=="-s"||flag=="--seed")
	    seed=std::stoi(argv[i+1]);
	if (flag=="-c"||flag=="--set-color")
	    {
		setColor=true;
		userColor=argv[i+1];
	    }


    }

    //ignores drawing walls if pixel size is 1
    if (pixsize==1)
	wallstrue=0;

    Draw xwin(pixsize,xres,yres);

    int xblocks=xwin.screenwidth/xwin.pixwidth-1;
    int yblocks=xwin.screenheight/xwin.pixwidth-1;

    Maze maze(xblocks,yblocks);

    maze.startCreation(seed);

    maze.nextStep();

    int colors[6];

    if (setColor==false)
    {

    for (int i=0;i<6;i++) {
	colors[i]=rand()%256;
    }

    double distance =sqrt(  pow((colors[0]-colors[3]),2) + pow((colors[1]-colors[4]),2) + pow((colors[3]-colors[5]),2));

    while (distance<200|distance>300) {
	for (int i=0;i<6;i++)
	    colors[i]=rand()%256;
	distance =sqrt(  pow((colors[0]-colors[3]),2) + pow((colors[1]-colors[4]),2) + pow((colors[3]-colors[5]),2));
    }

    desaturate(saturation / 100.0, &colors[0], &colors[1], &colors[2]);
    desaturate(saturation / 100.0, &colors[3], &colors[4], &colors[5]);

    }
    else
    {
	for (int i=0;i<12;i+=2)
	{
	    unsigned int col;
	    std::stringstream ss;
	    ss << std::hex << std::string(userColor.begin()+i,userColor.begin()+i+2);
	    ss >> col;
	    colors[i/2]=col;
	}
	
    }

    maze.drawValues(&xwin,colors[0],colors[1],colors[2],colors[3],colors[4],colors[5],colormult);

    if (wallstrue!=0) {
	//horizontal
	drawWall(maze.wall.horwalls,maze.wall.width,maze.wall.height,&xwin,black,1.0,1.0/2.0,0);
	//verticle
	drawWall(maze.wall.vertwalls,maze.wall.width+1,maze.wall.height-1,&xwin,black,1.0/2.0,1.0,1);

    }

    xwin.writePng(name);

    return 0;
}
Exemplo n.º 19
0
int maze(int maxlevel, int x, int y, int **tabela, int **solution){
	
	int symbol;

	symbol = tabela[x][y];

	/*
	if (symbol == 4){ printf("|\n");}
	if (symbol == 7){ printf("/\n");}	
	if (symbol == 2){ printf("\\\n");}	
	*/

	if (symbol == 5){ return 0;}	
	
	if (x == maxlevel){ z++;solution[z][0] = x; solution[z][1] = y;return 1;}

	tabela[x][y] = 5;

	if (symbol == 4){
		if (tabela[x+1][y-1] == 7){
			if (maze(maxlevel,x+1,y-1,tabela,solution)){
				z++;
				solution[z][0] = x; solution[z][1] = y;
				return 1;
			}
		}		
		if (tabela[x+1][y] == 4){
			if (maze(maxlevel,x+1,y,tabela,solution)){
				z++;
				solution[z][0] = x; solution[z][1] = y;
				return 1;
			}
		}
		if (tabela[x+1][y+1] == 2){
			if (maze(maxlevel,x+1,y+1,tabela,solution)){
				z++;
				solution[z][0] = x; solution[z][1] = y;
				return 1;
			}
		}
	}
				
	else if (symbol == 2){ /* direita */
		if (tabela[x+1][y+1] == 4){
			if (maze(maxlevel,x+1,y+1,tabela,solution)){
				z++;
				solution[z][0] = x; solution[z][1] = y;
				return 1;
			}
		}		
		if (tabela[x+1][y+1] == 2){
			if (maze(maxlevel,x+1,y+1,tabela,solution)){ 
				z++;
				solution[z][0] = x; solution[z][1] = y;
				return 1;
			}
		}
		if (tabela[x+1][y] == 7){
			if (maze(maxlevel,x+1,y,tabela,solution)){ 
				z++;
				solution[z][0] = x; solution[z][1] = y;
				return 1;
			}
		}
		/* SAME LINE */
		
		if (tabela[x][y+1] == 7){
			if (maze(maxlevel,x,y+1,tabela,solution)){
				z++;
				solution[z][0] = x; solution[z][1] = y;
				return 1;
			}
		}
	
		if (tabela[x][y-1] == 7){
			if (maze(maxlevel,x,y-1,tabela,solution)){
				z++;
				solution[z][0] = x; solution[z][1] = y;
				return 1;
			}
		}
		
		
	}
		
	else if (symbol == 7){ /* esquerda */
		if (tabela[x+1][y-1] == 7){
			if (maze(maxlevel,x+1,y-1,tabela,solution)){
				z++;
				solution[z][0] = x; solution[z][1] = y;
				return 1;
			}
		}
		if (tabela[x+1][y-1] == 4){ 
			
			if (maze(maxlevel,x+1,y-1,tabela,solution)){
				z++;
				solution[z][0] = x; solution[z][1] = y;
				return 1;
			}
		}
		if (tabela[x+1][y] == 2){
			if (maze(maxlevel,x+1,y,tabela,solution)){
				z++;
				solution[z][0] = x; solution[z][1] = y;
				return 1;
			}
		}
		/* SAME LINE */
		
		if (tabela[x][y-1] == 2){
			if (maze(maxlevel,x,y-1,tabela,solution)){ 
				z++;
				solution[z][0] = x; solution[z][1] = y;
				return 1;
			}
		}

		if (tabela[x][y+1] == 2){
			if (maze(maxlevel,x,y+1,tabela,solution)){ 
				z++;
				solution[z][0] = x; solution[z][1] = y;
				return 1;
			}
		}

	}
		
	tabela[x][y] = 5;
	
	return 0;

}
Exemplo n.º 20
0
void Main()
{
	// 迷路の幅、高さ
	const int w = 41, h = 31;

	// 迷路 (true: 壁, false: 道)
	std::vector<std::vector<bool>> maze(w, std::vector<bool>(h, false));

	// ------------------------------
	// 棒倒し法で迷路を生成する
	// ------------------------------

	// 周囲を壁にする
	for (int x = 0; x < w; ++x) {
		maze[x][0] = true;
		maze[x][h - 1] = true;
	}
	for (int y = 0; y < h; ++y) {
		maze[0][y] = true;
		maze[w - 1][y] = true;
	}

	// 棒倒し
	for (int y = 2; y <= h - 3; y += 2) for (int x = 2; x <= w - 3; x += 2) {

		// 上下左右のうち、候補になるマスのリストを作る
		std::vector<Point> points;
		if (!maze[x + 1][y]) points.push_back({ x + 1, y });
		if (!maze[x - 1][y]) points.push_back({ x - 1, y });
		if (!maze[x][y + 1]) points.push_back({ x, y + 1 });
		if (y == 2) points.push_back({ x, y - 1 });

		// 候補から1つランダムに選ぶ
		Point p = points[Random(0, static_cast<int>(points.size() - 1))];

		// マス (x, y) と選んだマスを壁にする
		maze[x][y] = true;
		maze[p.x][p.y] = true;

	}

	// ------------------------------
	// 棒倒し法ここまで
	// ------------------------------

	// 迷路の1マスを描画する大きさ
	const int cw = 15, ch = 15;

	// 壁と道の色
	const Color colWall = { 0, 0, 0 }, colFloor = { 192, 192, 192 };

	// プレイヤーの位置
	Point me = { 1, 1 };

	// プレイヤーの色
	const Color colMe = { 255, 0, 0 };

	// プレイヤーの見た目の半径
	const int meRadius = std::min(cw, ch) / 2 - 1;

	// キー設定
	const auto keyR = Input::KeyRight | Input::KeyD;
	const auto keyU = Input::KeyUp | Input::KeyW;
	const auto keyL = Input::KeyLeft | Input::KeyA;
	const auto keyD = Input::KeyDown | Input::KeyS;

	while (System::Update())
	{
		// プレイヤーの操作
		if (keyR.clicked && !maze[me.x + 1][me.y]) ++me.x;
		if (keyU.clicked && !maze[me.x][me.y - 1]) --me.y;
		if (keyL.clicked && !maze[me.x - 1][me.y]) --me.x;
		if (keyD.clicked && !maze[me.x][me.y + 1]) ++me.y;

		// 迷路を描画
		for (int y = 0; y < h; ++y) for (int x = 0; x < w; ++x) {
			Rect(x * cw, y * ch, cw, ch).draw(maze[x][y] ? colWall : colFloor);
		}

		// プレイヤーを描画
		Circle({ me.x * cw + cw / 2, me.y * ch + ch / 2 }, meRadius).draw(colMe);
	}
}
//---------------------------------------------------------------------------
//From http://www.richelbilderbeek.nl/CppCreateMaze.htm
std::vector<std::vector<int> > CreateMaze(const int size)
{
  //Size must be odd
  assert( size % 2 == 1);

  std::vector<std::vector<int> > maze(size, std::vector<int>(size,0));

  //Draw outer walls
  for (int i=0; i!=size; ++i)
  {
    maze[0]     [i     ] = 1;
    maze[size-1][i     ] = 1;
    maze[i]     [0     ] = 1;
    maze[i]     [size-1] = 1;
  }

  //Draw pillars
  for (int y=2; y!=size-1; y+=2)
  {
    for (int x=2; x!=size-1; x+=2)
    {
      maze[y][x] = 1;
    }
  }

  //Check around pillars
  const int nWallsToAdd = ((size / 2) - 1) * ((size / 2) - 1);
  for (int i=0; i!=nWallsToAdd; )
  {

    for (int y=2; y!=size-1; y+=2)
    {
      for (int x=2; x!=size-1; x+=2)
      {
        const int nWalls
          = (maze[y-1][x] == 0 ? 0 : 1)
          + (maze[y+1][x] == 0 ? 0 : 1)
          + (maze[y][x+1] == 0 ? 0 : 1)
          + (maze[y][x-1] == 0 ? 0 : 1);
        if ( nWalls == 0)
        {
          switch(std::rand() % 4)
          {
            case 0: maze[y-1][x] = 1; break;
            case 1: maze[y+1][x] = 1; break;
            case 2: maze[y][x+1] = 1; break;
            case 3: maze[y][x-1] = 1; break;
          }
          ++i;
        }
        else if (nWalls == 1)
        {
          switch(std::rand() % 6)
          {
            case 0: std::swap(maze[y-1][x], maze[y+1][x]); break;
            case 1: std::swap(maze[y-1][x], maze[y][x+1]); break;
            case 2: std::swap(maze[y-1][x], maze[y][x-1]); break;
            case 3: std::swap(maze[y+1][x], maze[y][x+1]); break;
            case 4: std::swap(maze[y+1][x], maze[y][x-1]); break;
            case 5: std::swap(maze[y][x+1], maze[y][x-1]); break;
          }
        }
      }
    }
  }
  return maze;
}
Exemplo n.º 22
0
int main(){
    // Sets up raspbery pi hardware and ensures everything is working.
    init(0);
    
    std::signal(SIGINT, handle_signal);
    
    openGate();
    
    // Test code for camera, takes picture and prints it.
    int black_count = 0;
    int counter = 0;
    bool first_full_line = true;
    //maze();
    while(true){
        // Reads current image from camera stores in memory.
        take_picture();
        int total=0;
        int total_error = 0;
        int num_white = 0;
        int num_col_white = 0;
        int total_white = 0;
        int prev_error = 0;
        bool c;
        // loop takes a line of pixels 5 wide horizontally accross the picture
        for(int i=0; i<PICTURE_WIDTH; i++){
            for(int j = 0; j<5; j++){
                // c gets assigned 0 or 1
                c = get_pixel(i, (PICTURE_HEIGHT/2)+j, 3) > 127;
                // 0 or 1 added to total_white
                total_white += c;
            }
            // num_white gets the values from just 1 pixel line across the picture.
            c = get_pixel(i, PICTURE_HEIGHT/2, 3) > 127;
            num_white += c;
            // added to the total
            total += (i-(PICTURE_WIDTH/2))*c;
        }
        
        total_error += total;
        // PID control see https://github.com/kaiwhata/ENGR101-2016/wiki/PID-(Proportional-Integral-Derivative)-Control
        // for more detail
        double proportional_signal = total*KP;
        double derivative_signal = (total-prev_error/0.1)*KD;
        double integral_signal =  total_error*KI;
        prev_error = total;
        int total_signal = proportional_signal + derivative_signal + integral_signal;
        //deadend checker
        counter++;
        // if the camera sees nothing but black implements black_count
        if(num_white == 0){
            black_count++;
        }
        // takes a picture of a verticle column in centre of picture
        // currently unused.
        for(int i=0; i<PICTURE_HEIGHT; i++){
            c = get_pixel(PICTURE_WIDTH/2, i, 3) > 127;
            num_col_white += c;
        }
        // detecting if picture is fully white, e.g. only see white
        if (num_white >= 320){
            printf("hit\n");
            if(first_full_line == true){
                // drives straight through
                first_full_line = false;
                set_motor(1, MOTOR_SPEED);
                set_motor(2, -MOTOR_SPEED);
                Sleep(1,0);
            } else {
                //turns left
                set_motor(1, -MOTOR_SPEED - total_signal);
                set_motor(2, -MOTOR_SPEED - total_signal);
            }
        } else if(num_white > 0){
            // drives forward
            set_motor(1, MOTOR_SPEED - total_signal);
            set_motor(2, -MOTOR_SPEED - total_signal);
        } else {
            // turns
            set_motor(1, -MOTOR_SPEED);
            set_motor(2, MOTOR_SPEED);
        }
        // if stuck at dead end for too long spins around
        if(black_count == 25){
            black_count = 0;
            set_motor(1, MOTOR_SPEED);
            //turns avc around
            set_motor(2, MOTOR_SPEED);
            Sleep(1,0);
        }
        //resetes counting how many times it detects dead end.
        if(counter == 60){
            counter = 0;
            black_count =0;
        }

        /*printf("num white:%d\n", num_white);
        printf("black:%d\n", black_count);
        printf("Counter:%d\n", counter);
        printf("Row:%d\n", num_white);
        printf("Col:%d\n", num_col_white);*/
        
        // detecting if at red square for start of maze    
        int num_red = 0;
        for(int i=0; i<PICTURE_WIDTH; i++){
            bool r = get_pixel(i, PICTURE_WIDTH/2, 0) > 200;
            bool g = get_pixel(i, PICTURE_WIDTH/2, 1) > 200;
            bool b = get_pixel(i, PICTURE_WIDTH/2, 2) > 200;
            if(r && !g && !b){
                num_red++;
            }
        }
        //printf("Red:%d\n", num_red);
        if(num_red > 100){
            set_motor(1, 0);
            set_motor(2, 0);
            maze();
        }
           
        Sleep(0,SLEEP_TIME);
    }
    return 0;
}
Exemplo n.º 23
0
Grid<double> createRandomMaze(int size) {
    Grid<double> maze(size, size, kMazeFloor);
    BasicGraph* graph = gridToGraph(maze, mazeCost);
    
    // assign random weights to the edges
    // give each edge a 'random' weight;
    // put all edges into a priority queue, sorted by weight
    Set<Edge*> edgeSet = graph->getEdgeSet();
    int edgeCount = edgeSet.size();
    for (Edge* edge : edgeSet) {
        int weight = randomInteger(1, edgeCount * 1000);
        edge->cost = weight;
    }
    
    // run the student's Kruskal algorithm to get a minimum spanning tree (MST)
    Set<Edge*> mst = kruskal(*graph);
    
    // convert the MST/graph back into a maze grid
    // (insert a 'wall' between any neighbors that do not have a connecting edge)
    graph->clearEdges();
    for (Edge* edge : mst) {
        graph->addEdge(edge->start, edge->finish);
        graph->addEdge(edge->finish, edge->start);
    }

    // physical <-> logical size; a maze of size MxN has 2M-1 x 2N-1 grid cells.
    // cells in row/col 0, 2, 4, ... are open squares (floors), and cells in 
    // row/col 1, 3, 5, ... are blocked (walls).
    int digits = countDigits(size);
    int worldSize = size * 2 - 1;
    Grid<double> world(worldSize, worldSize, kMazeWall);
    for (int row = 0; row < worldSize; row++) {
        for (int col = 0; col < worldSize; col++) {
            if (row % 2 == 0 && col % 2 == 0) {
                world[row][col] = kMazeFloor;
            }
        }
    }
    
    for (int row = 0; row < size; row++) {
        int gridRow = row * 2;
        for (int col = 0; col < size; col++) {
            int gridCol = col * 2;
            string name = vertexName(row, col, digits);
            
            // decide whether to put open floor between neighbors
            // (if there is an edge between them)
            for (int dr = -1; dr <= 1; dr++) {
                int nr = row + dr;
                int gridNr = gridRow + dr;
                for (int dc = -1; dc <= 1; dc++) {
                    int nc = col + dc;
                    int gridNc = gridCol + dc;
                    if ((nr != row && nc != col)
                            || (nr == row && nc == col)
                            || !world.inBounds(gridNr, gridNc)) {
                        continue;
                    }
                    string neighborName = vertexName(nr, nc, digits);
                    if (graph->containsEdge(name, neighborName)) {
                        world[gridNr][gridNc] = kMazeFloor;
                    }
                }
            }
        }
    }
    
    delete graph;
    return world;
}
Exemplo n.º 24
0
int main(int argc, const char *argv[]) {
	if( argc != 2 ) //checks for the input file name
	{
		std::cerr << "Error: no input file name" << std::endl;
		std::cerr << "Usage: ./" << argv[0] << " someinput.txt" << std::endl;
		return 1;
	}

	std::ifstream mazeInputFile ( argv[1] );	// open the input file
	int numberOfMazes = 0;
	mazeInputFile >> numberOfMazes; 			// read the number of mazes

	for (int currentMaze = 0; currentMaze < numberOfMazes; currentMaze++ ) {
		int mazeSize = 0;
		mazeInputFile >> mazeSize;				// read the maze size from the input file

		std::cout << "size = " << mazeSize << std::endl;
		Utils mazeUtils(mazeSize, mazeInputFile); // helper class for testing, output

		if (mazeSize < 10 || mazeSize > 30) {
			std::cerr << "Error: invalid maze size " << mazeSize << " read from " << argv[1] << std::endl;
			std::cerr << "     Maze sizes must be between 10 and 30" << std::endl;
			return 1;
		}

		// Create a new maze object of the given size
		Maze maze(mazeSize);

		// Initialize the maze
		maze.readFromFile(mazeInputFile);

		int row, col;

		// Solve the maze
		do {

			// Get current location of 'x' in the maze
			maze.getCurrentPosition(row, col);

			// Print the current maze string (this is provided, you don't need to implement)
			mazeUtils.print(row, col);
			std::cout << "Press ENTER to continue..." << std::endl;
			std::cin.get();    // wait for a keypress by user before moving on

			// Advance one step in the maze
			maze.step();

		} while ( ! maze.atExit() );


		maze.getCurrentPosition(row, col);
		mazeUtils.print(row, col);
		std::cout << "YAY! Maze solved!" << std::endl;
                std::cout << "Press ENTER to continue..." << std::endl;
		std::cin.get();    // wait for a keypress by user before moving on

		mazeUtils.reset();

	} // currentMaze


}
Exemplo n.º 25
0
int main(int argc,char *argv[]) {




char green[] ="#00FF00";
char red[] ="#ff0000";
char white[]="#FFFFFF";
char black[]="#000000";

int xres=1920;
int yres=1080;
int pixsize=10;
//if wallstrue equals zero then there will be no walls, else there will be walls
int wallstrue=1;
char * name="maze.png";

//if (argc>1)
//xres=std::stoi(argv[1]);
//if (argc>2)
//yres=std::stoi(argv[2]);
//if (argc>3)
//pixsize=std::stoi(argv[3]);
//if (argc>4)
//wallstrue=std::stoi(argv[4]);
//if (argc>5)
//name=argv[5];


for (int i=1;i<argc;i++)
{
    std::string flag=argv[i];
if (flag=="-w"||flag=="--width")
xres=std::stoi(argv[i+1]);
if (flag=="-h"||flag=="--height")
yres=std::stoi(argv[i+1]);
if (flag=="-p"||flag=="--pixel-size")
pixsize=std::stoi(argv[i+1]);
if (flag=="-b"||flag=="--walls")
wallstrue=std::stoi(argv[i+1]);
if (flag=="-n"||flag=="--file-name")
name=argv[i+1];


}


Draw xwin(pixsize,xres,yres);

int xblocks=xwin.screenwidth/xwin.pixwidth-1;
int yblocks=xwin.screenheight/xwin.pixwidth-1;

Maze maze(xblocks,yblocks);

//1 means it loops
maze.startCreation(1);


maze.nextStep();


if (wallstrue!=0)
{
	//horizontal
	drawWall(maze.wall.horwalls,maze.wall.width,maze.wall.height,&xwin,black,1.0,1.0/2.0,0);
	//verticle
	drawWall(maze.wall.vertwalls,maze.wall.width+1,maze.wall.height-1,&xwin,black,1.0/2.0,1.0,1);

}

//	drawBlock(maze.xpos,maze.ypos,&xwin,&maze,red_gc);


	int colors[6];

	for (int i=0;i<6;i++)
	{
	colors[i]=rand()%256;
	}

	double distance =sqrt(  pow((colors[0]-colors[3]),2) + pow((colors[1]-colors[4]),2) + pow((colors[3]-colors[5]),2));

	while (distance<200|distance>300)
	{
	for (int i=0;i<6;i++)
	colors[i]=rand()%256;
	distance =sqrt(  pow((colors[0]-colors[3]),2) + pow((colors[1]-colors[4]),2) + pow((colors[3]-colors[5]),2));
	}


maze.drawValues(&xwin,colors[0],colors[1],colors[2],colors[3],colors[4],colors[5]);

//	maze.drawValues(&xwin,255,255,255,0,0,0);



xwin.writePng(name);



//	xwin.printPoints();
//	xwin.drawScene();



xwin.clearStack();

return 0;
}
Exemplo n.º 26
0
    /* Generate a maze using kruskal */
	std::unique_ptr<maze::Maze> maze::KruskalGenerator::make_maze()
	{
		/*  Algorithm: https://en.wikipedia.org/wiki/
        Maze_generation_algorithm#Randomized_Kruskal.27s_algorithm 
        (accessed 21/09/14)
    	*/

    	/* Initialize maze object */
    	std::unique_ptr<maze::Maze> maze(new Maze(height, width));


        /* List of pointers to all cells */
        std::vector<std::vector<maze::Cell *> > * all_cells = maze->get_cells();
        /* Disjoint-set of these cells */
        josh::Disjoint_set<maze::Cell *> cell_set;
        /* A list of all possible pathways */
        std::vector<maze::Pathway *> possible_pathways;

        std::mt19937 mt (seed);

        /* Fill the disjoint set with the cells */
        for(std::vector<maze::Cell *> row : *all_cells)
        {
            for(maze::Cell * cell : row)
            {
                cell_set.add(cell);
            }
        }

        /* Now we need a list of all possible pathways - To save on redundant checks, 
           we can break the operation into multiple parts */

        /* Main block */
        for(unsigned y = 0; y < height - 1; y++) /* each row except last */
        {
            for (unsigned x = 0; x < width - 1; x++) /* each column except last */
            {
                /* Add a pathway form the current cell to the cell to the right into possible pathways */
                /*std::cerr << "y: " << y << ", x: " << x << "\n";*/
                possible_pathways.push_back(new Pathway(maze->get_cell(x,y), maze->get_cell(x + 1, y)));

                /* Add a pathway form the current cell to the cell to the bottom into possible pathways */
                possible_pathways.push_back(new Pathway(maze->get_cell(x,y), maze->get_cell(x, y + 1)));

            }
        }

        /* Last column */
        for(unsigned y = 0; y < height - 1; y++) /* each row except last */
        {
            /* Add a pathway form the end (column) cell to the cell bellow into possible pathways */
            possible_pathways.push_back(new Pathway(maze->get_cell(width - 1, y), maze->get_cell(width - 1, y + 1)));
        }

        /* Last row */
        for(unsigned x = 0; x < width - 1; x++) /* each column except last */
        {
            /* Add a pathway form the end (row) cell to the cell to the right into possible pathways */
            possible_pathways.push_back(new Pathway(maze->get_cell(x, height - 1), maze->get_cell(x + 1, height - 1)));
        }

        /* Now we can continue with a randomised Kruskal's algorithm
           Since we are using a vector, and we only want to iterate over 
           each pathway only once and at random, the most efficient way
           is to shuffle the list and then traverse */

        std::shuffle(possible_pathways.begin(), possible_pathways.end(), mt);

        for(maze::Pathway * random_pathway : possible_pathways)
        {
            /* See if the cells are disjoint */
            maze::Cell * cell1 = random_pathway->get_first_cell();
            maze::Cell * cell2 = random_pathway->get_second_cell();

            josh::Tree_node<maze::Cell *> * set_of_cell1, * set_of_cell2;

            try 
            {
                set_of_cell1 = cell_set.find_set(cell1);
            }
            catch (const josh::CannotFindObject)
            {
                throw maze::CannotGenerateMaze("Error with maze cell generation");
            }
            
            try
            {
                set_of_cell2 = cell_set.find_set(cell2);
            }
            catch (const josh::CannotFindObject)
            {
                throw maze::CannotGenerateMaze("Error with maze cell generation");
            }


            if(cell_set.is_disjoint(set_of_cell1, set_of_cell2))
            {
                /* They are - add pathway to maze and union two sets */
                maze->add_pathway(random_pathway);
                cell_set.union_sets(set_of_cell1, set_of_cell2);

            }
            else
            {
                /* we wont need the allocated pathway */
                delete random_pathway;
            }

            
        }

    	return maze;
	}
Exemplo n.º 27
0
//---------------------------------------------------------------
void Usr_Submit(void)
{
   if(cnt < 81)  // fill all positions and then try
   {
	frame(190,180,430,300,LIGHTBLUE,LIGHTBLUE,WHITE);
	frame(193,183,427,297,LIGHTBLUE,LIGHTBLUE,WHITE);
	frame(196,186,424,200,BLUE,BLUE,BLUE);
	setcolor(WHITE);
	settextstyle(0,0,1);
	outtextxy(280,190,"MESSAGE");
	setcolor(BLACK);
	outtextxy(203,216,"FILL ALL POSITIONS AND");
	outtextxy(203,231,"THEN TRY !");
	delay(1000);
	Message_Box();
   }

   else //if(cnt == 81)
   {
      int flag = 0;

      for(int i=0;i<9;i++)
	for(int j=0;j<9;j++)
	{
	  if(arr[i][j] != puzz[i][j])
	  {   flag = 1;
	      break;
	  }
	}

       if(flag == 1)
       {
	frame(190,180,430,300,LIGHTBLUE,LIGHTBLUE,WHITE);
	frame(193,183,427,297,LIGHTBLUE,LIGHTBLUE,WHITE);
	frame(196,186,424,200,BLUE,BLUE,BLUE);
	setcolor(WHITE);
	settextstyle(0,0,1);
	outtextxy(280,190,"MESSAGE");
	setcolor(BLACK);
	outtextxy(203,230,"YOUR SOLUTION IS WRONG.");
	outtextxy(203,246,"DO TRY !");
	delay(1000);
	Message_Box();
	cnt = 81;
       }

       else
       {
	frame(190,180,430,300,LIGHTBLUE,LIGHTBLUE,WHITE);
	frame(193,183,427,297,LIGHTBLUE,LIGHTBLUE,WHITE);
	frame(196,186,424,200,BLUE,BLUE,BLUE);
	setcolor(WHITE);
	settextstyle(0,0,1);
	outtextxy(280,190,"MESSAGE");
	setcolor(BLACK);
	outtextxy(203,230,"CONGRATULATIONS !! ");
	outtextxy(203,246,"YOU HAVE CRACKED THIS ONE.");
	delay(1000);
	Message_Box();
	for(i=0;i<9;i++)     // flush all the arrays
	  for(j=0;j<9;j++)
	    cnt = arr[i][j] = stat[i][j] = puzz[i][j] = hnt[i][j] = 0;

	maze();
	fill_maze();
	men_stat = 0;
	code = -1;
	puz_typ = 0;
	Number_Pad(9);
	curr=10;
       }
   }
}
Exemplo n.º 28
0
void MazeGen::RemoveWall(Vertex & current, Vertex & neighbor)
{
	maze(current.x, current.y)->Blue = 255;
	maze(current.x, current.y)->Green = 255;
	maze(current.x, current.y)->Red = 255;

	// Neighbor is the right neighbor of current
	if(neighbor.x > current.x)
	{
		maze(current.x + 1, current.y)->Blue = 255;
		maze(current.x + 1, current.y)->Green = 255;
		maze(current.x + 1, current.y)->Red = 255;
	}

	// Neighbor is the bottom neighbor of current
	else if(neighbor.y > current.y)
	{
		maze(current.x, current.y + 1)->Blue = 255;
		maze(current.x, current.y + 1)->Green = 255;
		maze(current.x, current.y + 1)->Red = 255;
	}

	// Neighbor is the left neighbor of current
	else if(neighbor.x < current.x)
	{
		maze(current.x - 1, current.y)->Blue = 255;
		maze(current.x - 1, current.y)->Green = 255;
		maze(current.x - 1, current.y)->Red = 255;
	}

	// Neighbor is the top neighbor of current
	else
	{
		maze(current.x, current.y - 1)->Blue = 255;
		maze(current.x, current.y - 1)->Green = 255;
		maze(current.x, current.y - 1)->Red = 255;
	}
}