#include <raylib.h>

#define MAX 10

struct cell {
	int x;
	int y;
	Color color;
};

int main(void)
{
	struct cell snake[10];
	struct cell apple;
	int dx = 1, dy = 0;
	int score = 0;
	int count = 4;
	int size = 20;
	int key;
	int i, j;
	int running = 1;

	j = 60;
	for (i = 0; i < count; i++) {
		snake[i].x = j;
		snake[i].y = 180;
		snake[i].color = BLUE;
		j -= 20;
	}
	snake[0].color = RED;
	apple.x = 260;
	apple.y = 100;
	apple.color = GREEN;

	InitWindow(480, 480, "snake");
	SetTargetFPS(8);
	SetExitKey(81);

	while (!WindowShouldClose()) {
		BeginDrawing();
		ClearBackground(RAYWHITE);
		if (running) {
			for (i = 0; i < GetScreenWidth()/size; i++) {
				DrawLine(i*size, 0, i*size, GetScreenHeight(), PURPLE);
			}
			for (i = 0; i < GetScreenHeight()/size; i++) {
				DrawLine(0, i*size, GetScreenWidth(), i*size, PURPLE);
			}
			DrawText(TextFormat("apple: %d", score), 5, 5, 20, BLACK);
			for (i = 0; i < count; i++) {
				DrawRectangle(snake[i].x, snake[i].y, size, size, snake[i].color);
			}
			DrawRectangle(apple.x, apple.y, size, size, apple.color);
		} else {
			DrawText("press r to reload", 5, 5, 20, BLACK);
		}
		EndDrawing();

		key = GetCharPressed();
		switch (key) {
		case 'l':
			dx = 1;
			dy = 0;
			break;
		case 'h':
			dx = -1;
			dy = 0;
			break;
		case 'j':
			dx = 0;
			dy = 1;
			break;
		case 'k':
			dx = 0;
			dy = -1;
			break;
		case 'r':
			running = 1;
		}

		if (running) {
			for (i = count-1; i > 0; i--) {
				snake[i].x = snake[i-1].x;
				snake[i].y = snake[i-1].y;
			}
			snake[0].x += dx * size;
			snake[0].y += dy * size;
			if (snake[0].x == apple.x && snake[0].y == apple.y) {
				if (count < MAX) {
					snake[count].x = snake[count-1].x;
					snake[count].y = snake[count-1].y;
					snake[count].color = snake[count-1].color;
					count++;
					score++;
					/* TODO: better math */
					apple.x = GetRandomValue(0, (GetScreenWidth()-size))/size*size;
					apple.y = GetRandomValue(0, (GetScreenHeight()-size))/size*size;
				} else {
					running = 0;
					score = 0;
					count = 4;
					dx = 1;
					dy = 0;
					snake[0].x = 60;
					snake[0].y = 180;
				}
			}
		}
	}

	CloseWindow();
	return 0;
}
