import pygame
from pygame.locals import *
import sys
import shelve
import atexit
import os.path
import glob
import pickle
import pygame.image
import pygame.font
import pygame.key
import pygame.mouse
import pygame.display
import pygame.mixer
import pygame.mixer_music
import pygame.time
import pygame.event
import pygame.mouse



class Event:
        """this is a superclass for any events that might be generated by an
        object and sent to the EventManager"""
        def __init__(self):
                self.name = "Generic Event"

class TickEvent(Event):
    def __init__(self):
        self.name = 'CPU Tick Event'

class QuitEvent(Event):
    def __init__(self):
        self.name = 'Program Quit Event'

class MapBuiltEvent(Event):
    def __init__(self, map):
        self.name = 'Map Finished Building Event'
        self.map = map

class GameStartedEvent(Event):
    def __init__(self, game):
        self.name = 'Game Started Event'
        self.game = game

class CharacterSelectRequest(Event):
    def __init__(self, species):
        self.name = 'Character Select Request'
        self.species = species

class CharacterPlaceEvent(Event):
    """
    This event occurs when a Character is *placed* in a sector, ie it doesn't
    move there from an adjacent sector.
    """
    def __init__(self, row, column, permission):
        self.name = 'Character Placement Event'
        self.column = column
        self.row = row
        self.permission = permission

        
#------------------------------------------------------------------------------

class EventManager:
        """this object is responsible for coordinating most communication
        between the Model, View, and Controller."""
        def __init__(self ):
                from weakref import WeakKeyDictionary
                self.listeners = WeakKeyDictionary()

        #----------------------------------------------------------------------
        def RegisterListener( self, listener ):
                self.listeners[ listener ] = 1

        #----------------------------------------------------------------------
        def UnregisterListener( self, listener ):
                if listener in self.listeners.keys():
                        del self.listeners[ listener ]

        #----------------------------------------------------------------------
        def Post( self, event ):
                for listener in self.listeners.keys():
                        #NOTE: If the weakref has died, it will be 
                        #automatically removed, so we don't have 
                        #to worry about it.
                        listener.Notify( event )

#------------------------------------------------------------------------------
class KeyboardController:
    """..."""
    def __init__(self, evManager):
        self.evManager = evManager
        self.evManager.RegisterListener(self)
        self.x = 0
        self.y = 0

    #----------------------------------------------------------------------
    def Notify(self, event):
        if isinstance(event, TickEvent):
            # Handle input events.
            for event in pygame.event.get():
                ev = None
                if event.type == KEYDOWN and event.key == K_ESCAPE:
                    ev = QuitEvent()
                elif event.type == KEYDOWN and event.key == K_a:
                    species = "animal"
                    ev = CharacterSelectRequest(species)
                elif event.type == KEYDOWN and event.key == K_s:
                    species = "plant"
                    ev = CharacterSelectRequest(species)
                elif event.type == KEYDOWN and event.key == K_c:
                    species = "info"
                    ev = CharacterSelectRequest(species)
                    
                elif event.type == KEYDOWN and event.key == K_RETURN:
                    ev = CharacterPlaceEvent( self.x, self.y, 0)
                if ev:
                    self.evManager.Post(ev)


#------------------------------------------------------------------------------
class CPUSpinnerController:
    """..."""
    def __init__(self, evManager):
        self.evManager = evManager
        self.evManager.RegisterListener(self)

        self.keepGoing = 1

    #----------------------------------------------------------------------
    def Run(self):
        while self.keepGoing:
            event = TickEvent()
            self.evManager.Post(event)

    #----------------------------------------------------------------------
    def Notify(self, event):
        if isinstance(event, QuitEvent):
            # This will stop the while loop from running.
            self.keepGoing = 0
            
###------------------------------------------------------------------------------
##class MouseController:
##    def __init__(self, state):
##        self.state = state
##
##    #----------------------------------------------------------------------
##    def Notify(self, event):
##        if isinstance(event, TickEvent):
##            for event in pygame.event.get():
##                ev = None
##                if event.type == pygame.MOUSEBUTTONDOWN:
##                    # User clicks the mouse. Get the position
##                    pos = pygame.mouse.get_pos()
##                    if pos[1] >= 500:
##                            continue
##                    # Change the x/y screen coordinates to grid coordinates
##                    elif pos[0] >= 500:
##                        if pos[0] >=520 and pos[0]<=620 and pos[1] >=20 and pos[1] <=120:
##                            species = "animal"
##                            ev = CharacterSelectRequest(species)
##                        if pos[0] >=520 and pos[0]<=620 and pos[1] >=150 and pos[1] <=250:
##                            species = "plant"
##                            ev = CharacterSelectRequest(species)
##                        if pos[0] >=520 and pos[0]<=620 and pos[1] >=280 and pos[1] <=380:
##                            species = "info"
##                            ev = CharacterSelectRequest(species)
##                    else:
##                        column=pos[0] // (width+margin)
##                        row=pos[1] // (height+margin)
##                        ev = CharacterPlaceRequest(row, column, 0)
##                        
##                    if ev:
##                        self.evManager.Post(ev)
##                    

#--------------------------------------------------------------------------------------
class Cell:

    #----------------------------------------------------------------------------
    # Terrain class: will (potentially) be split into new file later 
    class Terrain:
         def __init__(self, terrain):
            self.type = terrain


    #----------------------------------------------------------------------------
    # Organism class: will (potentially) be split into new file later 
    class Organism:

        def __init__(self, organism):
            #Set the type of the organism, plant, herbivore, omnivore, etc.
            #At the moment this is limited to place holder variables 1 and 2
            self.type = organism
            #1 and 2 (our dummy organisms) should have different ranges
            if organism == 2:
                self.range = 1
            else:
                self.range = 0

        def organismType(self):
            return self.organism

    #----------------------------------------------------------------------------
    # Initialize the cell with a terrain and an organism 
    def __init__(self):
        self.terrain = Cell.Terrain(1)
        self.organism = Cell.Organism(0)

    #----------------------------------------------------------------------------
    #Currently, we do not have various types of organisms, so if we were
    #to use this, we would merely put addOrganism(1) so that one is present.
    #Functionality will be added later to have different organism types etc.
    def addOrganism(self, organism):
        self.organism = Cell.Organism(organism)


    #----------------------------------------------------------------------------
    # Check to see if there is an organism 
    def isFull(self):
        return (self.organism.type != 0)


    #----------------------------------------------------------------------------
    # Pulls up the range of the organism in the cell 
    def cellRange(self):
        return self.organism.range


    #----------------------------------------------------------------------------
    # Returns the type of organism containted in the cell 
    def cellType(self):
        return self.organism.type

    #----------------------------------------------------------------------------
    # outputs info to the game's display about the specified cell 
    def displayInfo(self):
        ter = self.terrain.type
        typ = self.organism.type
        ran = self.organism.range
        print("Terrain type:" + str(ter))
        global message
        if typ == 0:
            print("No organism")
            message[1] = ("Terrain Type: 1")
        else:
            print("Organism type:" + str(typ))
            print("Organism range:" + str(ran))
            message[1] = ("Organism type:" + str(typ) + "  Organism range:" + str(ran))


###------------------------------------------------------------------------------
##class PygameView:
##    """..."""
##    def __init__(self, evManager):
##        self.evManager = evManager
##        self.evManager.RegisterListener(self)
##
##        self.plantNumber = 0
##        self.animalNumber = 0
##
##        pygame.init()
##        self.window = pygame.display.set_mode((640,550))
##        pygame.display.set_caption('Chain of Life')
##        self.background = pygame.Surface(self.window.get_size())
##        self.background.fill((0, 0, 0))
##
##        #--------------------------------------------------------------------
##        def drawButton(self, screen, color, x, y, width, height, message, fontsize):
##                fontobject = pygame.font.Font(None, fontsize)
##                pygame.draw.rect(screen, color, (x, y, width, height), 4)
##                if len(message) != 0:
##                    screen.blit(fontobject.render(message, 4, white, ), ( x + (width/4), y+(height/4)))
##
##        #--------------------------------------------------------------------_
##        def Notify(self, event):
##                if isinstance(event, TickEvent):
##                        output = gameBoard.Output()
##                        for row in range(.getRows()):
##                                for column in range(gameBoard.getCols()):
##                                    color = white
##                                    if gameBoard.grid[row][column].isFull():
##                                        if gameBoard.grid[row][column].cellType() == "plant:
##                                            color = green
##                                            self.plantNumber += 1
##                                        if gameBoard.grid[row][column].cellType() == "animal":
##                                            color = red
##                                            self.animalNumber += 1
##
##                        gameBoard.drawButton(screen, green, 520, 20, 100, 100, "PLANT", 100)
##                        if organismType.state == "a": ##highlights whats selected
##                        gameBoard.drawButton(screen, white, 516, 16, 108, 108, "", 0)
##                        gameBoard.drawButton(screen, red, 520, 150, 100, 100, "ANIMAL", 100)
##                        if organismType.state == "s": ##highlights whats selected
##                        gameBoard.drawButton(screen, white, 516, 146, 108, 108, "", 0)
##                        gameBoard.drawButton(screen, white, 520, 280, 100, 40, "INFO", 40)
##                        if organismType.state == "c": ##highlights whats selected
##                        gameBoard.drawButton(screen, white, 516, 276, 108, 48, "", 0)
##
##                elif isinstance(event, MapBuiltEvent):
##                        map = event.map
##                        self.ShowMap(map)
##                elif isinstance(event, CharacterPlaceEvent):
##                        self.ShowCharacter(event.charactor)
##                elif isinstance(event, CharacterMoveEvent):
##                        self.MoveCharacter(event.charactor)
##


#---------------------------------------------------------------------------------
class GameBoard:
        """..."""

        #STATE_PREPARING = 0
        #STATE_RUNNING = 1
        #STATE_PAUSED = 2

        #------------------------------------------------------------------
        def __init__(self, evManager, height, width):
                
    
                self.STATE_PREPARING = 0
                self.STATE_RUNNING = 1
                self.STATE_PAUSED = 2
                
                
                self.evManager = evManager
                self.evManager.RegisterListener(self)
                

                self.state = self.STATE_PREPARING
                
                self.height = height
                self.width = width

                self.grid = []
                self.output = []

                self.species = "plant"

        #------------------------------------------------------------------
        def start(self, height, row):
                for row in range(self.height):
                    self.grid.append([])
                    self.output.append([])
                    for column in range(self.width):
                        cell = Cell()
                        self.grid[row].append(cell)
                        #self.output[row].append()
                self.state = self.STATE_RUNNING
                
                ev = GameStartedEvent(self)
                self.evManager.Post(ev)

        #------------------------------------------------------------------
        def getRows(self):
                return self.width

        #------------------------------------------------------------------
        def getCols(self):
                return self.height

        #------------------------------------------------------------------
        def addOrganism(self, row, column):
                global message
                if self.species == "info":
                        self.displayInfo( row, column )
                elif self.viableAdd(row, column) == True:
                    self.grid[row][column].addOrganism(self.species)
                    return 1
                else:
                    print("Invalid organism placement")
                    return 0
                    
        #-------------------------------------------------------------------
        def viableAdd(self, row, column):
                if self.grid[row][column].isFull():
                    return False

                #oRange = organism.range
        
                ##changed the names
                down = self.grid[min(row+1, self.getRows()-1)][column]
                up = self.grid[max(row-1, 0)][column]
                right = self.grid[row][min(column+1, self.getCols()-1)]
                left = self.grid[row][max(column-1, 0)]
                downRight = self.grid[min(row+1, self.getRows()-1)][min(column+1, self.getCols()-1)]
                downLeft = self.grid[min(row+1, self.getRows()-1)][max(column-1, 0)]
                upRight = self.grid[max(row-1, 0)][min(column+1, self.getCols()-1)]
                upLeft = self.grid[max(row-1, 0)][max(column-1, 0)]

                ## Food type required
                #food = self.grid[row][column].organism.type - 1

                #if (right.cellType() != food and left.cellType() != food
                #    and up.cellType() != food and down.cellType() != food
                #    and downRight.cellType() != food and downLeft.cellType() != food
                #    and upRight.cellType() != food and upLeft.cellType() != food):
                #    return False 
                return True
                
        #--------------------------------------------------------------------
        def displayInfo( self, row, column ):
                print("Cell [" + str(row) + "," + str(column) + "]")
                global message
                message[0] = ("Cell [" + str(row) + "," + str(column) + "]")
                self.grid[row][column].displayInfo()

        #--------------------------------------------------------------------
        def selectSpecies(self, species):
                self.species = species

##        #--------------------------------------------------------------------
##        def Output(self):
##                for row in range(GameBoard.getRows()):)
##                        for column in range(GameBoard.getCols()):
##                                self.output[row][column] = self.grid[row][column].cellType()
##                return self.output

        #--------------------------------------------------------------------
        def Notify(self, event):
                if isinstance(event, TickEvent):
                        if self.state == self.STATE_PREPARING:
                                self.start(20, 20)
                                ev = MapBuiltEvent(self)
                                self.evManager.Post(ev)
                                self.state = self.STATE_RUNNING
                if isinstance(event, CharacterPlaceEvent):
                        if event.permission == 0:
                                if self.addOrganism( event.row, event.column ):
                                        print "Getting verification"
                                        ev = CharacterPlaceEvent(event.row, event.column, 1)
                                        self.evManager.Post(ev)
                if isinstance(event, CharacterSelectRequest):
                        self.selectSpecies( event.species )

        
                        
################################################################################################              




# load an image with transparency (key #ff00ff)
# convert to display surface format
def makeImage(filename):
    image = pygame.image.load(filename)
    #image.set_colorkey((255,0,255),RLEACCEL)
    image.convert()
    return image

# load a whole set of ground tiles from a manifest file
def makeGroundTiles(filename):
    f = open(os.path.join('assets',filename + '.tiles'))
    tiles = []
    for line in f.readlines():
        line = line.rstrip()
        if line[0] == '#':
            continue
        tiles.append(makeImage(os.path.join('gfx','tiles',line)))
    f.close()
    return tiles

# load a whole object tile set
def makeObjectTileSet(manifest):
    tiles = []
    # read the tile definition file
    f = open(os.path.join('assets',manifest + '.obj'))
    for line in f.readlines():
        line = line.rstrip()
        if line[0] == '#':
            continue
        tiles.append(makeImage(os.path.join('gfx','objects',line)))
    f.close()
    return tiles

def drawBackground(level, tileset, screen):
    # offset of *top-left corner* of top left tile
    # 400 - 19 (half tile width)
    # 120 - 9 (half height of top face of isometric cube)
    rowstartx = 381
    rowstarty = 111
    for i in level:
        xoff = rowstartx
        yoff = rowstarty
        rowstartx -= 18
        rowstarty += 9
        for j in i:
            screen.blit(tileset[j],(xoff,yoff))
            xoff += 18
            yoff += 9

# render objects & mobs (non-flat tiles; can be any height, but only 1 wide)
# objects must be considered in terms of their *bottom-left corner* because of the varying heights
# the "hotspot" of a mob - the centre of its bottom face - moves in two steps:
#   - from source-tile centre to joining edge of source & dest
#   - from joining edge of source & dest to centre of dest
def drawObjectsAndMobs(level, tileset, mobs, surface, frameno, targets = None):
    ix = 0
    iy = 0
    # offset of *bottom-left* of top left tile
    # 400 - 19 (half of overlay tile width), 
    # 120 + 9 (half bottom of top face of isometric cube)
    xstart = 381
    ystart = 129
    for i in level:
        xoff = xstart - (iy * 18)
        yoff = ystart + (iy * 9)
        for j in i:
            if not j == -1:
                surface.blit(tileset[j],(xoff,yoff-tileset[j].get_height()))
            xoff += 18
            yoff += 9
            for mob in mobs:
                if mob.location[0] == ix and mob.location[1] == iy:
                    mob.draw(surface, frameno, targets)
            ix += 1
        ix = 0
        iy += 1

def exitFunc():
    print "Bye!"


atexit.register(exitFunc)

def makeEmptyArray(v):
    array = []
    for i in range(20):
        array2 = []
        for j in range(20):
            array2.append(v)
        array.append(array2)
        del array2
    return array


class GameBoardView:
    def __init__(self, screen, evManager, tileset, objectTileSet):
        self.STATE_PREPARE = 0
        self.STATE_RUN = 1
        self.state = self.STATE_PREPARE

        self.evManager = evManager
        self.evManager.RegisterListener(self)

        self.screen = screen
        self.level = []
        # background
        self.level.append(makeEmptyArray(0))
        self.level.append(makeEmptyArray(-1))
    
        # filename
        self.filename = ''
        # edit cursor position
        self.x = 0
        self.y = 0
        # tile set index & current tile set (ground, overlay, object)
        self.setIndex = 1
        self.set = 1
        # highlighting graphics
        # selected tile type
        self.tileHighlighter = makeImage(os.path.join('gfx','current_tile.bmp'))
        # selected grid square
        self.gridHighlighter = makeImage(os.path.join('gfx','current_square.bmp'))
        # mode = map editor
        self.mode = 0
        self.tileSet = tileset
        self.objectTileSet = objectTileSet


    def draw(self):
            # draw level as it currently stands

            print "draw######################"
            print self.level
            print self.tileSet
            print self.objectTileSet
            drawBackground(self.level[0], self.tileSet, self.screen)
            drawObjectsAndMobs(self.level[1], self.objectTileSet, [], self.screen, 0)
            # draw current tile set as a row across the top
            if self.set == 0:
                tiles = self.tileSet
            else:
                tiles = self.objectTileSet
            count = 0
            for tile in tiles:
                self.screen.blit(tile,(381 - ((self.setIndex - count) * 38), 0))
                count += 1
            # draw editing highlighters
            self.screen.blit(self.tileHighlighter,(381,0))
            self.screen.blit(self.gridHighlighter,(381 + (self.x*18) - (self.y*18), 111 + (self.x*9) + (self.y*9)))

    def addOrganism(self):
            self.level[self.set][self.y][self.x] = self.setIndex    


    def Notify(self, event):
            if isinstance(event, TickEvent):
                    if self.state == self.STATE_PREPARE:
                        print "vijay"
                        self.draw()
                        pygame.display.flip()
                        self.state = self.STATE_RUN
            if isinstance(event, CharacterPlaceEvent):
                    print "detected event"
                    if event.permission == 0:
                        print "incorrect permission"

                    if event.permission == 1:
                        print "adding sprite"
                        
                        self.addOrganism()
                        self.draw()
                        pygame.display.flip()
    
                            

################################################################################################                                                                                                                  

                

                
##class GameBoard:
##    
##    def __init__(self, height, width):
##
##        self.height = height
##        self.width = width
##        self.grid = []
##        for row in range(height):
##            self.grid.append([])
##            for column in range(width):
##                cell = Cell()
##                self.grid[row].append(cell)
##
##    def getRows(self):
##        return self.width
##
##    def getCols(self):
##        return self.height
##
##    def addOrganism(self, row, column, organism):
##
##        global message
##        if self.viableAdd(row, column, organism) == True:
##            self.grid[row][column].addOrganism(organism)
##            message[1] = ""
##        else:
##            print("Invalid organism placement")
##            message[1] = ("Invalid organism placement")
##
##    def viableAdd(self, row, column, organism):
##
##        if self.grid[row][column].isFull():
##            return False
##        elif organism ==1:
##            return True
##
##        oRange = organism
##        
##        ##changed the names
##        down = self.grid[min(row+1, self.getRows()-1)][column]
##        up = self.grid[max(row-1, 0)][column]
##        right = self.grid[row][min(column+1, self.getCols()-1)]
##        left = self.grid[row][max(column-1, 0)]
##        downRight = self.grid[min(row+1, self.getRows()-1)][min(column+1, self.getCols()-1)]
##        downLeft = self.grid[min(row+1, self.getRows()-1)][max(column-1, 0)]
##        upRight = self.grid[max(row-1, 0)][min(column+1, self.getCols()-1)]
##        upLeft = self.grid[max(row-1, 0)][max(column-1, 0)]
##
##        ## Food type required
##        food = organism - 1
##
##        if (right.cellType() != food and left.cellType() != food
##            and up.cellType() != food and down.cellType() != food
##            and downRight.cellType() != food and downLeft.cellType() != food
##            and upRight.cellType() != food and upLeft.cellType() != food):
##            return False 
##        else:
##            return True
##
##    def displayInfo( self, row, column ):
##        print("Cell [" + str(row) + "," + str(column) + "]")
##        global message
##        message[0] = ("Cell [" + str(row) + "," + str(column) + "]")
##        self.grid[row][column].displayInfo()
##
##    def drawButton(self, screen, color, x, y, width, height, message, fontsize):
##        fontobject = pygame.font.Font(None, fontsize)
##        pygame.draw.rect(screen, color, (x, y, width, height), 4)
##        if len(message) != 0:
##            screen.blit(fontobject.render(message, 4, white, ), ( x + (width/4), y+(height/4)))     

# Global variable class
class currentState:
    def __init__(self, state):
        self.state = state


# Event manager initialization
#event = EventManager()

# New game board
#gameBoard = GameBoard(event, 20,20) 

# Define some colors
#black    = (   0,   0,   0)
#white    = ( 255, 255, 255)
#green    = (   0, 255,   0)
#red      = ( 255,   0,   0)
#blue     = (   0,   0, 255)
 
# This sets the width and height of each grid location
#width=20
#height=20
 
# This sets the margin between each cell
#margin=5

# Create a 2 dimensional array. A two dimesional
# array is simply a list of lists.
 
# Initialize pygame
pygame.init()

  
# Set the height and width of the screen
#screen=pygame.display.set_mode((640,550))
 
# Set title of screen
#pygame.display.set_caption("Chain of Life")
 
#Loop until the user clicks the close button.
#done=False
 
# Used to manage how fast the screen updates
clock=pygame.time.Clock()
                 
organismType = currentState("a")

# Global variables to be used in the statistics display of the game surface
plantNumber = currentState(0)
animalNumber = currentState(0)

# Message to be displayed
message = []
message.append("Welcome to Chain of Life")
message.append("")
message.append("")




def main():
    """..."""
    evManager = EventManager()
    #gameBoard = GameBoard(event, 20,20) 
    pygame.display.init()
    screen = pygame.display.set_mode((800, 600), HWSURFACE)
    
    pygame.font.init()
    font = pygame.font.Font(os.path.join('gfx','VeraSe.ttf'),28)
    # load ground tiles

    # load objects

    # hide the pointer
    pygame.mouse.set_visible(True)


    tileset = makeGroundTiles('ground')
    objectTileset = makeObjectTileSet('objects')


    keybd = KeyboardController(evManager)
    spinner = CPUSpinnerController(evManager)
    board = GameBoard(evManager, 200, 200)
    view = GameBoardView(screen, evManager, tileset, objectTileset )
    #print "drawing ###########################"
    #view.draw()
    #pygame.display.flip()
    spinner.Run()

if __name__ == '__main__':
    main()



if False:
    
    def ControllerTick():
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            if event.type == pygame.MOUSEBUTTONDOWN:
                # User clicks the mouse. Get the position
                pos = pygame.mouse.get_pos()
                if pos[1] >= 500:
                    continue
                # Change the x/y screen coordinates to grid coordinates
                if pos[0] >= 500:
                    if pos[0] >=520 and pos[0]<=620 and pos[1] >=20 and pos[1] <=120:
                        organismType.state = "a"
                    if pos[0] >=520 and pos[0]<=620 and pos[1] >=150 and pos[1] <=250:
                        organismType.state = "s"
                    if pos[0] >=520 and pos[0]<=620 and pos[1] >=280 and pos[1] <=320:
                        organismType.state = "c"
                    continue
                column=pos[0] // (width+margin)
                row=pos[1] // (height+margin)
                # Set that location to zero
                if organismType.state == "a":
                    gameBoard.addOrganism(row, column, 1)
                if organismType.state == "s":
                    gameBoard.addOrganism(row, column, 2)
                gameBoard.displayInfo(row, column)

            if event.type == pygame.KEYDOWN and event.key == pygame.K_a:
                organismType.state = "a"
            if event.type == pygame.KEYDOWN and event.key == pygame.K_s:
                organismType.state = "s"
            if event.type == pygame.KEYDOWN and event.key == pygame.K_c:
                organismType.state = "c"
        
            


    def ViewTick():
        plantNumber.state = 0
        animalNumber.state = 0
    
        gameBoard.drawButton(screen, green, 520, 20, 100, 100, "A", 100)
        if organismType.state == "a": ##highlights whats selected
                gameBoard.drawButton(screen, white, 516, 16, 108, 108, "", 0)
        gameBoard.drawButton(screen, red, 520, 150, 100, 100, "S", 100)
        if organismType.state == "s": ##highlights whats selected
                gameBoard.drawButton(screen, white, 516, 146, 108, 108, "", 0)
        gameBoard.drawButton(screen, white, 520, 280, 100, 40, "  C", 40)
        if organismType.state == "c": ##highlights whats selected
                gameBoard.drawButton(screen, white, 516, 276, 108, 48, "", 0)
    
        for row in range(gameBoard.getRows()):
            for column in range(gameBoard.getCols()):
                color = white
                if gameBoard.grid[row][column].isFull():
                    if gameBoard.grid[row][column].cellType() == 1:
                        color = green
                        plantNumber.state += 1
                    if gameBoard.grid[row][column].cellType() == 2:
                        color = red
                        animalNumber.state += 1
                pygame.draw.rect(screen, color, [(margin+width)*column+margin, (margin+height)*row+margin,width,height])
        gameBoard.drawButton(screen, blue, 520, 350, 100, 40, "Plants: " + str(plantNumber.state), 15)
        gameBoard.drawButton(screen, blue, 520, 420, 100, 40, "Animals: " + str(animalNumber.state), 15)
        gameBoard.drawButton(screen, white, 5, 510, 500, 30, (message[0] + "   " +
                                                              message[1] + "   " +
                                                              message[2]), 20)
            
 
# -------- Main Program Loop -----------
#while done==False:

    #ControllerTick()
 
    # Set the screen background
    #screen.fill(black)
 
    # Draw the grid
    #ViewTick()
     
    # Limit to 20 frames per second
    #clock.tick(20)
 
    # Go ahead and update the screen with what we've drawn.
    #pygame.display.flip()
 
# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
#pygame.quit ()
