//==============================================================================
//
// Snake
// -----
// http://www.masterspace.biz/andreschnabel/
// 2006 by André Schnabel (thefrogs@web.de)
//
//==============================================================================

// apples.c

#include "globals.h"
#include "apples.h"

apple_t apples[MAX_APPLES];
Uint32 lAppleSpawn;

// Initializes the array of apples
void InitApples(void)
{
	int i;
	
	for(i=0; i<MAX_APPLES; i++)
	{
		apples[i].active = false;
		apples[i].x = apples[i].y = 0;
	}
	
	lAppleSpawn = SDL_GetTicks();
}

// Put a new apple on the game board
void SpawnApple(int x, int y)
{
	int i;
	
	for(i=0; i<MAX_APPLES; i++)
	{
		if(!apples[i].active)
		{
			apples[i].x = x;
			apples[i].y = y;
			apples[i].active = true;
			break;
		}
	}
}

// Draws all apples
void DrawApples(void)
{
	int i;
	static SDL_Rect rect;
	
	rect.w = appleImg->w;
	rect.h = appleImg->h;
	
	for(i=0; i<MAX_APPLES; i++)
	{
		if(apples[i].active)
		{
			rect.x = apples[i].x;
			rect.y = apples[i].y;
			
			SDL_BlitSurface(appleImg, NULL, screen, &rect);
		}
	}
}

// So the snake can grow
boolean AppleOnPos(int x, int y, snake_t *snake)
{
	int i;
	
	for(i=0; i<MAX_APPLES; i++)
	{
		if(apples[i].active)
		{
			if(apples[i].x == x && apples[i].y == y)
			{
				char outStr[100];
				
				apples[i].active = false;
				
				snake->score += snake->speed;
				sprintf(outStr, "Player %d eats an apple!", snake->nr);
				
				AddMessage(outStr);
				
#ifndef NO_SOUND
				Mix_PlayChannel(-1, eatSnd, 0);
#endif
				return true;
			}
		}
	}
	
	return false;
}

void UpdateApples(void)
{
	// Spawn apples if necessary
	if(SDL_GetTicks() - lAppleSpawn > APPLE_SPAWNTIME)
	{
		int newAppleX, newAppleY;
		int i;
		boolean repeat = false;
		
		do
		{
			newAppleX = rand() % ((SCR_W - BLOCK_W) / BLOCK_W);
			newAppleY = rand() % ((SCR_H - BLOCK_H) / BLOCK_H);
		
			newAppleX *= BLOCK_W;
			newAppleY *= BLOCK_H;
			
			for(i=0; i<numPlayers; i++)
			{
				if(AlreadyBlockOnPos(newAppleX, newAppleY, &players[i]))
				{
					repeat = true;
					break;
				}
				else
					repeat = false;
			}
			
		} while(TileOnPos(newAppleX, newAppleY) || repeat);
		
		SpawnApple(newAppleX, newAppleY);
		lAppleSpawn = SDL_GetTicks();
	}
}
