import pygame, sys
from pygame.locals import *
from firebase import firebase
import math
import random
import time

# Global variables
screenTW = 550
screenTH = 550
squareSize = screenTW/11
mapW = 110
mapH = 110
world = []
aliens = []
objects = []

playerImage = pygame.image.load("img/player.png")
sellerImage = pygame.image.load("img/seller.png")

floorImage = pygame.image.load("img/floor.png")
alienImage = pygame.image.load("img/alien.png")
grassImage = pygame.image.load("img/grass.png")
waterImage = pygame.image.load("img/water.png")
wallImage = pygame.image.load("img/wall.png")

waterBottleImage = pygame.image.load("img/waterBottle.png")
pipeImage = pygame.image.load("img/pipe.png")
aquariumImage = pygame.image.load("img/aquarium.png")
lettuceSeedImage = pygame.image.load("img/lettuceSeed.png")
pumpImage = pygame.image.load("img/pump.png")

gameOverImage = pygame.image.load("img/gameOver.png")

objects1 = [["Water Bottle", waterBottleImage], ["Pipe", pumpImage], ["Aquarium", aquariumImage], ["Lettuce Seed", lettuceSeedImage], ["Pump", pumpImage]]
chunkSize = 11
chunkAmountX = int(mapW/chunkSize)
chunkAmountY = int(mapH/chunkSize)
waterProperties = []
baseSize = chunkSize
potableWaterChunkX = 0
potableWaterChunkY = 0
shopSize = chunkSize
shopX = 0
shopY = 0
while (potableWaterChunkX == 0 and potableWaterChunkY == 0) or (potableWaterChunkX == shopX and potableWaterChunkY == shopY):
    potableWaterChunkX = random.randint(0, chunkAmountX-1)
    potableWaterChunkY = random.randint(0, chunkAmountY-1)
while (shopX == 0 and shopY == 0) or (shopX == potableWaterChunkX and shopY == potableWaterChunkY):
    shopX = random.randint(0, chunkAmountX-1)
    shopY = random.randint(0, chunkAmountY-1)
shopX = 1
shopY = 1

# Pygame setup
pygame.init()
screen=pygame.display.set_mode((screenTW,screenTH),0,32)
pygame.font.init()
font = pygame.font.SysFont("Arial", 40)

# Database setup
HydralienDatabase = firebase.FirebaseApplication('https://hydralien-database.firebaseio.com/', None)

# Retrieve from database
globalWeapons = HydralienDatabase.get('/Weapons', None)
globalBlueprints = HydralienDatabase.get('/Blueprints', None)
globalScience = HydralienDatabase.get('/Science', None)

def positive(number):
    return int(math.sqrt(number**2))

def blit_text(surface, text, pos, font, color=pygame.Color('black')):
    words = [word.split(' ') for word in text.splitlines()]  # 2D array where each row is a list of words.
    space = font.size(' ')[0]  # The width of a space.
    max_width, max_height = surface.get_size()
    x, y = pos
    for line in words:
        for word in line:
            word_surface = font.render(word, 0, color)
            word_width, word_height = word_surface.get_size()
            if x + word_width >= max_width:
                x = pos[0]  # Reset the x.
                y += word_height  # Start on new row.
            surface.blit(word_surface, (x, y))
            x += word_width + space
        x = pos[0]  # Reset the x.
        y += word_height  # Start on new row.

def get_key():
  while 1:
    event = pygame.event.poll()
    if event.type == KEYDOWN:
        return event.key
    else:
        pass

def display_box(message):
  pygame.draw.rect(screen, (0,0,0), (screenTW/2-200, screenTH/2-20, 400, 37), 0)
  pygame.draw.rect(screen, (255,255,255), (screenTW/2-202, screenTH/2-20, 404, 37), 1)
  if len(message) != 0:
      screen.blit(font.render(message, 1, (255,255,255)), (screenTW/2-200, screenTH/2-15))
  pygame.display.flip()

def input_(question):
  current_string = []
  while 1:
    display_box(question + ": " + ''.join(current_string).title())
    inkey = get_key()
    if inkey == K_BACKSPACE:
        current_string = current_string[0:-1]
    elif inkey == K_RETURN:
        break
    elif (inkey >= 97 and inkey <= 122 and len(current_string) < 17) or inkey == K_SPACE:
        current_string.append(chr(inkey))
  return ''.join(current_string).title()

def numberInput(question):
  current_string = []
  while 1:
    display_box(question + ": " + ''.join(current_string).title())
    inkey = get_key()
    if inkey == K_BACKSPACE:
        current_string = current_string[0:-1]
    elif inkey == K_RETURN:
        break
    elif (inkey >= 48 and inkey <= 57 and len(current_string) < 5) or inkey == K_SPACE:
        current_string.append(chr(inkey))
  return int(''.join(current_string).title())

def addDatabase(location, thing):
    content = HydralienDatabase.get(location, None)
    if content != None and thing in content:
        amount = content[thing] + 1
        HydralienDatabase.put(location, thing, amount)
    else:
        HydralienDatabase.put(location, thing, 1)

def removeDatabase(location, thing):
    content = HydralienDatabase.get(location, None)
    amount = content[thing] - 1
    if amount > 0:
        HydralienDatabase.put(location, thing, amount)
    else:
        HydralienDatabase.delete(location, thing)

class Player:
    def __init__(self, name, x, y):
        self.x = x
        self.y = y
        self.name = name
        self.health = 100
        self.tool = "Water Testing Kit"
        self.toolAmount = 1
        player = HydralienDatabase.get('/Players/%s' % self.name, None)
        if "Water" in player:
            self.waterQuantity = player["Water"]
        else:
            self.waterQuantity = 25
        self.potableWater = True
        self.object = "No Object"
        self.oldMoveTime = time.time()
        self.oldClickedTime = time.time()
        self.oldRegenerateTime = time.time()
        self.oldShootTime = time.time()
        self.image = pygame.rect.Rect((x*squareSize, y*squareSize, squareSize, squareSize))
    def draw(self):
        for y in range(self.y*2+1):
            for x in range(self.x*2+1):
                screen.blit(world[y][x].image, (x*squareSize, y*squareSize))
                if objects[y][x] != "No Object":
                    screen.blit(objects[y][x].image, (x*squareSize, y*squareSize))
        for alien in aliens:
            screen.blit(alienImage, (alien.x*squareSize, alien.y*squareSize))
        screen.blit(playerImage, (self.x*squareSize, self.y*squareSize))
    def closeToBuilding(self):
        for y in range(11):
            for x in range(11):
                if world[y][x].location == "Base" or world[y][x].location == "Shop":
                    return True
    def damage(self, amount):
        self.health -= amount
    def regenerate(self, amount):
        if self.health < 100:
            self.health += amount
    def waterIsPotable(self, square):
        if square.name == "Water":
            pHGood = square.pH >= 7 and square.pH <= 7.5
            nitrateGood = square.nitrate <= 20
            nitriteGood = square.nitrite <= 0.01
            ammoniaGood = square.ammonia <= 0.5
            return pHGood and nitrateGood and nitriteGood and ammoniaGood
    def craftObject(self, objectInput):
        blueprints = HydralienDatabase.get('/Players/%s/Blueprints' % self.name, None)
        inventory = HydralienDatabase.get('/Players/%s/Inventory' % self.name, None)
        if objectInput in blueprints:
            if inventory != None:
                for _object in globalBlueprints[objectInput]["Objects"]:
                    if not (_object in inventory and inventory[_object] >= globalBlueprints[objectInput]["Objects"][_object]):
                        print("You don't have all the items!")
                        return
                addDatabase('/Players/%s/Inventory' % self.name, objectInput)
                for _object in globalBlueprints[objectInput]["Objects"]:
                    for n in range(globalBlueprints[objectInput]["Objects"][_object]):  
                        removeDatabase('/Players/%s/Inventory' % self.name, _object)
                return True
            else:
                print("You don't have any items!")
        else:
            print("You don't have the blueprint!")
    def retrieve(self):
        currentSquare = world[self.y][self.x]
        currentObject = objects[self.y][self.x]
        if currentObject != "No Object":
            if currentObject.name in globalBlueprints:
                player = HydralienDatabase.get('/Players/%s' % self.name, None)
                if globalBlueprints[currentObject.name]["Type"] == "Food Production":
                    if str(currentSquare.id) in player["Structures"]:
                        for object_ in globalBlueprints[currentObject.name]["Minimum"]:
                            if player["Structures"][str(currentSquare.id)][object_] < globalBlueprints[currentObject.name]["Minimum"][object_]:
                                return
                        for seedTimeId in player["Structures"][str(currentSquare.id)]["Seed"]:
                            seed = player["Structures"][str(currentSquare.id)]["Seed"][seedTimeId]
                            if currentObject.name == "Aquaponic":
                                if time.time()-int(seedTimeId) > globalScience[seed]["Growth"]/player["Structures"][str(currentSquare.id)]["Fish"]:
                                    addDatabase('/Players/%s/Inventory' % self.name, globalScience[seed]["Becomes"])
                                    HydralienDatabase.delete('/Players/%s/Structures/%d/Seed' % (self.name, currentSquare.id), seedTimeId)
                            else:
                                if time.time()-int(seedTimeId) > globalScience[seed]["Growth"]:
                                    addDatabase('/Players/%s/Inventory' % self.name, globalScience[seed]["Becomes"])
                                    HydralienDatabase.delete('/Players/%s/Structures/%d/Seed' % (self.name, currentSquare.id), seedTimeId)
    def getBlueprint(self, objectInput):
        blueprints = HydralienDatabase.get('/Players/%s/Blueprints' % self.name, None)
        if objectInput in globalBlueprints:
            if blueprints == None or objectInput not in blueprints:
                if self.waterQuantity >= globalBlueprints[objectInput]["Price"]:
                    self.waterQuantity -= globalBlueprints[objectInput]["Price"]
                    HydralienDatabase.put('/Players/%s/Blueprints' % self.name, objectInput, 1)
                else:
                    print("You don't have the %s oz of potable water required for this blueprint." % globalBlueprints[objectInput]["Price"])
            else:
                print("You allready have this blueprint!")
        else:
            print("This blueprint doesn't exist!")
    def handleKeys(self):
        global playerToolInfoText
        key = pygame.key.get_pressed()
        dist = 1
            
        if key[pygame.K_e]:
            objectInput = input_("Tool")
            inventory = HydralienDatabase.get('/Players/%s/Inventory' % self.name, None)
            if objectInput in inventory:
                self.tool = objectInput
                self.toolAmount = inventory[objectInput]
                playerToolInfoText = ""
                if self.tool in globalWeapons:
                    self.weaponInfo = globalWeapons[self.tool]["Level %s" % inventory[self.tool]]
                    print(self.weaponInfo)
            else:
                print("You don't have this tool!")

        if key[pygame.K_c]:
            objectInput = input_("Object")
            self.craftObject(objectInput)

        if key[pygame.K_p]:
            currentObject = objects[self.y][self.x]
            if currentObject != "No Object":
                addDatabase('/Players/%s/Inventory' % self.name, currentObject.name)
                if self.tool == currentObject.name:
                    self.toolAmount += 1
                objects[self.x][self.y] = "No Object"

        if key[pygame.K_r]:
            self.retrieve()
        
        if time.time()-self.oldClickedTime > 0.2:
            
            if pygame.mouse.get_pressed()[0]:
                x = int(pygame.mouse.get_pos()[0]//squareSize)
                y = int(pygame.mouse.get_pos()[1]//squareSize)
                currentSquare = world[self.y][self.x]
                clickedSquare = world[y][x]
                currentObject = objects[self.y][self.x]
                clickedObject = objects[y][x]

                print("%d, %d : %d" % (x, y, world[y][x].id))
                
                if currentSquare.location == "Shop":
                    if clickedSquare.name == "Architect":
                        objectInput = input_("Blueprint")
                        self.getBlueprint(objectInput)
                    elif clickedSquare.name == "Auction Manager":
                        pass
                    elif clickedSquare.name == "Scientist":
                        scienceInput = input_("Science")
                        inventory = HydralienDatabase.get('/Players/%s/Inventory' % self.name, None)
                        if scienceInput in globalScience:
                            if self.potableWater and self.waterQuantity >= globalScience[scienceInput]["Price"]:
                                self.waterQuantity -= globalScience[scienceInput]["Price"]
                                addDatabase('/Players/%s/Inventory' % self.name, scienceInput)
                            else:
                                print("You don't have the %s oz of potable water required to buy this scientific object." % globalScience[scienceInput]["Price"])
                    elif clickedSquare.name == "Weapon Guardian":
                        weaponInput = input_("Weapon")
                        inventory = HydralienDatabase.get('/Players/%s/Inventory' % self.name, None)
                        if weaponInput in globalWeapons:
                            if weaponInput in inventory:
                                amount = inventory[weaponInput]+1
                                newWeaponInfo = globalWeapons[weaponInput]["Level %s" % amount]
                                if self.potableWater and self.waterQuantity >= newWeaponInfo["Price"]:
                                    self.waterQuantity -= newWeaponInfo["Price"]
                                    HydralienDatabase.put('/Players/%s/Inventory' % self.name, weaponInput, amount)
                                    self.weaponInfo = newWeaponInfo
                                else:
                                    print("You don't have the %s oz of potable water required to upgrade this weapon." % newWeaponInfo["Price"])
                            else:
                                newWeaponInfo = globalWeapons[weaponInput]["Level 1"]
                                if self.potableWater and self.waterQuantity >= newWeaponInfo["Price"]:
                                    self.waterQuantity -= newWeaponInfo["Price"]
                                    HydralienDatabase.put('/Players/%s/Inventory' % self.name, weaponInput, amount)
                                    self.weaponInfo = newWeaponInfo
                                else:
                                    print("You don't have the %s oz of potable water required to upgrade this weapon." % newWeaponInfo["Price"])

                elif self.tool in globalWeapons:
                    if not self.closeToBuilding():
                        if self.waterQuantity >= 0.25 and time.time()-self.oldShootTime > self.weaponInfo["Reload Time"]:
                            if self.potableWater:
                                for alien in aliens:
                                    if x == alien.x and y == alien.y and round(math.sqrt(abs(self.x-alien.x)**2+abs(self.y-alien.y)**2)) <= self.weaponInfo["Range"]:
                                        alien.damage(self.weaponInfo["Damage"])
                                        print("Shot!")
                            self.waterQuantity -= 0.25
                            self.oldShootTime = time.time()

                elif self.tool in globalBlueprints:
                    if clickedSquare.location == "Base" and clickedSquare.name != "Wall":
                        if self.toolAmount > 0:
                            if clickedObject == "No Object":
                                self.toolAmount -= 1
                                toolImage = pygame.image.load(globalBlueprints[self.tool]["Image"])
                                objects[y][x] = Object(self.tool, [toolImage])
                                HydralienDatabase.put('/Players/%s/Structures/%d' % (self.name, clickedSquare.id), "Type", self.tool)
                                for object_ in globalBlueprints[self.tool]["Minimum"]:
                                    HydralienDatabase.put('/Players/%s/Structures/%d' % (self.name, clickedSquare.id), object_, 0)
                                removeDatabase('/Players/%s/Inventory' % self.name, self.tool)
                    else:
                        print("This tool can only be placed in your base.")

                elif self.tool in globalScience:
                    if clickedObject != "No Object":
                        if clickedObject.name in globalBlueprints:
                            if globalBlueprints[clickedObject.name]["Type"] == "Food Production":
                                if globalScience[self.tool]["Type"] != "Seed":
                                    player = HydralienDatabase.get('/Players/%s' % self.name, None)
                                    if globalScience[self.tool]["Type"] in player["Structures"][str(clickedSquare.id)]:
                                        type_ = globalScience[self.tool]["Type"]
                                        newAmount = player["Structures"][str(clickedSquare.id)][type_]+1
                                        if newAmount <= globalBlueprints[clickedObject.name]["Maximum"][type_]:
                                            if globalScience[self.tool]["Type"] == "Fish":
                                                if player["Structures"][str(clickedSquare.id)]["Water"] >= newAmount*600:
                                                    addDatabase('/Players/%s/Structures/%d' % (self.name, clickedSquare.id), "Fish")
                                                    removeDatabase('/Players/%s/Inventory' % self.name, self.tool)
                                            else:
                                                addDatabase('/Players/%s/Structures/%d' % (self.name, clickedSquare.id), type_)
                                                removeDatabase('/Players/%s/Inventory' % self.name, self.tool)
                                elif globalScience[self.tool]["Type"] == "Seed":
                                    player = HydralienDatabase.get('/Players/%s' % self.name, None)
                                    if "Seed" in player["Structures"][str(clickedSquare.id)]:
                                        newAmount = len(player["Structures"][str(clickedSquare.id)]["Seed"])+1
                                        if newAmount <= globalBlueprints[clickedObject.name]["Maximum"]["Seed"]:
                                            HydralienDatabase.put('/Players/%s/Structures/%d/Seed' % (self.name, clickedSquare.id), "%d" % time.time(), self.tool)
                                            removeDatabase('/Players/%s/Inventory' % self.name, self.tool)
                                    else:
                                        HydralienDatabase.put('/Players/%s/Structures/%d/Seed' % (self.name, clickedSquare.id), "%d" % time.time(), self.tool)
                                        removeDatabase('/Players/%s/Inventory' % self.name, self.tool)


                elif self.tool == "Water Bottle":
                    if x == self.x and y == self.y and currentSquare.name == "Water":
                        if self.toolAmount * 25 != self.waterQuantity:
                            objects[self.y][self.x] = Square("Grass", [grassImage, "Wilderness"])
                            self.waterQuantity += 25
                            if self.toolAmount * 25 < self.waterQuantity:
                                self.waterQuantity = self.toolAmount * 25
                            if self.waterIsPotable(currentSquare):
                                self.potableWater = True
                            else:
                                self.potableWater = False
                            print(self.potableWater)
                    else:
                        if clickedObject != "No Object":
                            if clickedObject.name in globalBlueprints:
                                if globalBlueprints[clickedObject.name]["Type"] == "Food Production":
                                    player = HydralienDatabase.get('/Players/%s' % self.name, None)
                                    if "Water" in player["Structures"][str(clickedSquare.id)]:
                                        amount = numberInput("Amount")
                                        oldAmount = player["Structures"][str(clickedSquare.id)]["Water"]
                                        minAmount = globalBlueprints[clickedObject.name]["Minimum"]["Water"]
                                        maxAmount = globalBlueprints[clickedObject.name]["Maximum"]["Water"]
                                        if amount+oldAmount >= minAmount and amount+oldAmount <= maxAmount:
                                            if self.waterQuantity >= amount:
                                                HydralienDatabase.put('/Players/%s/Structures/%d' % (self.name, clickedSquare.id), "Water", amount+oldAmount)
                                                self.waterQuantity -= amount
                
                elif self.tool == "Water Testing Kit":
                    playerToolInfoText = ""
                    if currentSquare.name == "Water":
                        playerToolInfoText = "Ph: %s\nNitrate: %s mg/L\nNitrite: %s mg/L\nAmonia: %s mg/L" % tuple(currentSquare.waterProperties)
                self.oldClickedTime = time.time()

                
        if time.time()-self.oldMoveTime > 0.2:
            
            if key[pygame.K_w]:
                world.insert(0, world.pop())
                objects.insert(0, objects.pop())
                for alien in aliens:
                    alien.y += 1
                self.oldMoveTime = time.time()
            if key[pygame.K_a]:
                for y in range(len(world)):
                    world[y].insert(0, world[y].pop())
                    objects[y].insert(0, objects[y].pop())
                for alien in aliens:
                    alien.x += 1
                self.oldMoveTime = time.time()
            if key[pygame.K_s]:
                world.insert(len(world), world.pop(0))
                objects.insert(len(objects), objects.pop(0))
                for alien in aliens:
                    alien.y -= 1
                self.oldMoveTime = time.time()
            if key[pygame.K_d]:
                for y in range(len(world)):
                    world[y].insert(len(world), world[y].pop(0))
                    objects[y].insert(len(objects), objects[y].pop(0))
                for alien in aliens:
                    alien.x -= 1
                self.oldMoveTime = time.time()
            
            currentObject = objects[self.x][self.y]
            if currentObject != "No Object":
                self.object = currentObject.name
            else:
                self.object = "No Object"

class Alien:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.health = 100
        self.oldMoveTime = time.time()
        self.oldDamageTime = time.time()
    def inBuilding(self):
        self.x %= mapW
        self.y %= mapH
        if world[self.y][self.x].location == "Base" or world[self.y][self.x].location == "Shop":
            return True
    def randomMove(self):
        moveX = random.choice([True, False])
        x = random.randint(-1, 1)
        y = random.randint(-1, 1)
        if moveX:
            self.x = (self.x+x) % mapW
            if self.inBuilding():
                self.x = (self.x-x) % mapW
        else:
            self.y = (self.y+y) % mapH
            if self.inBuilding():
                self.y = (self.y-y) % mapH
    def moveToPlayer(self):
        x = 0
        y = 0
        if positive(self.x-player.x)>=mapW-positive(self.x-player.x):
            if self.x>player.x:
                x = 1
            elif self.x<player.x:
                x  = -1
        elif positive(self.x-player.x)<mapW-positive(self.x-player.x):
            if self.x>player.x:
                x = -1
            elif self.x<player.x:
                x  = 1
        if positive(self.y-player.y)>=mapH-positive(self.y-player.y):
            if self.y>player.y:
                y = 1
            elif self.y<player.y:
                y = -1
        elif positive(self.y-player.y)<mapH-positive(self.y-player.y):
            if self.y>player.y:
                y = -1
            elif self.y<player.y:
                y  = 1
        moveX = random.choice([True, False])
        if moveX or y == 0:
            self.x = (self.x+x) % mapW
            if self.inBuilding():
                self.x = (self.x-x) % mapW
        if not moveX or x == 0:
            self.y = (self.y+y) % mapH
            if self.inBuilding():
                self.y = (self.y-y) % mapH
    def damage(self, amount):
        self.health -= amount
        if self.health <= 0:
            aliens.remove(self)
    def handleMoves(self):
        if time.time()-self.oldMoveTime > 0.5:
            if self.x < 11 and self.y < 11:
                self.moveToPlayer()
                pass
            else:
                self.randomMove()
                pass
            self.oldMoveTime = time.time()

class Square:
    def __init__(self, material, properties):
        self.name = material
        self.image = properties[0]
        self.location = properties[1]
        if self.name == "Water":
            self.waterProperties = properties[2]
            self.pH = self.waterProperties[0]
            self.nitrate = self.waterProperties[1]
            self.nitrite = self.waterProperties[2]
            self.ammonia = self.waterProperties[3]
    def __repr__(self):
        return str(self.x)
        return self.name[0]

class Object:
    def __init__(self, name, properties):
        self.name = name
        self.image = properties[0]
    def __repr__(self):
        return self.name

#print(potableWaterChunkX)
#print(potableWaterChunkY)

# Generate water properties by chunk
for y in range(chunkAmountY):
    waterProperties.append([])
    for x in range(chunkAmountX):
        if x == potableWaterChunkX and y == potableWaterChunkY:
            pH = round(random.uniform(7, 7.5), 2)
            nitrate = random.randint(1, 20)
            nitrite = round(random.uniform(0.001, 0.01), 4)
            ammonia = round(random.uniform(0.01, 0.5), 2)
            waterProperties[y].append([pH, nitrate, nitrite, ammonia])
        else:
            pH = round(random.uniform(4, 14), 2)
            nitrate = random.randint(1, 50)
            nitrite = round(random.uniform(0.001, 0.3), 4)
            ammonia = round(random.uniform(0.01, 3), 2)
            waterProperties[y].append([pH, nitrate, nitrite, ammonia])

id_ = 0

# Generate world
for y in range(mapH):
    world.append([])
    objects.append([])
    for x in range(mapW):
        water = random.randint(1, 50)
        alien = random.randint(1, 200)
        object_ = random.randint(1, 500)
        objects[y].append("No Object")
        
        if x < baseSize and y < baseSize:
            if x == 0 or y == 0 or x == baseSize-1 or y == baseSize-1:
                world[y].append(Square("Wall", [wallImage, "Base"]))
            else:
                world[y].append(Square("Floor", [floorImage, "Base"]))
                
        elif x == potableWaterChunkX*chunkSize+chunkSize//2 and y == potableWaterChunkY*chunkSize+chunkSize//2:
            world[y].append(Square("Water", [waterImage, "Wilderness", waterProperties[y//chunkSize][x//chunkSize]]))
            
        elif x >= shopX*chunkSize and y >= shopY*chunkSize and x < shopX*chunkSize+shopSize and y < shopY*chunkSize+shopSize:
            if x == shopY*chunkSize or y ==  shopX*chunkSize or x == shopX*chunkSize+shopSize-1 or y == shopY*chunkSize+shopSize-1:
                world[y].append(Square("Wall", [wallImage, "Shop"]))
            else:
                if x == shopX*chunkSize+1 and y == shopY*chunkSize+1:
                    world[y].append(Square("Architect", [sellerImage, "Shop"]))
                elif x == shopX*chunkSize+chunkSize-2 and y == shopY*chunkSize+1:
                    world[y].append(Square("Craftman", [sellerImage, "Shop"]))
                elif x == shopX*chunkSize+1 and y == shopY*chunkSize+chunkSize-2:
                    world[y].append(Square("Scientist", [sellerImage, "Shop"]))
                elif x == shopX*chunkSize+chunkSize-2 and y == shopY*chunkSize+chunkSize-2:
                    world[y].append(Square("Weapon Guardian", [sellerImage, "Shop"]))
                else:
                    world[y].append(Square("Floor", [floorImage, "Shop"]))
                
        elif water == 1:
            world[y].append(Square("Water", [waterImage, "Wilderness", waterProperties[y//chunkSize][x//chunkSize]]))
            
        else:
            world[y].append(Square("Grass", [grassImage, "Wilderness"]))
            if object_ == 1:
                object_ = random.choice(objects1)
                objects[y][x] = Object(object_[0], [object_[1]])
            elif object_ == 2:
                objects[y][x] = Object("Pipe", [pipeImage])

        world[y][x].id = id_
        id_ += 1
                
        if alien == 1 and not (x < baseSize and y < baseSize) and not (x > shopX*chunkSize and y > shopY*chunkSize and x < shopX*chunkSize+shopSize and y < shopY*chunkSize+shopSize):
            aliens.append(Alien(x, y))

players = HydralienDatabase.get('/Players', None)
for player in players:
    if "Structures" in players[player]:
        for structure in players[player]["Structures"]:
            object_ = players[player]["Structures"][structure]["Type"]
            image = pygame.image.load(globalBlueprints[object_]["Image"])
            objects[int(structure)//mapH][int(structure)%mapW] = Object(object_, [image])

# Spawn player
player = Player("Scott", 5, 5)

playerToolInfoText = ""
playerHealthText = font.render("Health: 100%", False, (0, 0, 0))
playerToolText = font.render("Tool: ", False, (0, 0, 0))
playerObjectText = font.render("Object: ", False, (0, 0, 0))
playerWaterQuantityText = font.render("25 oz", False, (0, 0, 0))

stop = False

while True:
    for event in pygame.event.get():
        if event.type==QUIT:
            stop = True
    if player.health == 0:
        time.sleep(1)
        stop = True
    if stop == True:
        break
    screen.fill((153, 204, 255))
    player.draw()
    player.handleKeys()
    if time.time()-player.oldRegenerateTime > 0.5:
        player.regenerate(1)
        player.oldRegenerateTime = time.time()
    for alien in aliens:
        alien.handleMoves()
        if alien.x == player.x and alien.y == player.y:
            if time.time()-alien.oldDamageTime > 0.5:
                player.damage(random.randint(20, 40))
                if player.health < 0:
                    player.health = 0
                    screen.blit(gameOverImage, (0, 0))
                alien.oldDamageTime = time.time()
    playerObjectText = font.render("Object: %s" % player.object, False, (0, 0, 0))
    playerHealthText = font.render("Health: %d%%" % player.health, False, (0, 0, 0))
    playerToolText = font.render("Tool: %s" % player.tool, False, (0, 0, 0))
    playerWaterQuantityText = font.render("%s oz" % player.waterQuantity, False, (0, 0, 0))
    blit_text(screen, playerToolInfoText, (15, 15), font)
    screen.blit(playerHealthText, (365, 15))
    screen.blit(playerObjectText, (15, 485))
    screen.blit(playerToolText, (15, 515))


    screen.blit(playerWaterQuantityText, (230, 15))
    pygame.display.update()

HydralienDatabase.put('/Players/%s' % player.name, "Water", player.waterQuantity)

pygame.quit()
sys.exit()
