import pygame
import gfx

images = ['ground_a0', 'dither']


class Tile:
    maxfood = 100
    food = 0
    iswater = 0
    isblocked = 0
    fertilize = 0
    def __init__(self):
    	self.image = images.ground_a0




class Map:
    def __init__(self):
	tilew, tileh = 200, 190
	self.drawloop = [((x+1), (y+1), (x-1)*tilew, (y-1)*tileh+2)
	    	    	 for y in range(480/tileh+2) for x in range(640/tilew+2)]
	self.tilesx = 10
	self.tilesy = 10
	self.tilew = tilew
	self.tileh = tileh
    	
	self.tiles = [Tile() for x in range(self.tilesx*self.tilesy)]
	
	#f = pygame.font.Font(None, 20)
    	#for x in range(self.tilesx):
	#    for y in range(self.tilesy):
	#    	tile = self.tile(x,y)
	#    	i = gfx.optimize(tile.image)
	#	t = f.render('%dx%d'%(x,y), 0, (255,255,255), (0,0,0))
	#    	i.blit(t, (0, 0))
	#	tile.image = i

    def viewtile(self, x, y):
    	x = x * self.tilew + self.tilew / 2 - 360
	y = y * self.tileh + self.tileh / 2 - 240
	return x, y

    def tilepos(self, x, y):
    	x = x * self.tilew + self.tilew / 2
	y = y * self.tileh + self.tileh / 2
	return x, y

    def pos_to_mapcoord(self, x, y):
    	return x/self.tilew, y/self.tileh
	
    def tile(self, x, y): 
	if x<0 or y<0 or x>=self.tilesx or y>=self.tilesy:
	    #print '  OOB', x, y
	    return self.tiles[0]
	return self.tiles[y*self.tilesx+x]

    	
	
    def draw(self, screen, px, py):
    	blit = screen.blit
	px -= 320
	py -= 240
	xoffs = self.tilew - (px % self.tilew)
	yoffs = self.tileh - (py % self.tileh)
	xtile = px / self.tilew
	ytile = py / self.tileh	
	
    	for x,y,xpos,ypos in self.drawloop:
	    tile = self.tile(x+xtile, y+ytile)
	    pos = xpos+xoffs, ypos+yoffs
	    blit(tile.image, pos)
	
	    


