class 'chickenPerson' (D2Person)

chickenPerson.points = 
{
	{30, 6},
	{29, 2},
	{32, 4},
	{32, 7},
	{30, 11},
	{26, 12},
	{19, 18},
	{20, 21},
	{26, 23},
	{31, 23},
	{37, 24},
	{46, 23},
	{46, 19},
	{48, 15},
	{47, 13},
	{41, 12},
	{36, 12},
	{33, 12},
	{33, 8},
	{33, 3},
	{30, 3},
}

chickenPerson.pointIdx = 1
chickenPerson.pointsIntervalMin = 2000
chickenPerson.pointsIntervalMax = 2001
chickenPerson.areaWidthOffset = 3
chickenPerson.areaHeightOffset = 3

chickenPerson.pointsTimer = 0
chickenPerson.pointsTargetX = nil
chickenPerson.pointsTargetY = nil
chickenPerson.direction = nil

function chickenPerson:__init(baseName) super(baseName)

	self:setAnchorBotY(20)
	self:setDefaultAnimation("IDLE")
	self:setWalkTimePerNode(350)
	self:setShadowY(-5)

end

function chickenPerson:onCreate()

	D2Person.onCreate(self)
	self.pointsTimer = getRandomRange(self.pointsIntervalMin, self.pointsIntervalMax)
end

function chickenPerson:onTick(time)

	if (scene:isStartingMovie() or scene:isPlayingMovie()) then
		return
	end

	gridX = self:getPosition():getGridX()
	gridY = self:getPosition():getGridY()
	gridPos = grid:getNode(gridX, gridY)

	-- skips when walking to a new point (pointsTimer == 0)	
	if (self.pointsTimer > 0) then
		self.pointsTimer = self.pointsTimer - time
		if (self.pointsTimer <= 0) then
			-- walk to another point in the list
			targetX = self.points[self.pointIdx][1]
			targetY = self.points[self.pointIdx][2]
			
			self:incPointsIdx()
			
			gridMinX = math.max(0, targetX - self.areaWidthOffset)
			gridMaxX = math.min(GRID_SIZE_X-1, targetX + self.areaWidthOffset)
			gridMinY = math.max(0, targetY - self.areaHeightOffset)
			gridMaxY = math.min(GRID_SIZE_Y-1, targetY + self.areaHeightOffset)
			
			local n = 0
			while (n < 16) do			
				if (targetX ~= gridX and targetY ~= gridY) then
					local targetPos = grid:getNode(targetX, targetY)
					if (not targetPos:isBlocked()) then
						if (grid:existsPath(gridPos, targetPos)) then
							break						
						end
					end
				end
				targetX = getRandomRange(gridMinX, gridMaxX)
				targetY = getRandomRange(gridMinY, gridMaxY)
				n = n + 1
			end
			
			if (n < 16 and targetX ~= nil and targetY ~= nil) then
				self:setAppearance("L")
				self:qWalkToXY(targetX, targetY)
				self.pointsTargetX = targetX
				self.pointsTargetY = targetY
				self.pointsTimer = 0						
			else
				self.pointsTargetX = nil
				self.pointsTargetY = nil
				self.pointsTimer = 1
				self:incPointsIdx()
			end					
		end		
	end
	
	-- check if you reached points destination
	if (gridX == self.pointsTargetX and gridY == self.pointsTargetY) then
		self.pointsTargetX = nil
		self.pointsTargetY = nil
		self.pointsTimer = getRandomRange(self.pointsIntervalMin, self.pointsIntervalMax)
	end
	
	-- store current direction
	self.direction = self:getDirection()
	
end

function chickenPerson:incPointsIdx()
	self.pointIdx = self.pointIdx + 1
	if (self.pointIdx > table.getn(self.points)) then
		self.pointIdx = 1
	end	
end