#include <ncurses.h>
#include "ncsnake.h"
#include <stdlib.h>

/*Hässliche Funktion, riesig groß. Aber es ist ja mehr ein Experiment mit ncurses...*/
char snakemain(WINDOW *w){
	int xmax, ymax;
	int *xsnake, *ysnake;
	int dirx, diry;
	int snakelength = 3;
	char noerror=1;
	int foodx, foody;

	getmaxyx(w,xmax,ymax);
	//Das Spielfeld sollte mindestens 6x6 sein
	if(xmax<6||ymax<6) return 0;

	//Brute-Force: Ich allokiere einfach so viel Speicher, wie die Schlange maximal lang werden kann
	xsnake = calloc((ymax+1)*(xmax+1), sizeof(int));
	ysnake = calloc((ymax+1)*(xmax+1), sizeof(int));

	//Überprüfen...
	if(xsnake == NULL || ysnake == NULL){
		free(xsnake);
		free(ysnake);
		return 0;
	}
	//initialisiere die Schlange
	ysnake[2] = (ysnake[1] = (ysnake[0] = ymax/3)+1)+1;
	xsnake[0] = xsnake[1] = xsnake[2] = xmax/3;
	dirx = 0;
	diry = -1;
	place_food(snakelength, xsnake, ysnake, xmax, ymax, &foodx, &foody);
	paint_snake(w, snakelength, xsnake, ysnake);
	wrefresh(w);
	char gameend=0;
	while(!gameend){
		int c;
		c = getch();
		switch(c){
			case 'q':
				gameend=1;
				break;
			case KEY_RIGHT:
				dirx=0;
				if(diry!=-1)
					diry=1;
				break;
			case KEY_LEFT:
				dirx=0;
				if(diry!=1)
					diry=-1;
				break;
			case KEY_UP:
				if(dirx!=1)
					dirx=-1;
				diry=0;
				break;
			case KEY_DOWN:
				if(dirx!=-1)
					dirx=1;
				diry=0;
				break;
		}
		//Futter gefressen?
		if(foodx == xsnake[0] && foody == ysnake[0]){
			snakelength++;
			place_food(snakelength, xsnake, ysnake, xmax, ymax, &foodx, &foody);
		}
		move_snake(snakelength, xsnake, ysnake, dirx, diry);
		werase(w);
		paint_snake(w, snakelength, xsnake, ysnake);
		//Futter malen
		mvwprintw(w, foodx, foody, "o");
		wrefresh(w);
		if(collision_snake(snakelength, xsnake, ysnake, xmax, ymax)){
			break;
		}
		napms(50);
	}
		
	free(xsnake);
	free(ysnake);

	return noerror;
}

int main(int argc, char argv[]){
	WINDOW *w = initscr();
	int returnvalue=0;
	
	cbreak();
	noecho();
	nodelay(w, 1);

	keypad(w, 1);
	
	scrollok(w, 0);
	
	if(!snakemain(w))
		returnvalue++;
		

	endwin();
	return 0;
}
