Example #1
0
int		main(int argc, char **argv)
{
	int w;
	int h;
	int **tab;
	int i;
	int case_per_sec;
	int score;

	i = 0;

	w = ft_atoi(argv[1]);
	h = ft_atoi(argv[2]);
	case_per_sec = ft_atoi(argv[3]);
	tab = (int **)malloc(sizeof(int*) * w);
	while (i < w)
	{
		tab[i] = (int *)malloc(sizeof(int) * h);
		i++;
	}
	set_tab(tab, w, h);
	puttab(tab,w, h);
	score = snake(tab, w, h, case_per_sec);
	ft_putstr("Game over !\nScore final: ");
	ft_putnbr(score);
}
Example #2
0
int main()
{
	srand(time(0));
	Snake02 snake(20, 20);
	snake.InitMatrix();
	snake.GetHeadPos();
	
	snake.GetFoodPos();
	snake.PrintScreen();
	int key{ 0 };
	do
	{
		if (_kbhit())
		{
			switch (_getch())
			{
			case (int)Arrows::KEY_RIGHT:
				snake.ArrowRight();
				break;
			case (int)Arrows::KEY_LEFT:
				snake.ArrowLeft();
				break;
			case (int)Shot::SPACE:
				snake.Fire();
				break;
			}
			snake.PrintScreen();
		}
	} while (!0);
	return 0;
}
void grid()
{
// setbkcolor(LIGHTGREEN);
 setfillstyle(1,LIGHTGREEN);
 floodfill(0,0,15);
 setlinestyle(0,0,3);
 setcolor(RED);
 settextjustify(1,1);
// settextstyle(0,0,1);
 for(int i=0;i<=480;i+=48)
  line(0,i,479,i);
 line(0,479,479,479);
 for(i=0;i<=480;i+=48)
  line(i,0,i,479);
 int k=1;int a=9;
 char h[3];
 setfillstyle(1,LIGHTBLUE);
 floodfill(639,479,RED);
 setcolor(BROWN);
 setlinestyle(0,0,3);
 ladd(110,452,412);
 ladd(350,452,364);
 ladd(206,404,316);
 ladd(398,308,268);
 ladd(110,260,220);
 ladd(254,260,172);
 ladd(206,164,28);
 ladd(350,164,124);
 ladd(62,116,76);
 snake(168, 374, 264, 447);
 snake(360, 278, 312, 399);
 snake(168, 230, 72, 351);
 snake(408,182,312,255);
 snake(120, 86, 168, 303);
 snake(264, 38, 360, 111);
 snake(72, 38, 72,159);
 snake(264, 134, 216, 255);
 setcolor(RED);
 settextstyle(4,0,1);

 while(a>0)
 {
  for(i=0;i<10;i++)
	{
	 sprintf(h,"%d",k++);
	 outtextxy(i*48+24,a*48+24,h);
	}
  a--;
  for(i=9;i>=0;i--)
	{
	 sprintf(h,"%d",k++);
	 outtextxy(i*48+24,a*48+24,h);
	}
  a--;
 }

}
Example #4
0
int main(){
	sf::RenderWindow App( sf::VideoMode( 800, 600, 32 ), "Snake" );
	std::cout << "f1\n";
	App.setFramerateLimit( 30 );
	std::cout << "f2\n";
	sf::Texture snakeTex;
	std::cout << "f2.1\n";
	if( !snakeTex.loadFromFile( "img/Silver.png" ) ){
		std::cout << "f2.2\n";
		return -1;
	}
	std::cout << "f3\n";
	snakeTex.setSmooth( false );
	std::cout << "f2\n";
	World world( &App );
	std::cout << "f3\n";
	FoodManager foodManager;
	foodManager.setBadFoodPerc( 10 );
	foodManager.setFoodGenTime( sf::seconds( 15 ) );
	std::cout << "f4\n";
	// Mighty snake warrior
	Snake snake(&foodManager);
	const float s = pixelToScale( snakeTex.getSize().x, TILE_SIZE );
	snake.setScale( {s, s} );
	snake.setSquareSize( TILE_SIZE );
	snake.createSprite( snakeTex );
	snake.reset( 10 );
	snake.setSpeed( 5 );
	std::cout << "f5\n";
	while( App.isOpen() ){
		std::cout << "f6\n";
		// Event
		sf::Event event;
		while( App.pollEvent(event) ){
			if( event.type == sf::Event::Closed ){
				App.close();
			}
			
			snake.pollEvent( &event );
		}
		std::cout << "f7\n";
		// Logic
		foodManager.logic();
		snake.logic();
		std::cout << "f8\n";
		// Render
		//App.clear( sf::Color( 255, 255, 255 ) );

		std::cout << "f9\n";
		foodManager.render( &App );
		snake.render( &App );
		world.render();
		std::cout << "f10\n";
		App.display();
		std::cout << "f11\n";
	}
	return 0;
}
Example #5
0
void GamePainter::drawSnakeCell(QPoint _pos)
{
    QBrush snake( QColor(0,200, 0), Qt::Dense2Pattern );
    m_painter.setBrush( snake );

    m_painter.drawEllipse( _pos.x() * m_cellSize.width()
                           , _pos.y() * m_cellSize.height() + 30
                           , m_cellSize.width() + 3
                           , m_cellSize.height() + 3
                           );
}
Example #6
0
/* Main function, the entry point of this program.
 * The main function is called from the startup code in file
 * Libraries/CMSIS/ST/STM32F4xx/Source/Templates/TrueSTUDIO/startup_stm32f4xx.s
 * (line 101)
 */
int main(void)
{
    while (1)
    {
      led_round();
      flash_all_leds();
      snake();
    }

    return 0; // never returns actually
}
Example #7
0
int main(void) 
{
    int trav[1024] = {0}, row = 0, column = 0, res = 0;
    scanf("%d %d", &trav[0], &trav[1]);
    for(int i = 1; trav[i]; i++)
      scanf("%d", &trav[i + 1]);
    res = snake(trav, &row, &column);
    if(res) printf("%d %d\n", row, column);
    else printf("err %d %d\n", row, column); 
    return 0;
}
Example #8
0
void SnakeApp::task() {
        while(true) {
            Snake snake(21, 33, SnakeApp::setPixel);

            Tilda::getGUITask().clearRoot();
            Tilda::delay(80);
            GLCD.ClearScreen();
            Tilda::delay(80);
            snake.render_start();

            uint8_t score = 0;

            while(!snake.game_over()) {
                uint32_t nextFrame = Tilda::millisecondsSinceBoot() + FRAME_DURATION;

                if (score != snake.length()) {
                    score = snake.length();
                    if (score > highscore) {
                        highscore = score;
                    }
                    GLCD.SelectFont(System5x7);
                    GLCD.CursorToXY(0, 105);
                    GLCD.print("Score:  ");
                    GLCD.print(score);
                    GLCD.CursorToXY(0, 115);
                    GLCD.print("HiScore:");
                    GLCD.print(highscore);
                }

                snake.tick();
                snake.render_start();
                snake.render_tick();

                while (nextFrame - Tilda::millisecondsSinceBoot() > 0) {
                    Button button = mButtonSubscription->waitForPress(nextFrame - Tilda::millisecondsSinceBoot());
                    if (button == UP) {
                        snake.dir_up();
                    } else if (button == DOWN) {
                        snake.dir_down();
                    } else if (button == LEFT) {
                        snake.dir_left();
                    } else if (button == RIGHT) {
                        snake.dir_right();
                    }
                }
            }

            Tilda::delay(1000);
        }
}
Example #9
0
void loop() 
{
	if (patternIndex == 0) {
		strobe(c1, 200);
	}
	if (patternIndex == 1) {
		sprite(PIXEL_COUNT, c1, c2, c3, 90);
	}
	if (patternIndex == 2) {
		snake(c1, c2, 10);
	}
	if (patternIndex == 3) {
		rainbow(20);
	}
	if (patternIndex == -1) {
		stripSet(OFF, 0);
	}
}
/****************************************************************
* Main
****************************************************************/
int main(){	
	// Set the signal callback for Ctrl-C
	signal(SIGINT, signal_handler);

	initUART();
	setSerial();
	while(keepgoing){
		cwrotate(800);
		ccwrotate(800);
		burstout(1000);
		burstin(1000);
		starburstout(600);
		starburstin(600);
		spiralin(400);
		spiralout(400);
		flashon_off(800);
		snake(200);
	}
	return 0;
}
Example #11
0
void loop()
{
 
 volume();
 beat();
 current = (float)analogRead(2)/ (1024/ 8)+1;
// current = 8;
 
 
 switch (current)
   {
      case 1:
       stargase();
       break;
      case 2:
      vol_meter();
      break;
      case 3:
       vol_visual();
       break;
      case 4:
      picture_move();
      break;
      case 5:
      vol_wave();
      break;
      case 6:
      snake();
      break;
      case 7:
      snake2();
      break;
      case 8:
      matrix();
       break;
   }
   
  last_value = current;
 
  print();
}
Example #12
0
void loop()
{
 print();
 current = (float)analogRead(4)/ (1024/ 7);
 current = 8;
 switch (current)
   {
      case 1:
       stargase();
       break;
      case 2:
      vol_meter();
      break;
      case 3:
       vol_visual();
       break;
      case 4:
      picture_move();
      break;
      case 5:
      vol_wave();
      break;
      case 6:
      snake();
      break;
      case 7:
      snake2();
      break;
      case 8:
       mikro_disko();
       break;
   }
  last_value = current;
 
 //

}
Example #13
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
//    Point p1(10, 10, '*');
//    p1.draw();

//    HorizontalLine hLine(20, 30, 15);
//    hLine.draw();

//    VerticalLine vLine(20, 31, 15);
//    vLine.draw();

//    Point p2(21, 31, 'H');
//    p2.draw();

    Point p3(30, 30, '*');

    Snake snake(p3, 10, UP);
    snake.draw();

    snake.startMove(RIGHT);

    return a.exec();
}
Example #14
0
int game::runMe() const
{
    initscr();
    noecho();
    keypad(stdscr, TRUE);
    raw();
    timeout(5);

    field field;
    snake snake(field.getHeight(), field.getWidith());
    while (!snake.colisionCheck())
    {
        switch (getch())
        {
        case KEY_UP:
            snake.changeDirection(3);
            break;
        case KEY_DOWN:
            snake.changeDirection(1);
            break;
        case KEY_LEFT:
            snake.changeDirection(4);
            break;
        case KEY_RIGHT:
            snake.changeDirection(2);
            break;
	case '\x1B': //quit after pressing esc
	  return gameOver();
	  break;
        }
        snake.moveMe();
        field.printSnake(snake.getSnake());
        std::this_thread::sleep_for(std::chrono::milliseconds(20));
    }
    return gameOver();
}
Example #15
0
int main() {
  // SETUP
  init();
  Serial.begin(9600);
  tft.initR(INITR_BLACKTAB);  // initialize screen
  
  // Setting the joystick button and LEDs
  pinMode(JOYSTICK_BUTTON, INPUT);
  digitalWrite(JOYSTICK_BUTTON, HIGH);
  
  // Initialize the SD card
  Serial.print("Initializing SD card...");
  if (!SD.begin(SD_CS)) {
    Serial.println("failed!");
    while(true) {} // something is wrong
  } 
  else {Serial.println("OK!");}
  
  // More initialization
  Serial.print("Initializing Raw SD card...");
  if (!card.init(SPI_HALF_SPEED, SD_CS)) {
    Serial.println("failed!");
    while(true) {} // something is wrong
  } 
  else {Serial.println("OK!");}
  
  // Create states for different modes
  // C1 for Mode 1 - MENU screen
  // C2 for Mode 2 - Snake Game
  // C3 for Mode 3 - GAME OVER screen
  // C4 for Mode 4 - Choose level
  // C5 for Mode 5 - PAUSE screen
  typedef enum {C1 = 1, C2, C3, C4, C5, ERR} State;
  State state = C1;
  int select, snakelength;
  
  while (state!=ERR) {
    if  (state == C1) {
      /// ====== MODE 1 - MENU ====== ///
      Serial.println("Currently in Mode 1");
      snakelength = 1;
      init_vert = analogRead(JOYSTICK_VERT); 
      init_horiz = analogRead(JOYSTICK_HORIZ);
      
      // preparations for the game - to not overlap with the pause menu
      q = q_create(720);
      i = 64; // x component
      j = 80; // y component
      q_add(q,i,j); // load into the queue
      random_x = food_x(); // load x coordinate of food piece
      random_y = food_y(); // load y coordinate of food piece
      pausedirection = 0; // set paused direction to 0
      // reset grid to 0
      for (int a = 0; a < 24; a++) {
        for (int b = 0; b < 30; b++) {
        grid[a][b] = 0;
        }
      }
      
      // display main menu
      snake();
      tft.setTextSize(2);
      
      while(true) {
        // alternate highlighting of START
        unsigned long time = millis()%1000;
        int a = time%1000;
        if ((a<17)) {
        tft.setCursor(34, 83);
        tft.fillRoundRect(30,80,65,20,5,WHITE);
        tft.setTextColor(RED);
        tft.print("START");
        }
        else if ((a>500) && (a<520)) {
        tft.setCursor(34, 83);
        tft.fillRoundRect(30,80,65,20,5,RED);
        tft.setTextColor(WHITE);
        tft.print("START");
        }
        // Read the Joystick - HIGH if not pressed, LOW otherwise
        select = digitalRead(JOYSTICK_BUTTON);     
        if (select == LOW) {
          break;
        }
      }
      state = C4; 
    }
    
    else if (state == C2) {
      /// ====== MODE 2 - SNAKE GAME ====== ///
      Serial.println("Currently in Mode 2");
      delay(50);
      soundsetup(); //setting up sound pin
      // print the background
      tft.fillScreen(DARKRED);
      tft.fillRect(4,5,120,150,DARKGRN);
      
      // print the snake
      int x,y;
      x = q_frontx(q);
      y = q_fronty(q);
      tft.fillRect(x,y,5,5, WHITE);
      
      //Bringing the food in, outside while loop first.
      tft.fillRect(random_x, random_y, 5, 5, YELLOW);
      
      // do auto calibration
      int px, py;
      int lastmove;
      
      // read beginning direction chosen by user
      if (pausedirection == 0) {
        direction = read_direction();
      }
      else {
        direction = pausedirection;
      }
      lastmove = direction;
      
      while (true) {
        
        // to direct movement 
        // (without going in reverse direction of previous movement)
        
        // up
        if (direction == 1) {
          if (lastmove == 2) {
            direction = 2;
            j = j-5;
          }
          else {
            j = j+5;
        }
        q_add(q,i,j);
        }
        // down
        else if (direction == 2) {
          if (lastmove == 1) {
            direction = 1;
            j = j+5;
          }
          else {
            j = j-5;
          }
        q_add(q,i,j);
        }
        // right
        else if (direction == 3) {
          if (lastmove == 4) {
            direction = 4;
            i = i-5;
          }
          else {
            i = i+5;
          }
        q_add(q,i,j);
        }
        // left
        else if (direction == 4) {
          if (lastmove == 3) {
            direction = 3;
            i = i+5;
          }
          else {
            i = i-5;
          }
        q_add(q,i,j);
        }
        
        // if the direction is changed, store the new direction & last move
        int new_direc = read_direction();
        if ((new_direc != direction) && (new_direc != 0)) {
          lastmove = direction;
          direction = new_direc;
        }
        
        // if the snake hits a piece of food, the food vanishes and gets replaced 
        if ((i == random_x) && (j == random_y)) {
          // snake grows by 4 squares, except for the first time
          // this allows for it to end up as a max of 720 in the queue
          if (snakelength == 1) {
            q_add(q,i,j);
            q_add(q,i,j);
            q_add(q,i,j);
            snakelength += 3;
          }
          else {
            q_add(q,i,j);
            q_add(q,i,j);
            q_add(q,i,j);
            q_add(q,i,j);
            snakelength += 4;
          }
      if (snakelength < 720) {
        random_x = food_x();
        random_y = food_y();
      
        // if the snake is already there, find a new spot for the food
        while (grid[random_x/5][random_y/5-1] == 1) {
          random_x = food_x();
          random_y = food_y();
        }
        // print the new food
        tft.fillRect(random_x, random_y, 5, 5, YELLOW);
          }
        }
        
        // if the snake runs over itself
        if ((snakelength > 1) && (grid[i/5][j/5-1] == 1)) {
          delay(450); // pause when snake runs into itself
          int m = 0;
          soundLoop();
          while(m < 6000) {
            int rand_x = dissolve_x();
            int rand_y = dissolve_y();
            tft.fillRect(rand_x, rand_y, 5, 5, BLACK);
            m++;
          }
          state = C3;
          break;
        }
        
        px = q_frontx(q);
        py = q_fronty(q);
        // reprint the snake if there is movement
        if ((i != px) || (j != py)) {
          tft.fillRect(i,j,5,5, WHITE);
          grid[i/5][j/5-1] = 1;          // snake body is in grid
          tft.fillRect(px,py,5,5,DARKGRN);
          grid[px/5][py/5-1] = 0;        // snake body is no longer in grid
          q_remove(q);                   // take away from the queue
          delay(speed);                  // controls the speed of the snake
        }
       
        // if any of the borders are hit
        if ((i < 4)||(j < 5)||(i > 119)||(j > 150)) {
          delay(450); // pause when border is hit
          // dissolve the screen
          int m = 0;
          soundLoop();
          while(m < 6000) {
            int rand_x = dissolve_x();
            int rand_y = dissolve_y();
            tft.fillRect(rand_x, rand_y, 5, 5, BLACK);
            m++;
          }
          //~ delay(250);
          state = C3; 
          break;
        }
        
        // Read the Joystick - HIGH if not pressed, LOW otherwise
        select = digitalRead(JOYSTICK_BUTTON);     
        if (select == LOW) {
          state = C5;
          break;
        }
      }
    }
    
    else if (state == C3) {
      /// ====== MODE 3 - GAME OVER ====== ///
      Serial.println("Currently in Mode 3");
      q_destroy(q); // clear the queue
      tft.fillScreen(BLACK);
      tft.fillRoundRect(5,20,118,25,5,RED);
      tft.setCursor(10, 25); 
      tft.setTextColor(BLACK);
      tft.setTextSize(2);
      tft.setTextWrap(true);
      tft.print("GAME OVER");
      tft.print("\n"); 
      
      tft.setCursor(10, 55);
      tft.setTextColor(RED);
      tft.setTextSize(1.5);
      if (snakelength >= 720) {
        snakelength = 720;
        tft.print("YOU WON! CONGRATZ");
      }
      else {
        tft.print("      Oh no!         You hit something!");
      }
      
      tft.setCursor(10, 80);
      tft.setTextColor(WHITE);
      tft.setTextSize(1);
      tft.print("Length of Snake:");
      tft.print(snakelength);
      tft.setCursor(10, 100);
      tft.print("Press the joystick   to return to main    menu");
      
      // Read the Joystick - HIGH if not pressed, LOW otherwise
      while (true) {
        select = digitalRead(JOYSTICK_BUTTON);     
        if (select == LOW) {
          break;
        }
      }
      state = C1;
    }
    
    else if (state == C4) {
      /// ====== MODE 4 - CHOOSE LEVEL ====== ///
      Serial.println("Currently in Mode 4");
      // printing
      // snake display
      snake();
      // difficulty levels
      tft.setTextSize(2);  
      tft.setTextColor(WHITE);
      easy(RED);
      tft.setTextColor(RED);
      medium(WHITE);
      hard(WHITE);
      
      int selection = 1;
      int oldselection;
      while(true) {
        // read direction from the user for updating selection
        oldselection = selection;
        vertical = analogRead(JOYSTICK_VERT);      // will be 0-1023
        delay(100);
        
        // scroll down
        if (vertical > init_vert + 200) {
        selection++;
          if (selection > 3) {
            selection = 0;
          }
        } 
        // scroll up
        else if (vertical < init_vert - 200) {
          selection--;
          if (selection < 0) {
            selection = 3;
          }
        }
        
        if (selection != oldselection) {
          update(selection);
        }
        
        // Read the Joystick - HIGH if not pressed, LOW otherwise
        select = digitalRead(JOYSTICK_BUTTON);     
        if (select == LOW) {
          Serial.print("made selection: ");
          Serial.println(selection);
          if (selection == 1) {speed = 225;}
          else if (selection == 2) {speed = 150;}
          else if (selection == 3) {speed = 75;}
          break;
        }
      }
      state = C2;
    }
    
    else if (state == C5) {
      /// ====== MODE 5 - PAUSE MENU ====== ///
      Serial.println("Currently in Mode 5");
      pausedirection = direction;
      
      // printing snake and pause
      snake();
      tft.setTextSize(2);
      tft.setCursor(34, 73); 
      tft.fillRoundRect(30,70,65,20,5,WHITE);
      tft.setTextColor(RED);
      tft.print("Pause");
      
      while(true) {
        // Read the Joystick - HIGH if not pressed, LOW otherwise
        select = digitalRead(JOYSTICK_BUTTON);     
        if (select == LOW) {
          break;
        }
      }
      // reset grid to 0
      for (int a = 0; a < 24; a++) {
        for (int b = 0; b < 30; b++) {
        grid[a][b] = 0;
        }
      }
      state = C2; 
    }
    //if not any of this:
    else { 
      Serial.println("There has been an error");
      state = ERR; 
    }
  }
    
  Serial.end();
  return 0;
}
Example #16
0
static void
mushroom (void)
{
  snake ();
}
Example #17
0
int main()
{
	//state
	enum gameState
	{
		MENU,
		INGAME,
		EXITING
	} currentState(MENU); //launch into menu

	//window and framerate control
	sf::RenderWindow window(sf::VideoMode(800, 800), "SnakeFML");
	window.setFramerateLimit(60);
	sf::Image icon;
	icon.loadFromFile("Icon.png");
	window.setIcon(icon.getSize().x, icon.getSize().y, icon.getPixelsPtr());
	sf::Clock	dtClock;

	//Objects
	Score			score("KBZipaDeeDooDah.ttf");
	World			world("Grass.png", { 1000,1000 });
	Snake			snake(window,world,score,"SnakeHead.png");
	MouseSpawner	spawner(&window,"Mouse.png", snake);
	Button			playButton([&]() {currentState = INGAME; }, "PlayButton.png");
	Button			quitButton([&]() {currentState = EXITING; }, "QuitButton.png");
	Menu			menu(window,{ playButton, quitButton });



	while (window.isOpen())
	{
		if (currentState == EXITING)
		{
			window.close();
			continue;
		}
		auto dt(dtClock.restart().asSeconds());
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
			{
				currentState = EXITING;
			}

			switch (currentState)
			{
			case MENU:
				menu.handleEvent(event);
				break;
			case INGAME:
				if (event.type == sf::Event::KeyPressed)
				{
					switch (event.key.code)
					{
						//escape to pause
					case sf::Keyboard::Escape:
						currentState = MENU;
						break;
					default:
						break;
					}
				}
				break;
			default:
				break;
			}
		}

		window.clear(sf::Color(50,150, 255));	//because Sea!

		if (currentState == INGAME)
		{
			//update objects if in game (i.e. not paused)
			snake.update(dt);
			spawner.checkCollisions();
			spawner.spawn();
		}

		//draw the essentials (with the correct view)
		window.setView(snake.getView());
		window.draw(world);
		spawner.draw();
		window.draw(snake);

		//default view for score (and menu, if needed)
		window.setView(window.getDefaultView());
		window.draw(score);

		if (currentState == MENU)
			window.draw(menu);

		window.display();
		sf::sleep(sf::seconds(0));
	}
	window.close();

	return 0;
};
Example #18
0
int align_get_dist(int i1, int j1, int i2, int j2, int limit)
{
        int *last_d, *temp_d;
        int goal_diag, ll, uu;
        int c, k, row;
        int start, lower, upper;
                
        /* Compute the boundary diagonals */
        start = j1 - i1;
        lower = max(j1-i2, start-limit);
        upper = min(j2-i1, start+limit);
        goal_diag = j2-i2;
       
        if (goal_diag > upper || goal_diag < lower) {
           (void)fprintf(stderr, "The two sequences are not really similar.\n");
           (void)fprintf(stderr, "Please try an exact aligning method.\n");
           exit(1);
        }       
                      
        /* Allocate space for forward vectors */ 
        last_d = (int *)ckalloc((upper-lower+1)*sizeof(int)) - lower;
        temp_d = (int *)ckalloc((upper-lower+1)*sizeof(int)) - lower;

        /* Initialization */
        for (k=lower; k<=upper; ++k) last_d[k] = MININT;
        last_d[start] = snake(start, i1, i2, j2);
        
        if (last_d[goal_diag] >= i2) {
                /* Free working vectors */
                free(last_d+lower);
                free(temp_d+lower);
                return 0;
        }

        for (c=1; c<=limit; ++c) {
          ll = max(lower,start-c); uu = min(upper, start+c);
          for (k=ll; k<=uu; ++k) {
               if (k == ll)
                        row = last_d[k+1]+1;    /* DELETE */
               else if (k == uu)
                        row = last_d[k-1];      /* INSERT */
               else if ((last_d[k]>=last_d[k+1]) &&
                             (last_d[k]+1>=last_d[k-1]))
                        row = last_d[k]+1;      /*SUBSTITUTE */
               else if ((last_d[k+1]+1>=last_d[k-1]) &&
                             (last_d[k+1]>=last_d[k]))
                        row = last_d[k+1]+1;    /* DELETE */
               else
                        row = last_d[k-1];      /* INSERT */
                
               temp_d[k] = snake(k,row,i2,j2);
          }     
                      
          for (k=ll; k<=uu; ++k) last_d[k] = temp_d[k];

          if (last_d[goal_diag] >= i2) {
#ifdef STATS
                 (void)fprintf(stderr, "get_dist = %d\n",c);
#endif
        
                 /* Free working vectors */
                    free(last_d+lower);
                    free(temp_d+lower);
                    return c;
           }
        }

        /* Ran out of distance limit */
        return -1;
}
Example #19
0
void    align_path(int i1, int j1, int i2, int j2, int dist, edit_script **head, edit_script **tail)
{

        int     *last_d, *temp_d,       /* forward vectors */
                *rlast_d, *rtemp_d;     /* backward vectors */

        edit_script *head1, *tail1, *head2, *tail2;
        int midc, rmidc;
        int start, lower, upper;
        int rstart, rlower, rupper;
        int c, k, row;
        int mi, mj, tmp, ll, uu;
        char flag;

        *head = *tail = NULL;

        /* Boundary cases */
        if (i1 == i2) {
           if (j1 == j2) *head = NULL;
           else {
                head1 = (edit_script *) ckalloc(sizeof(edit_script));
                head1->op_type = INSERT;
                head1->num = j2-j1;
                head1->next = NULL;
                *head = *tail = head1;
           }
           return;
        }

        if (j1 == j2) {
                head1 = (edit_script *) ckalloc(sizeof(edit_script));
                head1->op_type = DELETE;
                head1->num = i2-i1;
                head1->next = NULL;
                *head = *tail = head1;
                return;
        }

        if (dist <= 1) {
           start = j1-i1; 
           if (j2-i2 == j1-i1) {
                head1 = (edit_script *) ckalloc(sizeof(edit_script));
                head1->op_type = SUBSTITUTE;
                head1->num = i2-i1;
                head1->next = NULL;
                *head = *tail = head1;
           } else if (j2-j1 == i2-i1+1) {

                tmp = snake(start,i1,i2,j2);
                if (tmp>i1) {
                    head1 = (edit_script *) ckalloc(sizeof(edit_script));
                    head1->op_type = SUBSTITUTE;
                    head1->num = tmp-i1;
                    *head = head1;
                }
                head2 = (edit_script *) ckalloc(sizeof(edit_script));
                head2->op_type = INSERT;
                head2->num = 1;

                if (*head) head1->next = head2; 
                else *head = head2; 
                *tail = head2;
                head2->next = NULL;

                if (i2-tmp) {
                    head1 = head2;
                    *tail = head2 = (edit_script *)ckalloc(sizeof(edit_script));
                    head2->op_type = SUBSTITUTE;
                    head2->num = i2-tmp;
                    head2->next = NULL;
                    head1->next = head2;
                } 
           } else if (j2-j1+1 == i2-i1) {

                tmp = snake(start,i1,i2,j2);
                if (tmp>i1) {
                    head1 = (edit_script *) ckalloc(sizeof(edit_script));
                    head1->op_type = SUBSTITUTE;
                    head1->num = tmp-i1;
                    *head = head1;
                }
                head2 = (edit_script *) ckalloc(sizeof(edit_script));
                head2->op_type = DELETE;
                head2->num = 1;

                if (*head) head1->next = head2;
                else *head = head2;
                *tail = head2;
                head2->next = NULL;

                if (i2>tmp+1) {
                    head1 = head2;
                    *tail = head2 = (edit_script *)ckalloc(sizeof(edit_script));
                    head2->op_type = SUBSTITUTE;
                    head2->num = i2-tmp-1;
                    head2->next = NULL;
                    head1->next = head2;
                }
           } else {
                (void)fprintf(stderr, 
                      "align.c: warning: something wrong when aligning."); 
           }                
           return;
        }
                
        /* Divide the problem at the middle cost */
        midc = dist/2;
        rmidc = dist - midc;
                
        /* Compute the boundary diagonals */
        start = j1 - i1;
        lower = max(j1-i2, start-midc);
        upper = min(j2-i1, start+midc);
        rstart = j2-i2; 
        rlower = max(j1-i2, rstart-rmidc);
        rupper = min(j2-i1, rstart+rmidc);

        /* Allocate space for forward vectors */
        last_d = (int *)ckalloc((upper-lower+1)*sizeof(int)) - lower;
        temp_d = (int *)ckalloc((upper-lower+1)*sizeof(int)) - lower;

        for (k=lower; k<=upper; k++) last_d[k] = -1;
        last_d[start] = snake(start,i1,i2,j2);
                
        /* Forward computation */  
        for (c=1; c<=midc; ++c) {
             ll = max(lower,start-c); 
             uu = min(upper,start+c);
             for (k=ll; k<=uu; ++k) {
                  if (k == ll) {
                      /* DELETE : down from (k+1,c-1) */
                      row = last_d[k+1]+1;
                  } else if (k == uu) {
                      /* INSERT : right from (k-1,c-1) */
                      row = last_d[k-1];
                  } else if ((last_d[k]>=last_d[k+1]) &&
                             (last_d[k]+1>=last_d[k-1])) {
                      /* SUBSTITUTE */
                      row = last_d[k]+1;
                  } else if ((last_d[k+1]+1>=last_d[k-1]) &&
                             (last_d[k+1]>=last_d[k])) {
                      /* DELETE */
                      row = last_d[k+1]+1;
                  } else {
                      /* INSERT */
                      row = last_d[k-1];
                  }

                  temp_d[k] = snake(k,row,i2,j2);
             } 
             for (k=ll; k<=uu; ++k)
                  last_d[k] = temp_d[k];
       }

        /* Allocate space for backward vectors */
        rlast_d = (int *)ckalloc((rupper-rlower+1)*sizeof(int)) - rlower;
        rtemp_d = (int *)ckalloc((rupper-rlower+1)*sizeof(int)) - rlower;

        for (k=rlower; k<=rupper; k++) rlast_d[k] = i2+1;
        rlast_d[rstart] = rsnake(rstart,i2,i1,j1,M);

        /* Backward computation */
        for (c=1; c<=rmidc; ++c) {
             ll = max(rlower,rstart-c);
             uu = min(rupper,rstart+c);
             for (k=ll; k<=uu; ++k) {
                  if (k == ll) {
                      /* INSERT : left from (k+1,c-1) */
                      row = rlast_d[k+1];
                  } else if (k == uu) {
                      /* DELETE : up from (k-1,c-1) */  
                      row = rlast_d[k-1]-1;
                  } else if ((rlast_d[k]-1<=rlast_d[k+1]) &&
                             (rlast_d[k]-1<=rlast_d[k-1]-1)) {
                      /* SUBSTITUTE */
                      row = rlast_d[k]-1;
                  } else if ((rlast_d[k-1]-1<=rlast_d[k+1]) &&
                             (rlast_d[k-1]-1<=rlast_d[k]-1)) {
                      /* DELETE */
                      row = rlast_d[k-1]-1;
                  } else {
                      /* INSERT */
                      row = rlast_d[k+1];
                  }
               
                  rtemp_d[k] = rsnake(k,row,i1,j1,M);
             }    
             for (k=ll; k<=uu; ++k)
                  rlast_d[k] = rtemp_d[k];
       }

       /* Find (mi, mj) such that the distance from (i1, j1) to (mi, mj) is
          midc and the distance from (mi, mj) to (i2, j2) is rmidc.
        */

       flag = SIMFALSE;
       mi = i1; mj = j1;
       ll = max(lower,rlower); uu = min(upper,rupper);
       for (k=ll; k<=uu; ++k) {
            if (last_d[k]>=rlast_d[k]) {
                if (last_d[k]-i1>=i2-rlast_d[k]) {
                    mi = last_d[k]; mj = k+mi;
                } else {
                    mi = rlast_d[k]; mj = k+mi; 
                } 
                flag = SIMTRUE;

                break;
            }         
       }              
       free(last_d+lower); free(rlast_d+rlower);
       free(temp_d+lower); free(rtemp_d+rlower);
                      
       if (flag) {    
                /* Find a path from (i1,j1) to (mi,mj) */
                align_path(i1,j1,mi,mj,midc,&head1,&tail1);
                      
                /* Find a path from (mi,mj) to (i2,j2) */
                align_path(mi,mj,i2,j2,rmidc,&head2,&tail2);
                      
                /* Join these two paths together */
                if (head1) tail1->next = head2;
                else head1 = head2;
        } else {  
                (void)fprintf(stderr, 
                      "align.c: warning: something wrong when dividing\n");
                head1 = NULL;
        }         
        *head = head1;
        if (head2) *tail = tail2;
        else *tail = tail1;
}
Example #20
0
void CPlayState::Update(CGameEngine* game)
{
  sf::Vector2u window_size = game->window.getSize();

	//System Constants
  unsigned WINDOW_WIDTH = window_size.x;
  unsigned WINDOW_HEIGHT = window_size.y;
  unsigned FPS = 60;
  double PI = 3.14159265;

  //Window Settings
  /*
  sf::ContextSettings settings;
  settings.antialiasingLevel = 8;
  sf::RenderWindow window(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "Runner", sf::Style::Default, settings);
  window.setVerticalSyncEnabled(true);
  */

  sf::RenderWindow& window = game->window;

  double lastFrameTimeStamp = GetTickCount(); // GetTickCount is for Windows only
  double frame_length = 1000/FPS;

  //random generator
  std::default_random_engine rand_generator;
  rand_generator.seed(time(0)); // seed will only change once per second
  std::uniform_int_distribution<unsigned> random_x(25,WINDOW_WIDTH-25);
  std::uniform_int_distribution<unsigned> random_y(25,WINDOW_HEIGHT-25);


//-----------------------------------
  //LOAD SOUND FILES

  sf::SoundBuffer buffer;
  if (!buffer.loadFromFile("eat.wav")) {
    //error loading file
  }
  sf::Sound eatsound;
  eatsound.setBuffer(buffer);
  eatsound.setVolume(30);

  sf::SoundBuffer buffer2;
  if (!buffer2.loadFromFile("gameover.wav")) {
    //error loading file
  }
  sf::Sound gameoversound;
  gameoversound.setBuffer(buffer2);
  gameoversound.setVolume(30);


//-----------------------------------
  //LOAD FONT AND TEXT

  //Set Default font and text settings
  sf::Font font;
  font.loadFromFile("arial.ttf");
  sf::Text default_text_settings;
  default_text_settings.setFont(font);
  default_text_settings.setColor(sf::Color(254,255,221,100));
  default_text_settings.setStyle(sf::Text::Bold);
  default_text_settings.setCharacterSize(24);

  sf::Text displayscore = default_text_settings;
  displayscore.setPosition(500,50);

//--------------------------------------
  //INITIALIZE GAME OBJECTS

  //game variables
  bool collision = false;
  bool game_running = true;
  double snake_speed = game->m_GameMode.getGameSpeed();
  std::string gamespeed = "normal";
  unsigned directional_speed = 10;
  double hitbox = 2.2;
  unsigned score = 0;
  if(game->m_GameMode.getGameSpeed() == .30) {
      gamespeed = "fast";
      directional_speed = 15;
      hitbox = 3.3;
  }

  //snake
  unsigned snake_width = 10;
  unsigned snake_height = 10;
  int snake_length = 0;
  float snake_direction = 0;
  sf::Vector2f snake_coord;

  //snake head
  sf::RectangleShape snake(sf::Vector2f(snake_width*2, snake_height*2));
  snake.setPosition(WINDOW_WIDTH/2, WINDOW_HEIGHT/2);
  snake.setOrigin(snake_width, snake_height);

  //snake head
  sf::Texture snakehead;
  if (!snakehead.loadFromFile("snake_head.gif")) {
                // error...
  }
  snakehead.setSmooth(true);
  snake.setTexture(&snakehead);

  //snake skin
  sf::Texture snaketexture;
  if (!snaketexture.loadFromFile("snake_skin.gif")) {
                // error...
  }
  snaketexture.setSmooth(true);
  //snake.setTexture(&snaketexture);

  //snake body
  std::deque<sf::RectangleShape> snake_body{};
  sf::Vector2f snake_body_coord;

  //store past snake coordinates
  std::queue<sf::Vector2f> snake_history;

  //food
  sf::RectangleShape food(sf::Vector2f(6, 6));
  food.setFillColor(sf::Color(255,153,0));
  food.setPosition(random_x(rand_generator), random_y(rand_generator));
  sf::Vector2f food_coord;

  //background
  sf::Texture bgtexture;
  if (!bgtexture.loadFromFile("grassbackground2.jpg",sf::IntRect(0,0,640,480))) {
  //error
  }
  sf::Sprite bgsprite;
  bgsprite.setTexture(bgtexture);


//---------------------------------------



  //GAME LOOP

    while(game_running)
    {
      double currentTimeStamp = GetTickCount();
      if(currentTimeStamp - lastFrameTimeStamp >= frame_length)
      {

        //EVENT HANDLER
        sf::Event event;
        while (window.pollEvent(event))
        {
          switch (event.type)
          {
            case sf::Event::Closed:
              window.close();
              game->Quit();
              break;
          }
        }

        //USER INPUT HANDLER
        if(game->m_ControlMode.getControlType() == "keyboard") {
          if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
            snake_direction -= directional_speed;// move left
          }
          if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
            snake_direction += directional_speed; // move right
          }
        }

        if(game->m_ControlMode.getControlType() == "mouse") {
          if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
            snake_direction -= directional_speed; // move left
          }
          if (sf::Mouse::isButtonPressed(sf::Mouse::Right)) {
            snake_direction += directional_speed;// move right
          }
        }


        //GAME LOGIC

        //store past coordinates
        snake_coord = snake.getPosition();
        snake_history.push(snake_coord);

        //limit size of history queue so it doesn't grow too large
        if (snake_history.size() > snake_length + 10)
        {
          snake_history.pop();
        }

        //Create new snake shape
        sf::RectangleShape snake_temp(sf::Vector2f(snake_width, snake_height));
        //snake_temp.setFillColor(sf::Color(128,128,0));
        snake_temp.setPosition(snake_history.back());
        snake_temp.setOrigin(snake_width/2, snake_height/2);
        snake_temp.setTexture(&snaketexture);

        //Add new temporary snake shape to vector
        snake_body.push_back(snake_temp);

        //remove oldest snake shape from snake body if snake did not grow
        if(snake_body.size() > snake_length)
        {
          snake_body.pop_front();
        }

        //change snake head angle
        snake.setRotation(snake_direction);

        //move snake head forward
        snake.move((snake_speed * frame_length)*sin(snake_direction * PI / 180),
                   (snake_speed * frame_length)*-cos(snake_direction * PI / 180));


        //check if snake hit edge of window
        snake_coord = snake.getPosition();
        if(snake_coord.x - snake_width < 0)
        {
          std::cout<< "Game Over: left edge hit" << std::endl;
          collision = true;
        }
        if(snake_coord.y - snake_height < 0)
        {
          std::cout<< "Game Over: top edge hit" << std::endl;
          collision = true;
        }
        if(snake_coord.x + snake_width > WINDOW_WIDTH)
        {
          std::cout<< "Game Over: right edge hit" << std::endl;
          collision = true;
        }
        if(snake_coord.y + snake_height> WINDOW_HEIGHT)
        {
          std::cout<< "Game Over: bottom edge hit" << std::endl;
          collision = true;
        }

        //SURVIVAL GAME MODE
        if(game->m_GameMode.getGameType() == "survival") {
          snake_length++;
        }

        //check if snake ate food
        snake_coord = snake.getPosition();
        food_coord = food.getPosition();

        if ((snake_coord.x <= food_coord.x + snake_width) &&
            (snake_coord.x >= food_coord.x - snake_width) &&
            (snake_coord.y <= food_coord.y + snake_height) &&
            (snake_coord.y >= food_coord.y - snake_height))
        {
          food.setPosition(random_x(rand_generator), random_y(rand_generator));
          snake_length += 5;
          eatsound.play();
          score++;
        }

        //check for snake head and snake body collision
        for(std::deque<sf::RectangleShape>::size_type i = 0; i != snake_body.size(); i++) {
          snake_body_coord = snake_body[i].getPosition();


          if ((snake_coord.x <= snake_body_coord.x + hitbox) &&
              (snake_coord.x >= snake_body_coord.x - hitbox) &&
              (snake_coord.y <= snake_body_coord.y + hitbox) &&
              (snake_coord.y >= snake_body_coord.y - hitbox))   {
                  std::cout << "Game Over: Collision with body piece: #" << i << std::endl;
                  collision = true;
                  break;
          }
        }

        //GAME OVER CONDITION
        if (collision) {
          gameoversound.play();

          //Store the score in the file
          std::ofstream file;
          file.open ("highscores.txt", std::ios_base::app | std::ios_base::out);
          file << game->m_GameMode.getGameType() << "," << gamespeed << "," << score << "\r";
          file.close();

          Sleep(1000);
          game_running = false;
          game->PopState();
          game->PopState();
          break;
        }

        std::ostringstream ss;
        ss << score;
        displayscore.setString( std::string( "Score: "+ss.str() ) );

        //RENDER
        window.clear();

        window.draw(bgsprite);

        for(std::deque<sf::RectangleShape>::size_type i = snake_body.size(); i != 0; --i) {
          window.draw(snake_body[i-1]); //i != vector.size
        }
        window.draw(snake); //head drawn after body so it is on top
        window.draw(food);
        window.draw(displayscore);
        window.display();

        lastFrameTimeStamp = currentTimeStamp;

        //DEBUG
        //std::cout << snake_body.size();

      }

      Sleep(1); // saves some cpu

    } //end core game loop

}
Example #21
0
//**********************************************************************************************************************
// 
//**********************************************************************************************************************
void Snake::reset(QPoint const& position)
{
   Snake snake(position);
   this->swap(snake);
}
void inplace_1_isto_2_transpose_generic(int *x, const int &L, const int &M)
{
    int *te = new int[AVAIL_MEM >> 1];
    int *to = new int[AVAIL_MEM >> 1];
    int max_capacity = (AVAIL_MEM >> 1) / L;
    if (max_capacity <= 0)
    {
        std::cout << "\nIn-place transpose cannot be performed within specified memory constraints.\n";
        exit(1);
    }
    int num_lines_loaded = get_num_lines_to_be_loaded(max_capacity, L);
    int num_reduced_row = std::ceil( (float) M / (float) (2 * num_lines_loaded)); 
    int num_reduced_col = 2;
    /* The reduced row and col comes from the fact that we perform swaps of 'num_lines_loaded' rows first
       and thus reducing the amount of swaps required to be done using the snake function*/
    int i;

    if (num_lines_loaded > 1)
    {
        for (i = 0; i < M; i += 2 * num_lines_loaded)
        {
            // read
            for (int p = 0; p < num_lines_loaded; p++)
            {
                for (int j = 0; j < L; j++)
                {
                    te[p*L + j] = x[i*L + (2 * p + 0)*L + j];
                    to[p*L + j] = x[i*L + (2 * p + 1)*L + j];
                }
            }

            // write
            for (int p = 0; p < num_lines_loaded; p++)
            {
                for (int j = 0; j < L; j++)
                {
                    x[i*L + 0 + p*L + j] = te[p*L + j];
                    x[i*L + num_lines_loaded*L + p*L + j] = to[p*L + j];
                }
            }
        }
    }
    int *cycle_map = new int[num_reduced_row * num_reduced_col * 2];
    /* The memory required by cycle_map canniot exceed 2 times row*col by design*/

    get_cycles(cycle_map, num_reduced_row, num_reduced_col);

    int *ta = te;
    int *tb = to;
    int *ttmp;

    int inx = 0, start_inx;
    for (i = 0; i < cycle_map[0]; i++)
    {
        start_inx = cycle_map[++inx];
        std::cout << "\nCycle:" << (i + 1) <<">\t"<< "("<<start_inx <<","<< cycle_map[inx + 1] <<")";
        snake(x, ta, tb, L, num_lines_loaded, start_inx, cycle_map[inx + 1], 0);

        while (start_inx != cycle_map[++inx])
        {
            ttmp = ta;
            ta = tb;
            tb = ttmp;

            std::cout <<"\t" << "(" <<cycle_map[inx] << "," << cycle_map[inx + 1] << ")";
            int action_var = (cycle_map[inx + 1] == start_inx) ? 2 : 1;
            snake(x, ta, tb, L, num_lines_loaded, cycle_map[inx], cycle_map[inx + 1], action_var);
        }
    }

    delete[] te;
    delete[] to;
}