/* Création du plateau de jeu avec les pastilles et le serpent

   written by Yann KERAUDREN and Titouan LERICHE*/


#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "plateau_init.h"

  
  
struct adresse* plateau_init(void) {

  int ligne_pomme, colonne_pomme, i;

  unsigned char* tete = NULL;
  unsigned short* indice_queue = NULL;
  unsigned short* taille_serpent = NULL; 

  int** corps_serpent = NULL;
  
  int** plateau  = NULL;


  struct adresse* pointeur = NULL;

  
  srand(time(NULL));



  

  /* allocation du pointeur */

  pointeur = malloc(sizeof( struct adresse));



  

  /* allocation du tableau tete et queue */

  tete =  malloc(2 * sizeof(unsigned char));

  indice_queue =  malloc(sizeof(unsigned short));




  
  /* allocation du plateau dans le tas */
  
  plateau = calloc(LIGNES, sizeof(int*));
  
  for ( i = 0; i < LIGNES; i++)  {

    plateau[i] = calloc(COLONNES, sizeof(int));

  }



  
  /* allocation du corps du serpent */

  corps_serpent = malloc(TAILLE_SERPENT * sizeof(int*));

  for ( i = 0; i < TAILLE_SERPENT; i++) {

    corps_serpent[i] = malloc( 2 * sizeof(int));

  }



  /* allocation de la taille du serpent */

  taille_serpent = malloc(sizeof(unsigned short));
  

  /* positionnement du serpent et marquage de la tete et la queue */

  tete[0] = ((LIGNES/2)+(TAILLE_SERPENT/2)-1);
  tete[1] = COLONNES/2 ;

  


  for (i = 0; i < TAILLE_SERPENT ; i++)  {

    plateau[((LIGNES/2)-5)+i][COLONNES/2] = 1;

    
    corps_serpent[i][0] = ((LIGNES/2)-5) + i;
    corps_serpent[i][1] = COLONNES/2;

  }


  /* positionnement alétoire des pommes */

  for ( i = 0; i < NBR_POMME; i++)  {
    
  
    ligne_pomme = rand() % 40;
    colonne_pomme = rand() % 60;

    
    /* teste pour faire apparaitre exactement 5 pommes */
    
    while (plateau[ligne_pomme][colonne_pomme] == 2 || plateau[ligne_pomme][colonne_pomme] == 1)  {

      ligne_pomme = rand() % 40;
      colonne_pomme = rand() % 60;
    }


    
    /* le chiffre "2" definit une pomme */
    
    plateau[ligne_pomme][colonne_pomme] = 2;

  }


  *taille_serpent = TAILLE_SERPENT;

  *indice_queue = 0; 
  
  pointeur -> plateau = plateau;
  pointeur -> tete = tete;
  pointeur -> indice_queue = indice_queue; 
  pointeur -> corps_serpent = corps_serpent;
  pointeur -> taille_serpent = taille_serpent; 
  

  
  return pointeur;
}