# Concave
# Copyright (C) 2012 Daniel Malmqvist
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import pygame
from npc import NPC
pygame.init()

import sys
import datetime
import constants
import math
from player import Player
import gamemap
import g
from pygame.locals import *
import gc
import helperfunctions
import weapon
from minimap import Minimap
from spellbook import Spellbook

def concave(charName = "Daniel"):
    g.reset()
    
    
    screen = pygame.display.set_mode((640, 480))
    
    hudetc = pygame.image.load("graphic/hudetc.png")
    invent = pygame.image.load("graphic/inventory.png")
    menu = pygame.image.load("graphic/menu.png")
    minimapBG = pygame.image.load("graphic/minimap.png")
    magicBar = pygame.image.load("graphic/magicbar.png")
    
    g.getMagicImages()
    
    #now = datetime.datetime.now()
    #pygame.display.set_caption(str(now))
    pygame.display.set_caption("Concave")
    
    
    
    if g.getCurrentLevel() == 0:
        mapGrid = g.getMap()
        gameMap = gamemap.Map()
        #gameMap.loadMap(mapGrid)
        gameMap.loadMapTiled(0)
        mapGrid = gameMap.map
    else:
        mapGrid = g.getMap()
        gameMap = gamemap.Map()
        gameMap.loadMap(mapGrid)
        mapGrid = gameMap.map
        
    g.setInventory()
    inventory = g.getInventroy()
    
    player = Player(gameMap.startX*32+16, gameMap.startY*32+16, mapGrid, charName)
    
    g.setPlayer(player)
    
    weapons = weapon.Weapon()
    
    enemies = g.getEnemies()
    
    for e in enemies:
        e.loadImages()
    
    
    clock = pygame.time.Clock()
    
    usePressed = False
    showInventory = False
    showMenu = False
    
    items = g.getItems()
    
    
    itemImages = g.getItemImages()
    
    player.updateFromInventory()
    
    
    miniMap = Minimap()
    miniMap.generateMinimap(mapGrid)
    
    
    spellBook = Spellbook(player.level, player.mp)
    
    npcs = []
    npcs.append(NPC(1))
    npcs.append(NPC(2))
    
    
    
    frameCount = 0
    time = datetime.datetime.now()
    
    talkingToNPC = None
    
    levelImage = helperfunctions.renderTextBlock("Lvl: " + str(g.getCurrentLevel()), g.fontNormal, 1, (255,255,255))
    
    if g.getCurrentLevel() == 0:
        g.getSoundSystem().playMusic(0)
    elif g.getCurrentLevel() % 5 == 0:
        g.getSoundSystem().playMusic(2)
    else:
        g.getSoundSystem().playMusic(1)
    
    
    helpA = "Move your char by using w, a, s & d.\n"
    helpA += "To pick up items/talk to npcs press e.\n"
    helpA += "Open inventory by pressing i or c."
    helpA += "To attack press left mousebutton,\n"
    helpA += "the direction of attack depends on where you click in the world.\n"
    helpA += "To use magic press a number (currently only 1-4).\n"
    helpA += "This message will dissapear after your first exp point"
    
    helpText = helperfunctions.renderTextBlock(helpA, g.fontNormal, 1, (255,255,255))
    helpText = helperfunctions.addBorder(helpText)
    helpTextPos = (0, 480 - helpText.get_height() - 32)
    
    
    
    returnButton = helperfunctions.renderTextBlock("Return to menu", g.fontBig, 1, (255,255,255))
    exitButton = helperfunctions.renderTextBlock("Exit Game", g.fontBig, 1, (255,255,255))
    returnButton = helperfunctions.addBorderCentered(returnButton, 15)
    exitButton = helperfunctions.addBorderCentered(exitButton, 15)
    
    returnButtonPos = (320 - returnButton.get_width()/2, 192)
    exitButtonPos = (returnButtonPos[0], returnButtonPos[1] + 64)        
    
    diedText = helperfunctions.renderTextBlock("You got killed, \nbut now you are back in town.", g.fontBig, 1, (255,255,255))
    diedText = helperfunctions.addBorderCentered(diedText)
    diedTextPos = (320 - diedText.get_width()/2, 240 - diedText.get_height()/2)
    
    dieTextId = 0
    keepPlaying = True
    notEnoghMP = False
    while keepPlaying:
        if player.hp <= 0:
            player.hp = 1
            g.setCurrentLevel(0)
            dieTextId = 240
            
        frameCount += 1
        if (datetime.datetime.now() - time).seconds >= 5:
            print "FPS:", str(frameCount/5)
            frameCount = 0
            time = datetime.datetime.now()
            
            
            
        """
        When player walks up or down a staircase
        """
        if g.getCurrentLevel() != player.mapLevel:
            
            talkingToNPC = False
            print "Loading map", g.getCurrentLevel()
            screen.fill((0x32, 0x21, 0x25))
            if g.getCurrentLevel() == 0:
                loadText = helperfunctions.renderTextBlock("Loading city", g.fontBig, 1, (255,255,255))
            else:
                loadText = helperfunctions.renderTextBlock("Loading level " + str(g.getCurrentLevel()), g.fontBig, 1, (255,255,255))
            screen.blit(loadText, (320-loadText.get_width()/2, 240 - loadText.get_height()/2))
            pygame.display.flip()
            
            for e in enemies:
                e.clearImages()
                
            enemies = []
            
            if g.getCurrentLevel() == 0:
                up = True
                gameMap = gamemap.Map()
                gameMap.loadMapTiled(0)
                mapGrid = gameMap.map
                
                player.map = mapGrid
                
                g.getSoundSystem().playMusic(0)
                
            else:
                if g.getCurrentLevel() % 5 == 0:
                    g.getSoundSystem().playMusic(2)
                else:
                    if g.getSoundSystem().getCurrentMusicTrack() != 1:
                        g.getSoundSystem().playMusic(1)
                up = g.getCurrentLevel() < player.mapLevel
                
                mapGrid = g.getMap()
                gameMap = gamemap.Map()
                gameMap.loadMap(mapGrid)
                
                player.map = mapGrid
                
            
            
            player.mapLevel = g.getCurrentLevel()
            
            if g.getCurrentLevel() != 0:
                enemies = g.getEnemies()
                for e in enemies:
                    e.loadImages()
            else:
                enemies = []
            
            
            
            items = g.getItems()
            
            if up:
                for i in items:
                    if i.type == constants.STAIRDOWN():
                        player.x = i.x+8
                        player.y = i.y+8
                    
            else:
                for i in items:
                    if i.type == constants.STAIRUP():
                        player.x = i.x+8
                        player.y = i.y+8
            
            miniMap.generateMinimap(mapGrid)
            levelImage = helperfunctions.renderTextBlock("Lvl: " + str(g.getCurrentLevel()), g.fontNormal, 1, (255,255,255))
            
            player.deepestLevel = max(player.deepestLevel, g.currentLevel)
            
            if dieTextId==240:
                player.x = 37*32
                player.y = 33*32
            
            
            gc.collect()
            
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                player.save()
                g.getSoundSystem().stop()
                keepPlaying = False
            elif (event.type == KEYDOWN):
                if ((event.key == K_i or event.key == K_c) and not showMenu):
                    showInventory = not showInventory
                elif (event.key == K_ESCAPE):
                    if showInventory:
                        showInventory = False
                    elif showMenu:
                        showMenu = False
                    elif talkingToNPC:
                        talkingToNPC = None
                    elif not showMenu:
                        showMenu = True
                        showInventory = False
                        
                elif (event.key == K_0):
                    if spellBook.magicBar[0] and player.mp >= g.getMagics()[spellBook.magicBar[0]][1]:
                        player.mp -= g.getMagics()[spellBook.magicBar[0]][1]
                        player.beginCastMagic(spellBook.magicBar[0])
                    else:
                        notEnoghMP = True
                elif (event.key == K_1):
                    if spellBook.magicBar[1] and player.mp >= g.getMagics()[spellBook.magicBar[1]][1]:
                        player.mp -= g.getMagics()[spellBook.magicBar[1]][1]
                        player.beginCastMagic(spellBook.magicBar[1])
                    else:
                        notEnoghMP = True
                elif (event.key == K_2):
                    if spellBook.magicBar[2] and player.mp >= g.getMagics()[spellBook.magicBar[2]][1]:
                        player.mp -= g.getMagics()[spellBook.magicBar[2]][1]
                        player.beginCastMagic(spellBook.magicBar[2])
                    else:
                        notEnoghMP = True
                elif (event.key == K_3):
                    if spellBook.magicBar[3] and player.mp >= g.getMagics()[spellBook.magicBar[3]][1]:
                        player.mp -= g.getMagics()[spellBook.magicBar[3]][1]
                        player.beginCastMagic(spellBook.magicBar[3])
                    else:
                        notEnoghMP = True
                elif (event.key == K_4):
                    if spellBook.magicBar[4] and player.mp >= g.getMagics()[spellBook.magicBar[4]][1]:
                        player.mp -= g.getMagics()[spellBook.magicBar[4]][1]
                        player.beginCastMagic(spellBook.magicBar[4])
                    else:
                        notEnoghMP = True
                elif (event.key == K_5):
                    if spellBook.magicBar[5] and player.mp >= g.getMagics()[spellBook.magicBar[5]][1]:
                        player.mp -= g.getMagics()[spellBook.magicBar[5]][1]
                        player.beginCastMagic(spellBook.magicBar[5])
                    else:
                        notEnoghMP = True
                elif (event.key == K_6):
                    if spellBook.magicBar[6] and player.mp >= g.getMagics()[spellBook.magicBar[6]][1]:
                        player.mp -= g.getMagics()[spellBook.magicBar[6]][1]
                        player.beginCastMagic(spellBook.magicBar[6])
                    else:
                        notEnoghMP = True
                elif (event.key == K_7):
                    if spellBook.magicBar[7] and player.mp >= g.getMagics()[spellBook.magicBar[7]][1]:
                        player.mp -= g.getMagics()[spellBook.magicBar[7]][1]
                        player.beginCastMagic(spellBook.magicBar[7])
                    else:
                        notEnoghMP = True
                elif (event.key == K_8):
                    if spellBook.magicBar[8] and player.mp >= g.getMagics()[spellBook.magicBar[8]][1]:
                        player.mp -= g.getMagics()[spellBook.magicBar[8]][1]
                        player.beginCastMagic(spellBook.magicBar[8])
                    else:
                        notEnoghMP = True
                elif (event.key == K_9):
                    if spellBook.magicBar[9] and player.mp >= g.getMagics()[spellBook.magicBar[9]][1]:
                        player.mp -= g.getMagics()[spellBook.magicBar[9]][1]
                        player.beginCastMagic(spellBook.magicBar[9])
                    else:
                        notEnoghMP = True
                #elif (event.key == K_F11):
                #    g.setCurrentLevel(max(g.getCurrentLevel() - 1, 0))
                #elif (event.key == K_F12):
                #    g.setCurrentLevel(g.getCurrentLevel() + 1)
            elif event.type == MOUSEBUTTONDOWN and event.button == 3: # Right button
                (itemX, itemY) = event.pos
                if g.getCurrentLevel() == 0 and talkingToNPC:
                    talkingToNPC.onClick(itemX-16,itemY-32)
                    
                if showInventory:
                    itemX -= 464
                    itemY -= 304
                    itemX /= 32
                    itemY /= 32
                    if itemX >= 0 and itemX < 5:
                        if itemY >= 0 and itemY < 5:
                            inventory.useItem(itemX, itemY)
                        
            elif (event.type == MOUSEBUTTONDOWN and event.button == 1): #Left button press
                (itemX, itemY) = event.pos
                
                
                if showMenu and itemX >= returnButtonPos[0] and itemX <= returnButtonPos[0] + returnButton.get_width(): 
                    if itemY >= returnButtonPos[1] and itemY <= returnButtonPos[1] + returnButton.get_height():
                        player.save()
                        g.getSoundSystem().stop()
                        return
                
                if showMenu and itemX >= exitButtonPos[0] and itemX <= exitButtonPos[0] + exitButton.get_width(): 
                    if itemY >= exitButtonPos[1] and itemY <= exitButtonPos[1] + exitButton.get_height():
                        sys.exit()
                
                
                
                if g.getCurrentLevel() == 0 and talkingToNPC:
                    itemToBuy = talkingToNPC.onClick(itemX-16,itemY-32)
                    
                    if not itemToBuy:
                        if showInventory:
                            itemX -= 464
                            itemY -= 304
                            itemX /= 32
                            itemY /= 32
                            if itemX >= 0 and itemX < 5:
                                if itemY >= 0 and itemY < 5:
                                    if talkingToNPC.type == constants.MERCHANT():
                                        itemToSell = inventory.removeItem(itemX, itemY)
                                        if itemToSell:
                                            player.money += itemToSell.sell
                    else:
                        if player.money >= itemToBuy.buy:
                            inventory.addItem(itemToBuy)
                            player.money -= itemToBuy.buy
                    
                if showInventory:
                    itemX -= 464
                    itemY -= 304
                    itemX /= 32
                    itemY /= 32
                    if itemX >= 0 and itemX < 5:
                        if itemY >= 0 and itemY < 5:
                            inventory.dropItem(itemX, itemY)
                
                
                
    
        if True in pygame.mouse.get_pressed():
            (mx, my) = pygame.mouse.get_pos()
            
            if showInventory and mx >= 448:
                pass
            else:
                if  pygame.mouse.get_pressed()[0]:
                    if g.getCurrentLevel() > 0:
                        player.attack()
                    else:
                        player.attacking = False
                else:
                    pass
                    #player.magic()
            
            my = 480 - my
            myAtan2 = math.atan2(my - 240, mx - 320);
            angle = math.degrees(myAtan2)
            
            if angle < 0:
                angle += 360
            
    
            if angle > 45 and angle < 135:
                player.direction = constants.NORTH()
            elif angle >= 135 and angle <= 225:
                player.direction = constants.WEST()
            elif angle >= 225 and angle <= 315:
                player.direction = constants.SOUTH()
            else:
                player.direction = constants.EAST()
    
            player.moving = False
        else:
            player.attacking = False
            #player.castingMagic = False
        
        
        
        
        keystate = pygame.key.get_pressed()
        
        walking = []
        if keystate[K_DOWN] or keystate[K_s]:
            walking.append(constants.SOUTH())
        if keystate[K_UP] or keystate[K_w]:
            walking.append(constants.NORTH())
        if keystate[K_LEFT] or keystate[K_a]:
            walking.append(constants.WEST())
        if keystate[K_RIGHT] or keystate[K_d]:
            walking.append(constants.EAST())
    
    
    
    
        #print enemies[0].x, enemies[0].y, enemies[0].scale
        """
        Talk to npcs
        """
        if g.getCurrentLevel() == 0 and keystate[K_e]:
            for n in npcs:
                if player.getItemHitRect().colliderect(n.getUseRect()):
                    talkingToNPC = n
                    n.talk()
    
        """
        Use item on ground
        """
        if not usePressed and keystate[K_e]:
            usePressed = True
            
            usedItem = False
            itemsInHitBox = []
            for i in g.getItems():
                if player.getItemHitRect().colliderect(i.getHitBox()):
                    itemsInHitBox.append(i)
            
            if len(itemsInHitBox) >= 1:
                # Sort so player dosent pick up stairs before items
                itemsInHitBox.sort(cmp=lambda x,y: cmp(x.level, y.level), key=None, reverse=True)
                
                itemsInHitBox[0].use()
                if itemsInHitBox[0].level >= 0:
                    answer = g.getInventroy().addItem(itemsInHitBox[0])
                    
                    if answer:
                        g.removeItem(itemsInHitBox[0])
                        itemsInHitBox[0].hitBox = Rect((-1,-1,0,0))
                        usedItem = True
            
            
        if not keystate[K_e]:
            usePressed = False
    
        for m in g.getMagic():
            m.update()
    
        enemiesInRange = []
        enemiesNotInRange = []
        for e in enemies:
            eOffsetx = e.x - player.x
            eOffsety = e.y - player.y
            
            eX = 320+(e.x - player.x)
            eY = 240+(e.y - player.y)
            if g.getCurrentLevel() % 5 == 0:
                enemiesInRange.append(e)
            else:
                if (eX > -128 and eX <= 640 and eY > -128 and eY <= 480):
                    enemiesInRange.append(e)
                else:
                    enemiesNotInRange.append(e)
    
        player.update(enemiesInRange)
        
        for e in enemiesInRange:
            e.update(True, enemiesInRange, player.x+4, player.y-12)
        for e in enemiesNotInRange:
            e.update(False)
        
    
        if len(walking) > 0:
            if g.getCurrentLevel() == 0:
                needToUpdate = player.moveTo(walking, npcs)
                talkingToNPC = None
            else:
                needToUpdate = player.moveTo(walking, enemiesInRange)
        else:
            player.moving = False
    
        screen.fill((0x32, 0x21, 0x25))
        
        
        
        """
        Draw floor tiles
        
        Fix this, so it uses the previous images => less ram consumption
        screen.blit(gameMap.getCurrertMapSurface(player.x-320, player.y-240)[0], (0,0))
        """
        #screen.blit(gameMap.getFloorMap(player.x, player.y), gameMap.getCoord(player.x, player.y))
        screen.blit(gameMap.floorMap, (320-player.x,240-player.y))
        
        
        """
        Draw items in range
        """
        for i in items:
            iOffsetx = i.x - player.x
            iOffsety = i.y - player.y
            
            iX = 320+(i.x - player.x)
            iY = 240+(i.y - player.y)
            
            if (iX > -128 and iX <= 640 and iY > -128 and iY <= 480):
                if i.level >= 0:
                    screen.blit(itemImages[(i.type, i.level)], (iX, iY))
        
        
        
        
        
        """
        Draw npcs above player
        """
        
        if g.getCurrentLevel() == 0:
            for npc in npcs:
                nX = 320+(npc.x - player.x)
                nY = 240+(npc.y - player.y)
                
                screen.blit(npc.getImage(), (nX, nY))
        
        """
        Draw enemies above player
        """
        for e in enemies:
            eX = 320+(e.x - player.x)
            eY = 240+(e.y - player.y)
            
            if g.getCurrentLevel() % 5 == 0:
                screen.blit(e.getCurrentImage(), (eX, eY))
                if e.attacking and e.hp > 0:
                    drawPos = weapons.getImagePos(e.type, (eX,eY), e.scale)
                    screen.blit(weapons.getImage(e.type, e.direction, e.imageIndex, e.scale), drawPos)
            else:
                if (eY < 200 and eX > -128 and eX <= 640 and eY > -128 and eY <= 480):
                    screen.blit(e.getCurrentImage(), (eX, eY))
                    if e.attacking and e.hp > 0:
                        drawPos = weapons.getImagePos(e.type, (eX,eY), e.scale)
                        screen.blit(weapons.getImage(e.type, e.direction, e.imageIndex, e.scale), drawPos)
            for d in e.dots:
                screen.blit(d.getImage(), (eX, eY))
                
        
        """
        Draw Magic above Player
        """
        for m in g.getMagic():
            mX = 320+(m.x - player.x)
            mY = 240+(m.y - player.y)
            
            if (mY < 200 and mX > -128 and mX <= 640 and mY > -128 and mY <= 480):
                screen.blit(m.getImage(), (mX, mY))
        
        
        """
        Draw player
        """
        screen.blit(player.getCurrentImage(), (320-32,240-48))
        if player.attacking:
            drawPos = weapons.getImagePos(player.type, (320-32,240-48))
            screen.blit(weapons.getImage(player.type, player.direction, player.imageIndex-1), drawPos)
        
        
        """
        Draw Magic below Player
        """
        for m in g.getMagic():
            mX = 320+(m.x - player.x)
            mY = 240+(m.y - player.y)
            
            if (mY >= 200 and mX > -128 and mX <= 640 and mY > -128 and mY <= 480):
                screen.blit(m.getImage(), (mX, mY))
        
        
        """
        Draw npcs below player
        """
        
        if g.getCurrentLevel() == 0:
            for npc in npcs:
                nX = 320+(npc.x - player.x)
                nY = 240+(npc.y - player.y)
                
                screen.blit(npc.getImage(), (nX, nY))
        
        """
        Draw enemys below player
        """
        for e in enemies:
            eX = 320+(e.x - player.x)
            eY = 240+(e.y - player.y)
            
            
            if g.getCurrentLevel() % 5 == 0:
                screen.blit(e.getCurrentImage(), (eX, eY))
                if e.attacking and e.hp > 0:
                    drawPos = weapons.getImagePos(e.type, (eX,eY), e.scale)
                    screen.blit(weapons.getImage(e.type, e.direction, e.imageIndex, e.scale), drawPos)
            else:
                if (eY >= 200 and eX > -128 and eX <= 640 and eY > -128 and eY <= 480):
                    screen.blit(e.getCurrentImage(), (eX, eY))
                    if e.attacking and e.hp > 0:
                        drawPos = weapons.getImagePos(e.type, (eX,eY), e.scale)
                        screen.blit(weapons.getImage(e.type, e.direction, e.imageIndex, e.scale), drawPos)
    
        """ 
        Draw Walls 
        """
        #screen.blit(gameMap.getWallMap(player.x, player.y), gameMap.getCoord(player.x, player.y))
        screen.blit(gameMap.wallMap, (320-player.x,240-player.y))
        
        """
        Draw enemy health bars
        """
        for e in enemies:
            eX = 320+(e.x - player.x)
            eY = 240+(e.y - player.y)
            hp = e.getHpLineWidth()/2
            if hp > 0:
                pygame.draw.line(screen, (255,0,0), (eX+32-hp,eY), (eX+32+hp,eY), 4)
            elif hp == 0 and e.removeThis:
                g.removeEnemy(e)    
        
        
        
        """
        Draw hp, mp & exp
        """
        pygame.draw.line(screen, (0,0,0), (0,16), (64,16), 32)
        hpLineWidth = player.getHpLineWidth()
        mpLineWidth = player.getMpLineWidth()
        expLineWidth = player.getExpLineWidth()
        if hpLineWidth > 0:
            pygame.draw.line(screen, (240,22,10), (3,7), (hpLineWidth+3,7), 14)
        pygame.draw.line(screen, (22,22,240), (3,20), (mpLineWidth+3,20), 14)
        pygame.draw.line(screen, (0,255,240), (3,28), (expLineWidth+3,28), 2)
        
        screen.blit(hudetc, (0,0))
    
    
        """
        Draw Magic bar
        """
        screen.blit(spellBook.getBarImage(), (160, 480-32))
        screen.blit(magicBar, (160, 480-32))
    
    
        """
        Draw inventory
        """    
        if showInventory:
            screen.blit(invent, (448,0))
            screen.blit(player.inventoryImage, (480,112))
            
            inventoryImages = inventory.getImages()
            for x in range(0,5):
                for y in range(0,5):
                    if inventoryImages[y][x] != 0:
                        screen.blit(inventoryImages[y][x], (464+x*32, 304+y*32))
            
            if inventory.bodyArmor != 0:
                screen.blit(itemImages[(constants.TORSO(), inventory.bodyArmor.level)], (464+128, 304-64-64))
            if inventory.legsArmor != 0:
                screen.blit(itemImages[(constants.LEGS(), inventory.legsArmor.level)], (464+128, 304-64-32))
            if inventory.feetArmor != 0:
                screen.blit(itemImages[(constants.FEET(), inventory.feetArmor.level)], (464+128-64, 304-64))
            if inventory.beltArmor != 0:
                screen.blit(itemImages[(constants.BELT(), inventory.beltArmor.level)], (464+128-64-64, 304-64-32))
            if inventory.headArmor != 0:
                screen.blit(itemImages[(constants.HEAD(), inventory.headArmor.level)], (464+128-64, 304-128-64))
            if inventory.weapon != 0:
                screen.blit(itemImages[(inventory.weapon.type, 0)], (464+128-64-64, 304-64-64))
            
            
            text = g.fontBig.render(player.getName(), 1, (255, 255, 100))
            textpos = text.get_rect()
            textpos.left = 464
            textpos.top = 2
            screen.blit(text, textpos)
            
            
            textSurface = helperfunctions.renderTextBlock(player.getStatsText(), g.fontNormal, 1, (255,255,255))
            screen.blit(textSurface, (464,30))
            
            
            """
            On mouse over an item in inventory
            """
            (mx, my) = pygame.mouse.get_pos()
            if mx and mx > 464 and my > 304:
                itemX = mx
                itemY = my
                itemX -= 464
                itemY -= 304
                itemX /= 32
                itemY /= 32
                
                if itemX >= 0 and itemX < 5:
                    if itemY >= 0 and itemY < 5:
                        if inventory.items[itemY][itemX] != 0:
                            
                            itemClass = inventory.items[itemY][itemX].type
                            
                            if itemClass == constants.BELT() and inventory.beltArmor != 0:
                                helperfunctions.drawImageTextBox(inventory.items[itemY][itemX], screen, 288, inventory.beltArmor)
                            elif itemClass == constants.FEET() and inventory.feetArmor != 0:
                                helperfunctions.drawImageTextBox(inventory.items[itemY][itemX], screen, 288, inventory.feetArmor)
                            elif itemClass == constants.HEAD() and inventory.headArmor != 0:
                                helperfunctions.drawImageTextBox(inventory.items[itemY][itemX], screen, 288, inventory.headArmor)
                            elif itemClass == constants.LEGS() and inventory.legsArmor != 0:
                                helperfunctions.drawImageTextBox(inventory.items[itemY][itemX], screen, 288, inventory.legsArmor)
                            elif itemClass == constants.TORSO() and inventory.bodyArmor != 0:
                                helperfunctions.drawImageTextBox(inventory.items[itemY][itemX], screen, 288, inventory.bodyArmor)
                            elif (itemClass == constants.DAGGER() or 
                                    itemClass == constants.LONGSPEAR() or itemClass == constants.LONGSWORD() or 
                                    itemClass == constants.RAPIER() or itemClass == constants.SPEAR() or 
                                    itemClass == constants.STAFF()):
                                
                                helperfunctions.drawImageTextBox(inventory.items[itemY][itemX], screen, 288, inventory.weapon)
                            else:
                                # No item to compare to
                                helperfunctions.drawImageTextBox(inventory.items[itemY][itemX], screen)
                            
                """
                On mouse over equipment
                """
            elif mx >= 592 and mx <= 624 and my >= 176 and my <= 208:
                if inventory.bodyArmor != 0:
                    helperfunctions.drawImageTextBox(inventory.bodyArmor, screen, 176)
            elif mx >= 592 and mx <= 624 and my >= 208 and my <= 240:
                if inventory.legsArmor != 0:
                    helperfunctions.drawImageTextBox(inventory.legsArmor, screen, 208)
            elif mx >= 528 and mx <= 560 and my >= 240 and my <= 272:
                if inventory.feetArmor != 0:
                    helperfunctions.drawImageTextBox(inventory.feetArmor, screen, 240)
            elif mx >= 464 and mx <= 496 and my >= 208 and my <= 240:
                if inventory.beltArmor != 0:
                    helperfunctions.drawImageTextBox(inventory.beltArmor, screen, 208)
            elif mx >= 464 and mx <= 496 and my >= 176 and my <= 208:
                if inventory.weapon != 0:
                    helperfunctions.drawImageTextBox(inventory.weapon, screen, 176)
            elif mx >= 528 and mx <= 560 and my >= 112 and my <= 144:
                if inventory.headArmor != 0:
                    helperfunctions.drawImageTextBox(inventory.headArmor, screen, 112)
        
        elif showMenu:
            screen.blit(menu, (192, 112))
            
            screen.blit(returnButton, returnButtonPos)
            screen.blit(exitButton, exitButtonPos)
            
        else:
            screen.blit(miniMap.getSmallImage(player.x, player.y), (548, 0))
            screen.blit(minimapBG, (640-92, 0))
            
            screen.blit(levelImage, (640-levelImage.get_width()-1, 92))
            
        
        
        if talkingToNPC and talkingToNPC.talking:
            dialogImage = talkingToNPC.getDialogImage()
            dialogImage = helperfunctions.addBorder(dialogImage)
            
            screen.blit(dialogImage,(16,32))
            
            (mx, my) = pygame.mouse.get_pos()
            mx -= 16
            my -= 32
            
            if talkingToNPC.type == constants.MERCHANT():
                if mx >= talkingToNPC.itemStartX and mx <= talkingToNPC.itemStartX+160:
                    if my >= talkingToNPC.itemStartY and my <= talkingToNPC.itemStartY+64:
                        my -= talkingToNPC.itemStartY
                        x = mx/32
                        y = my/32
                        
                        if (len(talkingToNPC.itemsForSale)) > (x+5*y):
                            item = talkingToNPC.itemsForSale[x+5*y]
                            itemClass = item.type
                            
                            if itemClass == constants.BELT() and inventory.beltArmor != 0:
                                itemText = item.getText(inventory.beltArmor)
                            elif itemClass == constants.FEET() and inventory.feetArmor != 0:
                                itemText = item.getText(inventory.feetArmor)
                            elif itemClass == constants.HEAD() and inventory.headArmor != 0:
                                itemText = item.getText(inventory.headArmor)
                            elif itemClass == constants.LEGS() and inventory.legsArmor != 0:
                                itemText = item.getText(inventory.legsArmor)
                            elif itemClass == constants.TORSO() and inventory.bodyArmor != 0:
                                itemText = item.getText(inventory.bodyArmor)
                            elif (itemClass == constants.DAGGER() or 
                                    itemClass == constants.LONGSPEAR() or itemClass == constants.LONGSWORD() or 
                                    itemClass == constants.RAPIER() or itemClass == constants.SPEAR() or 
                                    itemClass == constants.STAFF()):
                                
                                itemText = item.getText(inventory.weapon)
                            else:
                                # No item to compare to
                                itemText = item.getText()
    
    
                            itemText = helperfunctions.renderTextBlock(itemText, g.fontNormal, 1, (255,255,255))
                            itemText = helperfunctions.addBorder(itemText)
                            
                            screen.blit(itemText, (16,32+dialogImage.get_height()))
                            
        
        if player.exp == 0:
            screen.blit(helpText, helpTextPos)
        
        (mx, my) = pygame.mouse.get_pos()
        
        
       
        if mx >= 160 and mx <= 640-160:
            if my >= 480-32 and my <= 480:
                mx -= 160
                mx /= 32
                mx += 1
                if mx == 10:
                    mx = 0
                
                if mx >= 0 and mx <= 9 and spellBook.magicBar[mx]:
                    magic = g.getMagics()[spellBook.magicBar[mx]]

                    magicText = magic[2] + "\n" + magic[3]
                    magicText = helperfunctions.renderTextBlock(magicText, g.fontNormal, 1, (255,255,255))
                    magicText = helperfunctions.addBorder(magicText)
                    
                    x = pygame.mouse.get_pos()[0]
                    if x + magicText.get_width() > 640:
                        x = 640 - magicText.get_width()
                    
                    screen.blit(magicText, (x, 480 - 32 - magicText.get_height()))
        
        
        if dieTextId > 0:
            dieTextId -= 1
            screen.blit(diedText, diedTextPos)
        
        
        for i in range(0, len(player.buffs)):
            screen.blit(helperfunctions.addBorderFixedSize((g.getMagicIcons()[player.buffs[i].type]), 2, 2), (64,i*64))
            
        
        pygame.display.flip()
        clock.tick(60)
    
    
#concave()
    
    
