Beispiel #1
0
// check if the snake collides with a fruit
int check_fruit_collision(GAME* game, int cury, int curx) {
  // calculate the range, limit the range to a maximum of 5
  int range = (game->snake.eat_range >= 5 ? 5 : game->snake.eat_range) - 1;
  // calculate the start position
  int startx = curx - range;
  int starty = cury - range;
  // calculate the end position
  int endx = startx + range * 2 + 1;
  int endy = starty + range * 2 + 1;
  int x,y;

  int on = 0; // check if there is food in the calculated range
  // iterate througth every field inside the range
  for(x = startx; x  < endx; x++) {
    for(y = starty; y  < endy; y++) {
      // is a fruit on the current field?
      if(fruit_is_on(&game->fruits, y, x) != NULL) {
        // exclude the field in the middle
        if(!(curx == x && cury == y)) {
          // execute the handler for this field (to eat the fruit)
          check_fruit_collision_handler(game, y, x);
        }
        on = 1; // found one!
      }
    }
  }
  return on;
}
Beispiel #2
0
// remove a single fruit from the game by it's position
void kill_fruit(FRUITS *fruits, int posy, int posx) {
  FRUIT *fruit;
  // check if a fruit is on the given position
  if((fruit = fruit_is_on(fruits, posy, posx)) != NULL) {
    // remove the fruit
    kill_fruit_by_ptr(fruits, fruit);
  }
}
Beispiel #3
0
// calls the effect of the fruit
int check_fruit_collision_handler(GAME* game, int cury, int curx) {
  // the the fruit by the given position
  FRUIT *fruit = fruit_is_on(&game->fruits, cury, curx);
  // is one on this position?
  if(fruit != NULL) {
    // execute the effect of the fruit
    fruit->effect(game);

    WINDOW *win = newwin(1, 1, cury, curx);
    wprintw(win, " ");
    wrefresh(win);
    delwin(win);
    // remove the fruit from the game
    kill_fruit_by_ptr(&game->fruits, fruit);
  }
  return 1;
}
Beispiel #4
0
// create a new fruit in the game
void grow_fruit(GAME* game) {
  int randy,randx;
  // generate a new random position until a empty spot is found
  do {
    randy = rand() % game->rows;
    randx = rand() % game->columns;
    // is nothing else there in the generated position?
  } while (snake_part_is_on(&game->snake, randy, randx) != NULL || fruit_is_on(&game->fruits, randy, randx) != NULL || check_extended_border_collision(game, randy, randx));

  // increase the length
  game->fruits.length++;
  // allocate memory for the new fruit
  if(game->fruits.length == 0) {
    // initialize the array with malloc if it is the first fruit in the array
    game->fruits.fruits = malloc(sizeof(FRUIT) * game->fruits.length);
  } else {
    // allocate more memory
    game->fruits.fruits = realloc(game->fruits.fruits, sizeof(FRUIT) * game->fruits.length);
  }
  
  // get a filled struct (containing the displayed char, the effect & co.) of the new fruit
  get_fruit(&game->fruits.fruits[game->fruits.length - 1], randy, randx);
}