'''  
    Copyright (c) 2012, Steve Peck aka gr3yh47 <gr3yh47@gmail.com>
    See COPYING.txt for full license text

    game.py
    This file is part of Bright Flame Tactics.

    Bright Flame Tactics 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.

    Bright Flame Tactics 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 Bright Flame Tactics.  If not, see <http://www.gnu.org/licenses/>.
    
    some code derived from qq, Copyright (c) 2008, 2009 Radomir Dopieralski <qq@sheep.art.pl>. see qq.rar for source and license
    
'''
import ConfigParser
import pygame
import pygame.locals as pg
import random
import os
from collections import deque, defaultdict
from map import *
from status import *
from items import *
from sprites import *


'''GLOBALS'''
#x and y offsets to iterate through for looking at adjacent tiles
#     N  W  S   E
DX = [0, -1, 0, 1]
DY = [-1, 0, 1, 0]

# Dimensions of the map tiles
TILE_WPIX, TILE_HPIX = 32, 32
   
  
class Game(object):
    '''main game object. builds all other objects'''
    
    def __init__(self):
        self.team_a = [] #list of players, team 1/A
        self.team_b = [] #list of players, team 2/B
        self.graveyard_a = [] #list of dead players, team 1/A
        self.graveyard_b = [] #list of dead players, team 2/B
        self.team_c = [] #currently unused, for 3rd parties in battles
        self.screen = pygame.display.get_surface()
        self.pressed_key = None
        battle_over = False
        self.shadows = pygame.sprite.RenderUpdates()
        self.sprites = SortedUpdates()
        self.fight_sprites = SortedUpdates()
        self.overlays = pygame.sprite.RenderUpdates()
        self.one_player = True #will be false for 2 player game
        self.clock = pygame.time.Clock()
        #number sprites used to show damage
        self.whiteones = Numbers()
        self.whitetens = Numbers('white', 'tens')
        self.redones = Numbers('red')
        self.redtens = Numbers('red', 'tens')
        self.crit_sprite = BattleMessage()
        self.dodge_sprite = BattleMessage('dodge')
        
        self.loading = []
        load_dir = os.path.join('.', 'graphics', 'loading')
        for load_msg in os.listdir(load_dir):
            self.loading.append(pygame.image.load(os.path.join(load_dir, load_msg)))
        
        #self.stat_panel = 'a'
        #self.panel_page = 0
        self.help = {}
        self.help['move'] = pygame.image.load(os.path.join('.', 'graphics', 'help', 'move.png')).convert()
        self.help['menu'] = pygame.image.load(os.path.join('.', 'graphics', 'help', 'menu.png')).convert()
        self.help['menu2'] = pygame.image.load(os.path.join('.', 'graphics', 'help', 'menu2.png')).convert()
        self.help['attack'] = pygame.image.load(os.path.join('.', 'graphics', 'help', 'attack.png')).convert()
        self.help['item'] = pygame.image.load(os.path.join('.', 'graphics', 'help', 'item.png')).convert()
        self.help['confirm'] = pygame.image.load(os.path.join('.', 'graphics', 'help', 'confirm.png')).convert()
        self.help['status'] = pygame.image.load(os.path.join('.', 'graphics', 'help', 'status.png')).convert()
        
        self.help_visible = True
        self.help_pos = (0, 500)
        
        self.char_names = []
        f = open(os.path.join('.', 'configs', 'names.txt'))
        for line in f:
            self.char_names.append(line.strip())
        
        #dicts for mapping stings to classes
        self.cls_d = {'Swordsman': Swordsman, 'Spearman': Spearman, 
                'Archer': Archer, 'Cavalry': Cavalry, 'Mage': Mage}
        
        self.wpn_d = {'Dagger': Dagger, 'Rapier': Rapier, 'Broadsword': Broadsword,
                'Longsword': Longsword, 'Zweihander': Zweihander,
                'Pike': Pike, 'Lance': Lance, 'Trident': Trident,
                'Spontoon': Spontoon, 'Longspear': Longspear,
                'Shortbow': Shortbow, 'Longbow': Longbow, 'Recurvebow': Recurvebow,
                'Heavybow': Heavybow, 'Crossbow': Crossbow,
                'Fire': Fire, 'Ice': Ice, 'Heal': Heal,
                'Lightning': Lightning, 'Tornado': Tornado}
                
        self.ldr_d = {'Power': 'str', 'Strategy': 'int', 'Efficiency': 'spd', 'Fortune': 'lck'}
        
        #populate weapon options and handedness by class
        self.wpns = defaultdict(list)
        self.handed = defaultdict(list)
        for cls in self.cls_d.iterkeys():
            f = open(os.path.join('.', 'configs', cls.lower() + 'wpns.txt'))
            g = open(os.path.join('.', 'configs', cls.lower() + 'handed.txt'))
            for line in f:
                self.wpns[cls].append(line.split())
            for line in g:
                self.handed[cls].append(int(line.strip()))
                                
        #sound initialization
        pygame.mixer.init()
        self.snd = {}
        sound_dir = os.path.join('.', 'sounds')
        self.snd['a'] = {}
        self.snd['b'] = {}
        for team in ['a', 'b']:
            for snd_type in os.listdir(os.path.join(sound_dir, team)):
                self.snd[team][snd_type] = []
                for snd_file in os.listdir(os.path.join(sound_dir, team, snd_type)):
                    if snd_file[-1] == 'v':
                        self.snd[team][snd_type].append(pygame.mixer.Sound(os.path.join(sound_dir, team, snd_type, snd_file)))
                        
        self.snd['menu'] = {}
        self.snd['menu']['select'] = pygame.mixer.Sound(os.path.join('.', 'sounds', 'menuselect.wav'))
        self.snd['menu']['confirm'] = pygame.mixer.Sound(os.path.join('.', 'sounds', 'menuconfirm.wav'))
        self.snd['menu']['cancel'] = pygame.mixer.Sound(os.path.join('.', 'sounds', 'menucancel.wav'))
        
        self.snd['battle'] = {}
        self.snd['battle']['cancel'] = pygame.mixer.Sound(os.path.join('.', 'sounds', 'battlecancel.wav'))
        self.snd['battle']['select'] = pygame.mixer.Sound(os.path.join('.', 'sounds', 'battleselect.wav'))
        self.snd['battle']['confirm'] = pygame.mixer.Sound(os.path.join('.', 'sounds', 'battleconfirm.wav'))
        
        
        self.snd['music'] = {}
        self.snd['music']['menu'] = pygame.mixer.Sound(os.path.join('.', 'sounds', 'music', 'menu.wav'))
        self.snd['music']['level'] = pygame.mixer.Sound(os.path.join('.', 'sounds', 'music', 'level.wav'))
        self.snd['music']['fight'] = pygame.mixer.Sound(os.path.join('.', 'sounds', 'music', 'fight.wav'))
        self.snd['music']['victory'] = pygame.mixer.Sound(os.path.join('.', 'sounds', 'music', 'victory.wav'))
        
        

  
    def intro(self):
        self.license()
        self.logos()
        self.lpc_animation()
        self.gr3yh47()
        self.snd['music']['menu'].play(-1)
        self.start_screen()
    
    def license(self):
        license_file = os.path.join('.', 'graphics', 'title', 'license.png')
        license_image = pygame.image.load(license_file)
        self.fade(license_image)
        for i in xrange(120):
            pygame.event.pump()
            self.clock.tick(15)
        self.fade(license_image, 'out')
        
    def logos(self):
        logos_file = os.path.join('.', 'graphics', 'title', 'logos.png')
        logos_image = pygame.image.load(logos_file)
        self.fade(logos_image)
        for i in xrange(60):
            pygame.event.pump()
            self.clock.tick(15)
        self.fade(logos_image, 'out')
     
    def lpc_animation(self):
        pixel_file = os.path.join('.', 'graphics', 'title', 'pixel.png')
        pixel_image = pygame.image.load(pixel_file)
        cage_file = os.path.join('.', 'graphics', 'title', 'cage.png')
        cage_image = pygame.image.load(cage_file)
        lpc_file = os.path.join('.', 'graphics', 'title', 'lpcpixelmissing.png')
        lpc_image = pygame.image.load(lpc_file)
        exclaimation_file = os.path.join('.', 'graphics', 'title', 'exclaimation.png')
        exclaimation_image = pygame.image.load(exclaimation_file)
        question_file = os.path.join('.', 'graphics', 'title', 'question.png')
        question_image = pygame.image.load(question_file)
        animation_sound = pygame.mixer.Sound(os.path.join('.', 'sounds', 'lpc_animation.wav'))
        bg_image = pygame.Surface((800, 600))
        
        
        bg_image.fill((0, 0, 0))
        bg_image.blit(pixel_image, (99, 110))
        bg_image.blit(cage_image, (78, 0))
        self.fade(bg_image)
        
        animation_sound.play()
        for i in xrange(8):
            bg_image.fill((0, 0, 0))
            pixel_x = 99 + 10 * i
            bg_image.blit(pixel_image, (pixel_x, 110))
            bg_image.blit(cage_image, (78, 0))
            self.screen.blit(bg_image, (0, 0))
            pygame.display.flip()
            self.clock.tick(15)
            pygame.event.pump()
        
        for i in xrange(20):
            bg_image.fill((0, 0, 0))
            pixel_x = 99 + 10 * i
            bg_image.blit(pixel_image, (169, 110))
            bg_image.blit(cage_image, (78, 0))
            if i > 9:
                bg_image.blit(exclaimation_image, (169, 100))
            self.screen.blit(bg_image, (0, 0))
            pygame.display.flip()
            self.clock.tick(15)
            pygame.event.pump()
            
        
        pixel_y = 110
        for i in xrange(13):
            bg_image.fill((0, 0, 0))
            bg_image.blit(cage_image, (78, 0))
            pixel_y = pixel_y + 5 * i
            bg_image.blit(pixel_image, (169, pixel_y))
            self.screen.blit(bg_image, (0, 0))
            pygame.display.flip()
            self.clock.tick(15)
            pygame.event.pump()        
            
        for i in xrange(25):
            bg_image.fill((0, 0, 0))
            bg_image.blit(cage_image, (78, 0))
            pixel_x = 99 + 10 * i
            bg_image.blit(pixel_image, (169, 500))
            if 4 < i < 15:
                bg_image.blit(question_image, (169, 489))
            self.screen.blit(bg_image, (0, 0))
            pygame.display.flip()
            self.clock.tick(15)
            pygame.event.pump()
            
        bg_image.fill((0, 0, 0))
        bg_image.blit(cage_image, (78, 0))
        
        self.fade(lpc_image, 'in', bg_image, (0, 420), (800, 144), pixel_image, (169, 500))
        
        for i in xrange(30):
            self.clock.tick(15)
            pygame.event.pump()
            
        temp_image = pygame.Surface((800, 600))
        temp_image.blit(self.screen, (0, 0))
        self.fade(temp_image, 'out')
     
    def gr3yh47(self):
        bg_file = os.path.join('.', 'graphics', 'title', 'gr3yh47bg.png')
        bg_image = pygame.image.load(bg_file).convert()
        gr3yh47_file = os.path.join('.', 'graphics', 'title', 'gr3yh47.png')
        gr3yh47_image = pygame.image.load(gr3yh47_file).convert_alpha()
        
        self.fade(bg_image)
        self.fade(gr3yh47_image, 'in', bg_image, (250, 200))
        
        for i in xrange(30):
            pygame.event.pump()
            self.clock.tick(15)
        
        bg_image.blit(gr3yh47_image, (250, 200))
        self.fade(bg_image, 'out')
          
    def start_screen(self):
        title_file = os.path.join('.', 'graphics', 'title', 'title.png')
        title_img = pygame.image.load(title_file).convert_alpha()
        self.fade(title_img)
        start = False
        toggle = 0
        diff = 1
        color = (0, 0, 0)
        def pressed(key):
            return self.pressed_key == key
        
        while not start:
            self.screen.fill(color)
            self.screen.blit(title_img, (0, 0))
            pygame.display.flip()
            self.clock.tick(15)
            
            for event in pygame.event.get():
                if event.type == pg.KEYDOWN:
                    self.pressed_key = event.key
            
            if pressed(pg.K_SPACE) or pressed(pg.K_RETURN):
                start = True
                self.snd['menu']['confirm'].play()
                self.pressed_key = None
                
            toggle += diff
            if toggle == 4:
                diff = -1
                color = (255, 255, 255)
            elif toggle == 0:
                diff = 1
                color = (0, 0, 0)
                          
    def fade(self, image, direction = 'in', bg = None, image_pos = (0, 0), size = (800, 600), extra = None, e_pos = (0, 0), num_frames = 25, color = (0, 0, 0)):
        solid = pygame.Surface(size)
        solid.fill(color)
        if direction == 'in':
            solid.set_alpha(255)
            increment = -(255 / num_frames)
            end = 0
        else:
            solid.set_alpha(0)
            increment = 255 / num_frames
            end = 255
            
        current_image = pygame.Surface(size)
        for i in xrange(num_frames):
            current_image.fill(color)
            current_image.blit(image, (0, 0))
            current_alpha = solid.get_alpha()
            if i < num_frames - 1:
                solid.set_alpha(current_alpha + increment)
            else:
                solid.set_alpha(end)
            current_image.blit(solid, (0, 0))
            if bg:
                final_image = pygame.Surface((800, 600))
                final_image.blit(bg, (0, 0))
                final_image.blit(current_image, image_pos)
                current_image = final_image
            self.screen.blit(current_image, (0, 0))
            if extra:
                self.screen.blit(extra, e_pos)
            pygame.display.flip()
            self.clock.tick(15)
            pygame.event.pump()
         
    def choose_map(self):
        map_names = []
        f = open(os.path.join('.', 'configs', 'mapnames.txt'))
        for line in f:
            map_names.append(line.strip())
        map_nums = [0, 1, 3]
        map_files = []
        map_imgs = []
        name_txts = []
        color = (0, 0, 0)
        this_font = pygame.font.Font(os.path.join('.', 'fonts', 'Trinigan.ttf'), 36)  
        for map_num, map_name in zip(map_nums, map_names):
            map_img_file = 'level' + str(map_num) + '.png'
            map_imgs.append(pygame.image.load(os.path.join('.', 'configs', map_img_file)))
            map_files.append('level' + str(map_num) + '.tmx')
            name_txts.append(this_font.render(map_name, 1, color))
        
        this_font = pygame.font.Font(os.path.join('.', 'fonts', 'Trinigan.ttf'), 64)  
        title_txt = this_font.render('Select The Battlefield', 1, color)
     
        
        def pressed(key):
            #read only current event for space and enter
            return self.pressed_key == key
        
        map_choice = 0
        while True:
            keys = pygame.key.get_pressed()
            pygame.display.flip()
            self.clock.tick(15)
            
            for event in pygame.event.get():
                if event.type == pg.KEYDOWN:
                    self.pressed_key = event.key

            if pressed(pg.K_1):
                map_choice = 0
                self.snd['menu']['select'].play()
            elif pressed(pg.K_2):
                map_choice = 1
                self.snd['menu']['select'].play()
            elif pressed(pg.K_3) and len(map_nums) >= 3:
                map_choice = 2
                self.snd['menu']['select'].play()
            elif pressed(pg.K_4) and len(map_nums) >= 4:
                map_choice = 3
                self.snd['menu']['select'].play()
            elif pressed(pg.K_5) and len(map_nums) >= 5:
                map_choice = 4
                self.snd['menu']['select'].play()
            elif pressed(pg.K_6) and len(map_nums) >= 6:
                map_choice = 5
                self.snd['menu']['select'].play()
            elif pressed(pg.K_7) and len(map_nums) >= 7:
                map_choice = 6
                self.snd['menu']['select'].play()
            elif pressed(pg.K_SPACE) or pressed(pg.K_RETURN):
                self.pressed_key = None 
                self.snd['menu']['confirm'].play()
                return map_files[map_choice]
            elif pressed(pg.K_h):
                self.toggle_help_display()
            
            self.pressed_key = None 
            
            #draw background, map, text
            self.screen.fill((0, 0, 0))
            self.screen.blit(self.background, (0, 0))
            txt_x = (800 - title_txt.get_width()) / 2
            self.screen.blit(title_txt, (txt_x, 60))
            img_x = (800 - map_imgs[map_choice].get_width() ) / 2
            img_y = (600 - map_imgs[map_choice].get_height() ) / 2
            self.screen.blit(map_imgs[map_choice], (img_x, img_y))
            txt_x = (800 - name_txts[map_choice].get_width()) / 2
            self.screen.blit(name_txts[map_choice], (txt_x, 470))
            self.screen.blit(self.help['menu2'], self.help_pos)
            #draw index numbers
            this_font = pygame.font.Font(os.path.join('.', 'fonts', 'UbuntuMono-R.ttf'), 16)  
            test = this_font.render('0', 1, color)
            num_width = test.get_width()
            starting_x = (800 - test.get_width() * len(map_nums)) / 2
            for index_num in xrange(len(map_nums)):
                if index_num == map_choice:
                    color = (0, 0, 0)
                else: 
                    color = (115, 115, 115)
                index_img = this_font.render(str(index_num + 1), 1, color)
                index_x = starting_x + index_num * num_width
                self.screen.blit(index_img, (index_x, 455))
                
    def choose_mode(self):
        background = pygame.image.load(os.path.join('.', 'graphics', 'creationgui', 'bg.png')).convert_alpha()
        color = (0, 0, 0)
        this_font = pygame.font.Font(os.path.join('.', 'fonts', 'Trinigan.ttf'), 64)  
        title_txt = this_font.render('Select Game Mode', 1, color)
        
        positions = [(240, 250), (460, 250)]
        
        mode_imgs = []
        mode_txts = []
        this_font = pygame.font.Font(os.path.join('.', 'fonts', 'Trinigan.ttf'), 18)
        mode_names = ['Deathmatch', 'CTF']
        for mode_name in mode_names:
            img_file = os.path.join('.', 'graphics', 'creationgui', mode_name.lower() + '.png')
            mode_imgs.append(pygame.image.load(img_file))
            mode_txts.append(this_font.render(mode_name, 1, color))
        
        def pressed(key):
            #read only current event for space and enter
            return self.pressed_key == key
                
        mode_choice = 0
        while True:
            keys = pygame.key.get_pressed()
            pygame.display.flip()
            self.clock.tick(15)
            
            for event in pygame.event.get():
                if event.type == pg.KEYDOWN:
                    self.pressed_key = event.key

            if pressed(pg.K_1):
                mode_choice = 0
                self.snd['menu']['select'].play()
            elif pressed(pg.K_2):
                mode_choice = 1
                self.snd['menu']['select'].play()
            elif pressed(pg.K_SPACE) or pressed(pg.K_RETURN):
                self.pressed_key = None 
                self.snd['menu']['confirm'].play()
                break
            elif pressed(pg.K_h):
                self.toggle_help_display()
            self.pressed_key = None    
            
            #draw background, map, text
            self.screen.fill((0, 0, 0))
            self.screen.blit(background, (0, 0))
            txt_x = (800 - title_txt.get_width()) / 2
            self.screen.blit(title_txt, (txt_x, 60))
            for mode_img, mode_txt, pos in zip(mode_imgs, mode_txts, positions):
                self.screen.blit(self.wood1, pos)
                self.screen.blit(mode_img, pos)
                txt_x = (96 - mode_txt.get_width()) / 2 + pos[0]
                txt_y = pos[1] + 100
                self.screen.blit(mode_txt, (txt_x, txt_y))
                
            self.screen.blit(self.wood2, positions[mode_choice])
            self.screen.blit(mode_imgs[mode_choice], positions[mode_choice])
            
            self.screen.blit(self.help['menu'], self.help_pos)
                
                
    
        if mode_choice == 0:
            a_condition = 1
            b_condition = 1
            #erase the flags if we arent playing ctf
            for (x, y) in [self.map.a_condition, self.map.b_condition]:
                self.map.tiles[x][y].overlay = None
        elif mode_choice == 1:
            a_condition = self.map.a_condition
            b_condition = self.map.b_condition
        return a_condition, b_condition
            
  
    def use_map(self, map, fight_bg_file = os.path.join('.', 'graphics', 'fightbg1.png')):
        '''loads the map for the level'''
        self.shadows = pygame.sprite.RenderUpdates()
        self.sprites = SortedUpdates()
        self.overlays = pygame.sprite.RenderUpdates()
        self.map = map
        
        self.background, overlays = self.map.render()
        self.fight_background = pygame.image.load(fight_bg_file).convert_alpha()
        
        self.set_team_pos(self.team_a)
        self.set_team_pos(self.team_b, 'b')
        self.screen_size = (max((map.width) * 32, 800), (map.height) * 32)
        pygame.display.set_mode(self.screen_size)
        
        help_y = self.screen_size[1] - 100
        self.help_pos = (0, help_y)
  
    def update_panels(self):
        '''updates the stats for everyone'''
        for player in self.team_a + self.team_b:
            player.collection.refresh()
  
  
    def battle(self, a_condition = 1, b_condition = 1):
        '''analogous to a Level, this is one battle between 2 teams'''
        #if condition is 1, everyone must be defeated. 
        if a_condition == 1:
            cond_string = 'Defeat all enemies!'
        #if condition is a coordinate tuple, that coord must be taken by the player
        else:
            a_cond_string = 'Capture the goal square' + str(a_condition)
            b_cond_string = 'Capture the goal square' + str(b_condition)
        self.turn_order = None
        #keep going until the condition is met or a whole team is dead
        while not self.condition_met(a_condition, b_condition):
            self.get_turn_order()
            while self.turn_order:
                self.update_panels()
                p_active, p_team = self.turn_order.popleft() #current player's turn and team
                if not self.condition_met(a_condition, b_condition):
                    if p_active in self.graveyard_a or p_active in self.graveyard_b:
                        pass
                    else:
                        #'a' team is always a player
                        if p_team == 'a':
                            self.player_turn(p_active)
                        else:
                            if self.one_player:
                                self.ai_turn(p_active) #ai turn for one player game
                            else:
                                self.player_turn(p_active) #player turn for 2 player game
        #reset teams and advance
        
    def condition_met(self, a_condition, b_condition):
        '''checks if winning condition is met'''
        if a_condition == 1:
            if not self.team_b:
                self.show_victory_screen('A', 1)
                return True
            elif not self.team_a:
                self.show_victory_screen('A', 2)
                return True
            else:
                return False
        else:
            team_a_target, team_b_target = a_condition, b_condition
            if self.map.tiles[team_a_target[0]][team_a_target[1]].affinity == 'a':
                self.show_victory_screen('a', a_condition)
                return True
            elif self.map.tiles[team_b_target[0]][team_b_target[1]].affinity == 'b':
                self.show_victory_screen('b', b_condition)
                return True
            else:
                return False
                
    def show_victory_screen(self, team, condition):
        self.snd['music']['level'].stop()
        self.snd['music']['victory'].play()
        this_font = pygame.font.Font(os.path.join('.', 'fonts', 'Trinigan.ttf'), 72)
        color = (11, 92, 47) #Kelly Green-ish
        victory_txt = this_font.render('Victory!', 1, color) 
        this_font = pygame.font.Font(os.path.join('.', 'fonts', 'Trinigan.ttf'), 24)
        if team == 'A':
            team_num = 1
        else:
            team_num = 2
        triumph_string = 'Team ' + str(team_num) + ' has triumphed by:'
        triumph_txt = this_font.render(triumph_string, 1, color)
        if condition == 1:
            condition_strings = []
            condition_strings.append("ERADICATING the enemy")
            condition_strings.append("WIPING the other team off the map")
            condition_strings.append("Destroying the other team MERCILESSLY")
            condition_strings.append("BRUTALLY beating down their foes")
            condition_strings.append("Humiliating the other team to DEATH")
            condition_strings.append("KILLING the other team's hopes - and their bodies.")            
            
            random.shuffle(condition_strings)
            condition_string = condition_strings[1]
        else:
            condition_string = 'Capturing the enemy flag at coordinates ' + str(condition)
        condition_txt = this_font.render(condition_string, 1, color)
        
        victory_bg = pygame.image.load(os.path.join('.', 'graphics', 'victorybg.png')).convert_alpha()
        #victory_bg = pygame.Surface((600, 400))
        #victory_bg.fill((255, 255, 255))
        txt_x = (600 - victory_txt.get_width()) / 2
        victory_bg.blit(victory_txt, (txt_x, 70))
        txt_x = (600 - triumph_txt.get_width()) / 2
        victory_bg.blit(triumph_txt, (txt_x, 185))
        txt_x = (600 - condition_txt.get_width()) / 2
        victory_bg.blit(condition_txt, (txt_x, 245))
        
        self.screen.blit(victory_bg, (100, 100))
        pygame.display.flip()
        for i in xrange(90):
            self.clock.tick(15)
            pygame.event.pump()
            
        self.reset_all()
        
    def reset_all(self):
        self.snd['music']['menu'].play(-1)
        same_teams = self.ask_same_teams()
        if same_teams:
            self.background = pygame.image.load(os.path.join('.', 'graphics', 'creationgui', 'bg.png')).convert_alpha()
            self.use_same_teams()
        else:
            quit()
        
    def ask_same_teams(self):
        background = pygame.image.load(os.path.join('.', 'graphics', 'creationgui', 'bg.png')).convert_alpha()
        color = (0, 0, 0)
        this_font = pygame.font.Font(os.path.join('.', 'fonts', 'Trinigan.ttf'), 48)  
        title_txt = this_font.render('Play again with same teams?', 1, color)
        this_font = pygame.font.Font(os.path.join('.', 'fonts', 'Trinigan.ttf'), 24)  
        note_txt = this_font.render('Note: the weaker (by level) team will be levelled up for balance', 1, color)
        
        positions = [(240, 250), (460, 250)]
        
        choice_imgs = []
        choice_txts = []
        this_font = pygame.font.Font(os.path.join('.', 'fonts', 'Trinigan.ttf'), 18)
        choices = ['Yes', 'No']
        for choice in choices:
            img_file = os.path.join('.', 'graphics', 'creationgui', choice.lower() + '.png')
            choice_imgs.append(pygame.image.load(img_file))
            choice_txts.append(this_font.render(choice, 1, color))
        
        def pressed(key):
            #read only current event for space and enter
            return self.pressed_key == key
                
        answer = 0
        while True:
            keys = pygame.key.get_pressed()
            pygame.display.flip()
            self.clock.tick(15)
            
            for event in pygame.event.get():
                if event.type == pg.KEYDOWN:
                    self.pressed_key = event.key

            if pressed(pg.K_1):
                answer = 0
                self.snd['menu']['select'].play()
            elif pressed(pg.K_2):
                answer = 1
                self.snd['menu']['select'].play()
            elif pressed(pg.K_SPACE) or pressed(pg.K_RETURN):
                self.pressed_key = None 
                self.snd['menu']['confirm'].play()
                if answer == 0:
                    return True
                else:
                    return False
            elif pressed(pg.K_h):
                self.toggle_help_display()
            self.pressed_key = None
            
            #draw background, map, text
            self.screen.fill((0, 0, 0))
            self.screen.blit(background, (0, 0))
            txt_x = (800 - title_txt.get_width()) / 2
            self.screen.blit(title_txt, (txt_x, 60))
            txt_x = (800 - note_txt.get_width()) / 2
            self.screen.blit(note_txt, (txt_x, 110))
            for choice_img, choice_txt, pos in zip(choice_imgs, choice_txts, positions):
                self.screen.blit(self.wood1, pos)
                self.screen.blit(choice_img, pos)
                txt_x = (96 - choice_txt.get_width()) / 2 + pos[0]
                txt_y = pos[1] + 100
                self.screen.blit(choice_txt, (txt_x, txt_y))
                
            self.screen.blit(self.wood2, positions[answer])
            self.screen.blit(choice_imgs[answer], positions[answer])
            
            self.screen.blit(self.help['menu'], self.help_pos)
                
        
        
    def use_same_teams(self):
        self.team_a.extend(self.graveyard_a)
        self.team_b.extend(self.graveyard_b)
        self.graveyard_a = []
        self.graveyard_b = []
        a_lvl_total = 0
        b_lvl_total = 0
        for player_a, player_b in zip(self.team_a, self.team_b):
            a_lvl_total += player_a.stats['lvl']
            b_lvl_total += player_b.stats['lvl']
            
        lvl_diff = a_lvl_total - b_lvl_total
        self.balance_teams(lvl_diff)
        
        #display the fact that teams are balanced
        
        self.start_2p(False)
    
    
    
    def balance_teams(self, lvl_diff):        
        if lvl_diff > 0:
            weaker_team = self.team_b
        elif lvl_diff < 0:
            weaker_team = self.team_a
        else:
            return None
        
        random.shuffle(weaker_team)
        lvl_up_nums = [1] * lvl_diff
        
        for player, lvl in zip(itertools.cycle(weaker_team), lvl_up_nums):
            player.lvl_up()
              
    def map_select(self):
        pass #TBI
                
    def get_turn_order(self):
        '''gets the turn order based on previous order and spd stats, creates one if none previous'''
        
        turn_order = deque([])
        if not self.turn_order:
            temp_a = deque(self.team_a)
            temp_b = deque(self.team_b)
            #populate turn order while players remain
            if self.team_c:
                turn_order.expand(self.team_c)
            while temp_a or temp_b:  
                #if next b is much faster than next a, b goes before a
                if temp_a and temp_b and temp_b[0].get_stat('spd') - temp_a[0].get_stat('spd') >= 2:
                    #tuples for easy access to team
                    turn_order.append((temp_b.popleft(), 'b'))
                    turn_order.append((temp_a.popleft(), 'a'))
                else:
                    if temp_a:
                        turn_order.append((temp_a.popleft(), 'a'))
                    if temp_b:
                        turn_order.append((temp_b.popleft(), 'b'))
        else:
            while self.turn_order:
                #if next player is much slower than second next player, swap them
                if len(prev_order) > 1 and prev_order[1][0].get_stat('spd') - prev_order[0][0].get_stat('spd') >= 2:
                    turn_order.append(prev_order.pop(1))
                    turn_order.append(prev_order.popleft())
                #otherwise just put next player in turn order
                else:
                    turn_order.append(prev_order.popleft())
        self.turn_order = turn_order
        
    def set_team_pos(self, team_list, team = 'a'):
        '''sets character positions on valid starting squares at random'''

        random.seed()
        start_list = self.map.start_list[team]
        random.shuffle(start_list)
        #puts the teams near eachother for testing
        # if team == 'a':
            # start_list = [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0)]
        for (x, y), member in zip(start_list, team_list):
        #for member in team_list:
            #i = random.randint(0, len(start_list) - 1)
            #x, y = start_list.pop(i)
            member.x, member.y = x, y
            member.pos = x, y
            self.map.tiles[x][y].occupy(member)
            self.sprites.add(member)
    
    
       
    def ai_turn(self, my_map):
        '''ai turn calls including ai logic'''
        pass #unimplemented
        
    def player_turn(self, p_active):
        '''top level method that calls all methods involving player turn.
        also handles mounted units and cleanup'''
        valid_moves, valid_coords = self.map.get_valid_moves(p_active)
        valid_atk = self.map.get_valid_atk(p_active, valid_coords)
        self.map.print_valid_moves(valid_moves)
        confirmed = False 
        #vacate the square so that the player can land on the same square if they want
        x, y = p_active.pos
        self.map.tiles[x][y].vacate()
        choice = None
        self.screen.blit(self.help['move'], (0, 500))
        while not confirmed:
            high_squares = self.map.highlight_valid_squares(valid_moves, valid_atk)
            self.background, overlays = self.map.render()
            self.screen.blit(self.background, (0,0))
            for (overlay, position) in self.map.render_overlays():
                self.screen.blit(overlay, position)
            
            pygame.display.flip()
            choice = self.player_mvt_phase(p_active, valid_coords)
            #ask if they want to use an item or attack a char
            #if item:
                #confirmed = self.item_menu()
            #else:
            if choice == 'atk':                
                self.map.reset_highlights(high_squares)
                real_atk = self.map.get_valid_atk(p_active)
                x, y = p_active.pos
                high_squares = self.map.highlight_valid_squares([self.map.tiles[x][y]], real_atk)
                self.background, overlays = self.map.render()
                self.screen.blit(self.background, (0,0))
                pygame.display.flip()
                confirmed = self.atk_phase(p_active, real_atk)
            elif choice == 'item':
                confirmed = self.item_phase(p_active)
            elif choice == 'status':
                confirmed = self.status_phase(p_active)
            elif choice == 'wait':
                confirmed = self.confirm('wait')
            self.map.reset_highlights(high_squares)
        #special stuff for mounted units
        if p_active.mounted:
            x, y = p_active.pos
            dist_moved = abs(p_active.x - x) + abs(p_active.y - y)
            p_active.mounted -= dist_moved
        if p_active.mounted and choice <> 'wait': #if there are mvt points left for mounted unit
            valid_moves, valid_coords = self.map.get_valid_moves(p_active)
            high_squares = self.map.highlight_valid_squares(valid_moves, None)
            self.background, overlays = self.map.render()
            confirmed = False
            while not confirmed:
                self.player_mvt_phase(p_active, valid_coords)
                confirmed = self.confirm('wait')
            self.map.reset_highlights(high_squares)
        p_active.x, p_active.y = p_active.pos
        if p_active.cls == 'Cavalry': #reset mounted stat if cavalry
            p_active.mounted = p_active.get_stat('mvt')
        #end of turn stuff
        #when mvt and attack is done, occupy the landing square
        x, y = p_active.pos    
        self.map.tiles[x][y].occupy(p_active)
    
    def player_mvt_phase(self, p_active, valid_coords):
        '''handles player mvt and animation'''
    
        clock = pygame.time.Clock()
        nextphase = None
        while not nextphase:
            p_active.depth = p_active.rect.center[1]
            self.screen.fill((0, 0, 0))
            self.screen.blit(self.background, (0, 0))
            self.sprites.update()
            if p_active.animation is None:
                nextphase = self.player_control(valid_coords, p_active)
                p_active.update()
            self.sprites.draw(self.screen)
            self.overlays.draw(self.screen)
            for (overlay, position) in self.map.render_overlays():
                self.screen.blit(overlay, position)
            #update dirty areas of the screen
            self.screen.blit(self.help['move'], self.help_pos)
            pygame.display.flip()
            #one tick
            clock.tick(30)
            # Process pygame events
            for event in pygame.event.get():
                flag = 0
                if event.type == pg.KEYDOWN and flag == 0:
                    self.pressed_key = event.key
                    if event.key == pg.K_SPACE:
                        flag = 1
                if event.type == pg.KEYUP and event.key == pg.K_SPACE:
                    flag = 0
            x, y = p_active.pos
            if self.map.tiles[x][y].is_occupied:
                nextphase = None 
        return nextphase
    
    def player_control(self, valid_coords, p_active):
        '''reads arrow keys and space during mvt phase of player turn'''
    
        keys = pygame.key.get_pressed()
    
        def pressed(key): #check if key is pressed
            #use keystate if it is one of the arrow keys
            if key == pg.K_UP or key == pg.K_DOWN or key == pg.K_LEFT or key == pg.K_RIGHT:
                return self.pressed_key == key or keys[key]
            #only use event for everything else
            else: 
                return self.pressed_key == key
            
        def walk(d): #walk in direction of key press
            x, y = p_active.pos
            p_active.direction = d 
            if (x + DX[d], y + DY[d]) in valid_coords:
                p_active.animation = p_active.walk_animation()
                p_active.depth += (32 * DY[d])
        if pressed(pg.K_UP):
            walk(0)
        elif pressed(pg.K_DOWN):
            walk(2)
        elif pressed(pg.K_LEFT):
            walk(1)
        elif pressed(pg.K_RIGHT):
            walk(3)
        elif pressed(pg.K_SPACE) or pressed(pg.K_RETURN) or pressed(pg.K_a):
            self.pressed_key = None 
            return 'atk'
        elif pressed(pg.K_i) or pressed (pg.K_d):
            self.pressed_key = None
            return 'item'
        elif pressed(pg.K_s) or pressed(pg.K_v):
            return 'status'
        elif pressed(pg.K_w) or pressed (pg.K_n):
            self.pressed_key = None
            return 'wait'
        elif pressed(pg.K_h):
            self.toggle_help_display()
        self.pressed_key = None 
        return False
    
    def confirm(self, text, context = None):
        '''Displays confirmation dialogue for various things. context can be passed in to determine behavior'''
        
        this_font = pygame.font.Font(os.path.join('.', 'fonts', 'UbuntuMono-R.ttf'), 12)
        color = (217, 183, 92)
        line1 = this_font.render('Are you sure you', 1, color)
        line2 = this_font.render('want to ' + text + '?', 1, color)
        if context:
            image_part = context.confirm()
            real_height = image_part.get_height() + 24
            real_width = max(image_part.get_width(), line1.get_width())
            real_image = pygame.Surface((real_width, real_height))
            real_image.fill((62, 38, 19))
            img_x = (real_image.get_width() - image_part.get_width()) / 2
            real_image.blit(image_part, (img_x, 24))
        else:
            real_width = max(line1.get_width(), line2.get_width())
            real_image = pygame.Surface((real_width, 24))
            real_image.fill((62, 38, 19))
        pos1 = (real_width - line1.get_width())/2
        pos2 = (real_width - line2.get_width())/2
        real_image.blit(line1, (pos1, 0))
        real_image.blit(line2, (pos2, 12))
        def pressed(key): #check if key is pressed
            return self.pressed_key == key
         
        while True:
            self.clock.tick(15)
            for event in pygame.event.get():
                if event.type == pg.KEYDOWN:
                    self.pressed_key = event.key
            if pressed(pg.K_y) or pressed(pg.K_SPACE) or pressed(pg.K_RETURN):
                self.snd['battle']['confirm'].play()            
                self.pressed_key = None
                return True
            elif pressed(pg.K_n) or pressed(pg.K_ESCAPE) or pressed(pg.K_BACKSPACE):
                self.snd['menu']['cancel'].play()
                self.pressed_key = None
                return False
            elif pressed(pg.K_h):
                self.toggle_help_display()
                self.pressed_key = None
                
            self.screen.fill((0, 0, 0))
            self.screen.blit(self.background, (0, 0))
            self.sprites.draw(self.screen)
            self.overlays.draw(self.screen)
            for (overlay, position) in self.map.render_overlays():
                self.screen.blit(overlay, position)
            #draw confirmation dialogue, help display
            self.screen.blit(real_image, (300, 300))
            self.screen.blit(self.help['confirm'], self.help_pos)
            pygame.display.flip()
            
    def atk_phase(self, p_active, real_atk):
        '''handles opponent selection if the player chose to attack'''
    
        #only allow truly attackable squares to be selected
        attackable = [(tile.x, tile.y) for tile in real_atk if not tile.is_traversable(p_active.team)]
        pygame.display.flip()
        selection = Selection()
        if attackable:
            selection.pos = attackable[0]
        else:
            return False #turn not confirmed if there is no one to attack
        self.sprites.add(selection)
        action = None
        while True:
            action = self.selection_control(attackable, selection)
            #selection.update()
            self.screen.fill((0, 0, 0))
            self.screen.blit(self.background, (0, 0))
            self.sprites.update()
            self.sprites.draw(self.screen)
            for (overlay, position) in self.map.render_overlays():
                self.screen.blit(overlay, position)
            self.screen.blit(self.help['attack'], self.help_pos)
            pygame.display.flip()
            self.clock.tick(15)
            #process pygame events
            for event in pygame.event.get():
                flag = 0
                if event.type == pg.KEYDOWN and flag == 0:
                    self.pressed_key = event.key
                    if event.key == pg.K_SPACE:
                        flag = 1
                if event.type == pg.KEYUP and event.key == pg.K_SPACE:
                    flag = 0
            x, y = selection.pos
            atk_tile = self.map.tiles[x][y]
            if action == 'esc':
                selection.kill()
                return False #turn not confirmed if they hit esc
            if action == 'space':      
                selection.kill()
                advance = self.choose_weapon(p_active, atk_tile)
                if self.confirm('attack', atk_tile.character) and advance:
                    self.fight(p_active, atk_tile)
                    return True
                else:
                    return False
                
    def selection_control(self, attackable, selection):
        '''handles target selection for self.atk_phase()'''
        keys = pygame.key.get_pressed()
    
        def pressed(key): #check if key is pressed
            return self.pressed_key == key
            
        def change(d):
            self.snd['battle']['select'].play()
            selection.i += 1
            try:
                selection.pos = attackable[selection.i]
            except IndexError:
                selection.i = 0
                selection.pos = attackable[selection.i]
            # if (attackable.index(selection.pos) + 1) in xrange(len(attackable)):
                # selection.pos = attackable[attackable.index(selection.pos) + 1]
            # else:
                # selection.pos = attackable[0]
            # pass
            
        if pressed(pg.K_UP):
            change(0)
        elif pressed(pg.K_DOWN):
            change(2)
        elif pressed(pg.K_LEFT):
            change(3)
        elif pressed(pg.K_RIGHT):
            change(1)
        elif pressed(pg.K_SPACE) or pressed(pg.K_RETURN):
            self.pressed_key = None 
            return 'space'
        elif pressed(pg.K_ESCAPE) or pressed(pg.K_BACKSPACE):
            self.pressed_key = None 
            return 'esc'
        elif pressed(pg.K_h):
            self.toggle_help_display()
        self.pressed_key = None 
        return None
      
    def choose_weapon(self, p_active, atk_tile):
        
        defender = atk_tile.character
        a_x, a_y = p_active.pos
        d_x, d_y = defender.pos
        y_dist = abs(d_y - a_y)
        x_dist = abs(d_x - a_x)
        dist = x_dist + y_dist
        
        if dist in p_active.e_weapon.ranges:
            pass
        elif dist in p_active.p_weapon.ranges:
            p_active.p_weapon.equip()
        elif dist in p_active.s_weapon.ranges:
            p_active.s_weapon.equip()
        
        highlight = 0
        self.screen.blit(p_active.inventory.show(0, True, dist), (300, 100))
        pygame.display.flip()

        while True:
        
            for event in pygame.event.get():
                if event.type == pg.KEYDOWN:
                    self.pressed_key = event.key
            #keys = pygame.key.get_pressed()
            def pressed(key): #check if key is pressed
                return self.pressed_key == key #or keys[key]
                
            if pressed(pg.K_UP):
                self.snd['battle']['select'].play()
                highlight = max(highlight - 1, 0)
            elif pressed(pg.K_DOWN):
                self.snd['battle']['select'].play()
                highlight = min(highlight + 1, 1)
            elif pressed(pg.K_SPACE) or pressed(pg.K_RETURN):
                if p_active.inventory.items[highlight].is_equippable:
                    if dist in p_active.inventory.items[highlight].ranges:
                        self.snd['battle']['confirm'].play()
                        p_active.inventory.items[highlight].equip()
                        self.pressed_key = None
                        return True
                    else:
                        self.snd['battle']['cancel'].play()
            elif pressed(pg.K_ESCAPE) or pressed(pg.K_BACKSPACE):
                self.snd['battle']['cancel'].play()
                self.pressed_key = None
                return False
            elif pressed(pg.K_h):
                self.toggle_help_display()
                self.pressed_key = None
            self.pressed_key = None
              
            self.screen.fill((0, 0, 0))
            self.screen.blit(self.background, (0, 0))
            self.sprites.draw(self.screen)
            self.overlays.draw(self.screen)
            for (overlay, position) in self.map.render_overlays():
                self.screen.blit(overlay, position)
            self.screen.blit(p_active.inventory.show(highlight, True, dist), (300, 100))
            self.screen.blit(self.help['item'], self.help_pos)
            pygame.display.flip()
            self.clock.tick(15)
      
    def fight(self, attacker, atk_tile):
        '''calculates damage and counterattack between two players after atk_phase'''
        
        defender = atk_tile.character
        weapon = attacker.e_weapon
        #preserve the original pos and direction so i can put them back later     
        a_pos = attacker.pos
        a_dir = attacker.direction
        d_pos = defender.pos
        d_dir = defender.direction
        
        a_x, a_y = attacker.pos
        d_x, d_y = defender.pos
        y_dist = d_y - a_y
        x_dist = d_x - a_x
        dist = x_dist + y_dist
        
        if abs(y_dist) >= abs(x_dist):
            dir = DY.index(abs(y_dist)/y_dist)
        else:
            dir = DX.index(abs(x_dist)/x_dist)
        
        xp, damage = weapon.attack(attacker, defender, self.map)
        attacker.scale = True
        defender.scale = True
        self.fight_animation_phase(attacker, defender, damage, dir, False, True)
        #self.counter(defender, attacker, a_x, a_y, dir)
        ##possibly add an if weapon.double here - would primarily be ranged wpns
        #xp2, damage = weapon.attack(attacker, defender)
        #xp += xp2
        #self.fight_animation_phase(attacker, defender, damage, dir)
        
        attacker.scale = False
        defender.scale = False
        
        self.fight_sprites.empty()
        #if they got any xp, the least they will get is 1
        if xp:
            min_xp = 1
        else:
            min_xp = 0
        if defender.stats['hp'] < 1: #kill xp
            xp += 3
            min_xp += 1
        a_level = float(attacker.stats['lvl'])
        d_level = float(defender.stats['lvl'])
        adj_xp = int(max(round(xp * d_level / a_level), min_xp))
        attacker.stats['xp'] += adj_xp
        
        attacker.check_lvl(self.screen)
        defender.check_lvl(self.screen)
        self.update_panels()
        attacker.direction = a_dir
        attacker.pos = a_pos
        defender.direction = d_dir
        defender.pos = d_pos
        self.screen.fill((0,0,0))
        pygame.display.flip()
        
        if defender.stats['hp'] < 1:
            x, y = defender.pos
            self.map.tiles[x][y].vacate()
            if defender.team == 'a':
                self.team_a.remove(defender)
                self.graveyard_a.append(defender)
            else:
                self.team_b.remove(defender)
                self.graveyard_b.append(defender)
            defender.kill()
    
    def counter(self, counterer, opponent, op_x, op_y, dir):
        '''function calls logic and animations for counterattack'''
        #flipping the direction for the counter
        c_dir = [2, 3, 0, 1]
        dir = c_dir[dir]
        c_weapon = counterer.in_range(op_x, op_y)
        if c_weapon:
            xp, damage = c_weapon.attack(counterer, opponent, self.map)
            counterer.stats['xp'] += xp
            self.fight_animation_phase(counterer, opponent, damage, dir, True)                
        else:
            pass
   
    def fight_animation_phase(self, attacker, defender, damage, dir, is_counter = False, init = False):
        '''handles fight animation with damage calculated in self.fight()'''
        
        self.snd['music']['level'].stop()
        self.snd['music']['fight'].play(-1)
        #initialization tasks and animations only needed for the first of 3 hits (attack, counter attack)
        if init:
            pygame.display.set_mode((800, 600))
            crit = None
            dodge = None
            #add the 2 characters to the special fight_sprites group that is 
            #populated here, and emptied after this method is called for the last time
            self.fight_sprites.add(attacker)
            self.fight_sprites.add(defender)
            #building and displaying the fight splash screen
            text_color = (127, 0, 0)
            fight_font = pygame.font.Font(os.path.join('.', 'fonts', 'MedievalSharp.ttf'), 72)
            vs_font = pygame.font.Font(os.path.join('.', 'fonts', 'MedievalSharp.ttf'), 24)
            fight_text = fight_font.render('Fight!', 1, text_color)
            vs_text = vs_font.render('vs.', 1, text_color)
            splash = pygame.Surface((800, 600))
            splash.fill((0, 0, 0))
            fight_x = (800 - fight_text.get_width())/2
            vs_x = (800 - vs_text.get_width())/2
            col_width = attacker.collection.image.get_width()
            col1_x = vs_x - col_width - 12
            col2_x = vs_x + vs_text.get_width() + 12
            splash.blit(fight_text, (fight_x, 100))
            splash.blit(attacker.collection.image, (col1_x, 250))
            splash.blit(vs_text, (vs_x, 300))
            splash.blit(defender.collection.image, (col2_x, 250))
            self.screen.blit(splash, (0, 0))
            pygame.display.flip()
            #wait a sec before clearing the splash screen and showing the fight scene
            for i in xrange (15):
                self.clock.tick(15)
            self.screen.blit(self.fight_background, (0, 0))
            pygame.display.flip()
            #change the character's facing an absolute position for the fight.
            #pos_list = ((16, 8), (5, 16), (0, 8), (5, 0))
            pos_list = ((-3, 2), (6, -2), (-3, -14),  (-10, -2))
            attacker.direction = dir
            attacker.pos = pos_list[attacker.direction]
            #'oppositing' the direction for the defender
            d_dirs = [2, 3, 0, 1]
            defender.direction = d_dirs[dir]
            defender.pos = pos_list[defender.direction]
            self.sprites.clear(self.screen, self.fight_background)
            #pre attack animation, of the players moving towards each other
            defender.animation = defender.pre_atk_animation()
            attacker.animation = attacker.pre_atk_animation()
            while defender.animation or attacker.animation:
                self.fight_sprites.clear(self.screen, self.fight_background)
                # advance the attack animation
                #defender.animation.next()
                #attacker.animation.next()
                defender.update()
                attacker.update()

                dirty = self.fight_sprites.draw(self.screen)
                pygame.display.update(dirty)

                self.clock.tick(15)
            for i in xrange(15):
                self.clock.tick(15)
            if attacker.e_weapon.action == 'bow' or attacker.e_weapon.action == 'spell':
                attacker.animation = attacker.ranged_atk_animation()
                ticks = 30
            else:
                attacker.animation = attacker.atk_animation(dir)
                ticks = 15

        
        #attacker on left, defender on right, with their tiles below them
        #hp bars, class, and current/max hp only above them
        

        #set up the numbers that display damage
        ones_digit = damage % 10
        tens_digit = damage / 10
        ones = self.redones
        self.fight_sprites.add(ones)
        ones.animation = ones.num_animation(ones_digit)
        if tens_digit:
            tens = self.redtens
            self.fight_sprites.add(tens)
            tens.animation = tens.num_animation(tens_digit)
            
        #old logic for when there were counters
        # if is_counter: 
            # ones = self.redones
            # self.fight_sprites.add(ones)
            # ones.animation = ones.num_animation(ones_digit)
            # if tens_digit:
                # tens = self.redtens
                # self.fight_sprites.add(tens)
                # tens.animation = tens.num_animation(tens_digit)
        # else:
            # ones = self.whiteones
            # self.fight_sprites.add(ones)
            # ones.animation = ones.num_animation(ones_digit)
            # if tens_digit:
                # tens = self.whitetens
                # self.fight_sprites.add(tens)
                # tens.animation = tens.num_animation(tens_digit)
        
        if attacker.e_weapon.was_crit:
            crit = self.crit_sprite
            self.fight_sprites.add(crit)
            if defender.direction % 2: #if there is a remainder it means this was 1 or 3 which is vertical fight
                crit.pos = (11, 9)
            else:
                crit.pos = (9, 10)
            crit.animation = crit.message_animation()
        
        nums_pos_list = ((12, 3), (8, 10), (12, 12),  (16, 10))
        ones.pos = (nums_pos_list[attacker.direction])
        if tens_digit:
            tens.pos = (nums_pos_list[attacker.direction])
            
        attacker_sound = random.choice(self.snd[attacker.team]['attack'])    
        if damage > 0:
            defender.animation = defender.hurt_animation(len(attacker.frames[attacker.action]))
            hurt = True
            defender_sound = random.choice(self.snd[defender.team]['hurt'])
        else:
            defender.animation = defender.dodge_animation(len(attacker.frames[attacker.action]))
            hurt = False
            defender_sound = random.choice(self.snd[defender.team]['dodge'])
            dodge = self.dodge_sprite
            self.fight_sprites.add(dodge)
            if defender.direction % 2: #if there is a remainder it means this was 1 or 3 which is vertical fight
                dodge.pos = (11, 9)
            else:
                dodge.pos = (9, 10)
            dodge.animation = dodge.message_animation()
        
        
        attacker_sound.play()
        while defender.animation or attacker.animation:
            if attacker.e_weapon.name == 'Ice':
                attacker.depth = 0
            elif attacker.e_weapon.name == 'Fire' or attacker.e_weapon.name == 'Lightning' or attacker.e_weapon.name == 'Tornado':
                attacker.depth = 1000
            self.fight_sprites.clear(self.screen, self.fight_background)
            # advance the attack animation
            ##print 'updating defender and attacker'
            self.fight_sprites.update()
            dirty = self.fight_sprites.draw(self.screen)
            pygame.display.update(dirty)

            self.clock.tick(ticks)
            
            if defender.play_sound:
                defender_sound.play()
            
            if hurt:
                ##print 'hurt, clearing sprites'
                self.fight_sprites.clear(self.screen, self.fight_background)
                ##print 'updating defender animation'
                defender.update()
                #defender.update()
                ##print 'assigning dirty'
                dirty = self.fight_sprites.draw(self.screen)
                ##print dirty
                pygame.display.update(dirty)
            self.clock.tick(ticks)
            
                
            
        if hurt:
            ones.kill()
            if tens_digit:
                tens.kill()
        if attacker.p_weapon.was_crit:
            self.crit_sprite.kill()
        if dodge:
            dodge.kill()
        if crit:
            crit.kill()
                
        self.screen.fill((0, 0, 0))
        pygame.display.set_mode(self.screen_size)
        
        self.snd['music']['fight'].stop()
        self.snd['music']['level'].play(-1)
      
    def item_phase(self, p_active):
        '''handles everything for item selection phase, both display and events'''
        highlight = 0
        self.screen.blit(p_active.inventory.show(), (300, 100))
        pygame.display.flip()

        while True:
        
            for event in pygame.event.get():
                if event.type == pg.KEYDOWN:
                    self.pressed_key = event.key
            #keys = pygame.key.get_pressed()
            def pressed(key): #check if key is pressed
                return self.pressed_key == key #or keys[key]
                
            if pressed(pg.K_UP):
                self.snd['battle']['select'].play()
                highlight = max(highlight - 1, 0)
            elif pressed(pg.K_DOWN):
                self.snd['battle']['select'].play()
                highlight = min(highlight + 1, len(p_active.inventory.items) - 1)
            elif pressed(pg.K_SPACE) or pressed(pg.K_RETURN):
                self.snd['battle']['confirm'].play()
                if p_active.inventory.items[highlight].is_equippable:
                    p_active.inventory.items[highlight].equip()
                    self.pressed_key = None
                else:
                    self.pressed_key = None
                    if self.confirm('use', p_active.inventory.items[highlight]):
                        p_active.inventory.items[highlight].use()
                        return True
            elif pressed(pg.K_ESCAPE) or pressed(pg.K_BACKSPACE):
                self.snd['battle']['cancel'].play()
                self.pressed_key = None
                return False
            elif pressed(pg.K_h):
                self.toggle_help_display()
                self.pressed_key = None
            self.pressed_key = None
            self.screen.fill((0, 0, 0))
            self.screen.blit(self.background, (0, 0))
            self.sprites.draw(self.screen)
            self.overlays.draw(self.screen)
            for (overlay, position) in self.map.render_overlays():
                self.screen.blit(overlay, position)
            self.screen.blit(p_active.inventory.show(highlight), (300, 100))
            self.screen.blit(self.help['item'], self.help_pos)
            pygame.display.flip()
            self.clock.tick(15)
   
    def status_phase(self, p_active):
        selection = Selection('menuselect.png')
        selection.pos = p_active.pos
        self.sprites.add(selection)
        action = None
        
        def pressed(key): #check if key is pressed
            return self.pressed_key == key
        
        def s_change(dir):
            x, y = selection.pos
            x += DX[dir]
            y += DY[dir]
            
            if x < len(self.map.tiles) and y < len(self.map.tiles[0]):
                    selection.pos = (x, y)
            else:
                pass
                    
        x_pos = 0
        current_char = None
        while True:
            #redraw everything
            self.screen.fill((0, 0, 0))
            self.screen.blit(self.background, (0, 0))
            self.sprites.update()
            self.sprites.draw(self.screen)
            for (overlay, position) in self.map.render_overlays():
                self.screen.blit(overlay, position)
            self.screen.blit(self.help['status'], self.help_pos)
            if current_char:
                self.screen.blit(current_char.inventory.show(None), (x_pos, 100))
            pygame.display.flip()
            self.clock.tick(15)
            #process pygame events
            for event in pygame.event.get():
                if event.type == pg.KEYDOWN:
                    self.pressed_key = event.key
                    
            x, y = selection.pos
            
            if self.map.tiles[x][y].character:
                current_char = self.map.tiles[x][y].character
                if x > len(self.map.tiles) / 2:
                    x_pos = 0
                else:
                    x_pos = self.screen.get_width() - 200
            elif p_active.pos == (x, y):
                current_char = p_active
            else:
                current_char = None
                
    
            if pressed(pg.K_UP):
                s_change(0)
            elif pressed(pg.K_DOWN):
                s_change(2)
            elif pressed(pg.K_LEFT):
                s_change(1)
            elif pressed(pg.K_RIGHT):
                s_change(3)
            elif pressed(pg.K_ESCAPE) or pressed(pg.K_BACKSPACE):
                self.pressed_key = None 
                selection.kill()
                return None
            elif pressed(pg.K_h):
                self.toggle_help_display()
            self.pressed_key = None 
        
 
 
    def game_test(self):
        pygame.key.set_repeat()
        ap1 = Archer('a')
        self.sprites.add(ap1)
        ap1.p_weapon = Shortbow()
        ap1.draw_weapons()
        ap2 = Swordsman('a')
        ap2.p_weapon = Broadsword()
        bp1 = Spearman('b')
        bp1.p_weapon = Javelin()
        bp2 = Spearman('b')
        bp2.p_weapon = Pike()
        self.team_a.append(ap1)
        self.team_a.append(ap2)
        self.team_b.append(bp1)
        self.team_b.append(bp2)
        
        
        self.set_team_pos(self.team_a)
        self.set_team_pos(self.team_b, 'b')
        
        self.screen.blit(self.background, (0,0))
        self.a_panel = StatPanel(self.team_a)
        self.b_panel = StatPanel(self.team_b)
        stat_image = self.a_panel.update()
        self.screen.blit(stat_image, (self.screen.get_width() - 100, 0)) 
        
        pygame.display.flip()
        
        
        
        self.battle()
    
    def main(self, mode = '2p'):
        if mode == 'Test':
            self.game_test()
        
        if mode == '1p':
            self.start_1p()
        
        if mode == '2p':
            self.start_2p()
        
    def start_1p(self):
        self.char_creation()
        
    def start_2p(self, init = True):
        if init:
            self.menu_player = "Player 1: "
            self.char_creation()
            self.menu_player = "Player 2: "
            self.char_creation(2)
        map_file = self.choose_map()
        self.use_map(Map(map_file))
        a_condition, b_condition = self.choose_mode()
        self.one_player = False
        self.snd['music']['menu'].stop()
        self.snd['music']['level'].play(-1)
        self.battle(a_condition, b_condition)
   
   
   
    def char_creation(self, player = 1):
        '''captain character creation method.
        used for both 1 and 2 player games'''
        self.page = 1
        self.px = defaultdict(lambda: 0)
        while self.page < 5:
            if self.page == 1:
                self.select_cls()
            if self.page == 2:
                self.select_weapons()#both primary and secondary
            if self.page == 3:
                self.select_style()
            if self.page == 4:
                self.select_team()
            if self.page == 5:
                #character_confirmation()
                pass
                
        pygame.event.set_blocked(pygame.KEYDOWN)
                
        self.screen.fill((0, 0, 0))
        self.screen.blit(self.loading[0], (0, 0))
        pygame.display.flip()
        if player == 1:
            team = 'a'
        else:
            team = 'b'
        
        
        temp = self.cls_d[self.px['cls']](team)
        temp.p_weapon = self.wpn_d[self.px['pw']]()
        temp.inventory.add(temp.p_weapon, temp)
        temp.p_weapon.equip()
        if self.px['sw']:
            temp.s_weapon = self.wpn_d[self.px['sw']]()
            temp.inventory.add(temp.s_weapon, temp)
            
        temp.inventory.add(Potion())
        
        names = self.char_names
        random.shuffle(names)
        if player == 1:
            self.p1 = temp
            self.p1.name = names[random.randint(10, 700)]
            self.team_a.append(self.p1)
        else:
            self.p2 = temp
            self.p2.name = names[random.randint(10, 700)]
            self.team_b.append(self.p2)
            
        ldr_stat = self.ldr_d[self.px['style']]
        self.screen.blit(self.loading[1], (0, 0))
        pygame.display.flip()
        for cls, name in zip(self.px['team'], names):
            pygame.event.pump()
            t_player = self.cls_d[cls](team)
            #randomly assigning weapons
            i = random.randint(0, len(self.wpns[cls][0]) - 1)
            pw_name = self.wpns[cls][0][i]
            t_player.p_weapon = self.wpn_d[pw_name]()
            t_player.inventory.add(t_player.p_weapon, t_player)
            t_player.p_weapon.equip()
            t_player.stats[ldr_stat] += 1
            t_player.inventory.add(Potion())
            if i not in self.handed[cls]:
                j = random.randint(0, 3)
                sw_name = self.wpns[cls][1][j]
                t_player.s_weapon = self.wpn_d[sw_name]()
                t_player.inventory.add(t_player.s_weapon, t_player)
            t_player.name = name
            if player == 1:
                self.team_a.append(t_player)
            else:
                self.team_b.append(t_player)
            
        self.screen.blit(self.loading[2], (0, 0))
        pygame.display.flip()
        for character in self.team_a + self.team_b:
            pygame.event.pump()
            character.draw_weapons()
            
        pygame.event.set_allowed(pygame.KEYDOWN)
                
    def select_cls(self):
        classes = ['Swordsman', 'Spearman', 'Mage', 'Archer', 'Cavalry']
        
        self.background = pygame.image.load(os.path.join('.', 'graphics', 'creationgui', 'bg.png')).convert_alpha()
        self.wood1 = pygame.image.load(os.path.join('.', 'graphics', 'creationgui', 'wood1.png')).convert()
        self.wood2 = pygame.image.load(os.path.join('.', 'graphics', 'creationgui', 'wood2.png')).convert()
        self.px['cls'] = 'Swordsman'
        positions = [(130, 170), (350, 170), (570, 170), (240, 350), (460, 350)]
        this_font = pygame.font.Font(os.path.join('.', 'fonts', 'Trinigan.ttf'), 18)
        color = (0, 0, 0)
        cls_img1 = []
        cls_img2 = []
        txt_img = []
        for cls in classes:
            filename1 = os.path.join('.', 'graphics', 'creationgui', cls.lower() + '1.png')
            filename2 = os.path.join('.', 'graphics', 'creationgui', cls.lower() + '2.png')
            cls_img1.append(pygame.image.load(filename1).convert_alpha())
            cls_img2.append(pygame.image.load(filename2).convert_alpha())
            txt_img.append(this_font.render(cls, 1, color))
        
        #Title text
        this_font = pygame.font.Font(os.path.join('.', 'fonts', 'Trinigan.ttf'), 64)  
        title_txt = this_font.render(self.menu_player + 'Select Your Class', 1, color)
        
        def pressed(key):
            return self.pressed_key == key
                
        choice_num = 0
        choice_prev = 1
        wait = 4
        toggle = 0
        current_img = cls_img1[0]
        while True:
            keys = pygame.key.get_pressed()
            pygame.display.flip()
            self.clock.tick(15)
            
            for event in pygame.event.get():
                if event.type == pg.KEYDOWN:
                    self.pressed_key = event.key

            if pressed(pg.K_1):
                self.px['cls'] = 'Swordsman'
                choice_prev = choice_num
                choice_num = 0
                wait = 0
                toggle = 1
                self.snd['menu']['select'].play()
            elif pressed(pg.K_2):
                self.px['cls'] = 'Spearman'
                choice_prev = choice_num
                choice_num = 1
                wait = 0
                toggle = 1
                self.snd['menu']['select'].play()
            elif pressed(pg.K_3):
                self.px['cls'] = 'Mage'
                choice_prev = choice_num
                choice_num = 2
                wait = 0
                toggle = 1
                self.snd['menu']['select'].play()
            elif pressed(pg.K_4):
                self.px['cls'] = 'Archer'
                choice_prev = choice_num
                choice_num = 3
                wait = 0
                toggle = 1
                self.snd['menu']['select'].play()
            elif pressed(pg.K_5):
                self.px['cls'] = 'Cavalry'
                choice_prev = choice_num
                choice_num = 4
                wait = 0
                toggle = 1
                self.snd['menu']['select'].play()
            elif pressed(pg.K_SPACE) or pressed(pg.K_RETURN):
                self.page += 1
                self.pressed_key = None 
                self.snd['menu']['confirm'].play()
                break
            elif pressed(pg.K_ESCAPE):
                #self.page -= 1
                self.pressed_key = None
                self.snd['menu']['cancel'].play()
                break
            elif pressed(pg.K_h):
                self.toggle_help_display()
            
            self.pressed_key = None 
            
            #draw background, weapons, and text
            self.screen.fill((0, 0, 0))
            self.screen.blit(self.background, (0, 0))
            txt_x = (800 - title_txt.get_width()) / 2
            self.screen.blit(title_txt, (txt_x, 60))
            for img, pos, txt in zip(cls_img1, positions, txt_img):
                self.screen.blit(self.wood1, pos)
                self.screen.blit(img, pos)
                txt_x = (96 - txt.get_width()) / 2 + pos[0]
                txt_y = pos[1] + 100
                self.screen.blit(txt, (txt_x, txt_y))
            
            # now that I'm redrawing everything every frame, this is no longer necessary
            # self.screen.blit(self.wood1, positions[choice_prev])
            # self.screen.blit(cls_img1[choice_prev], positions[choice_prev])
            self.screen.blit(self.wood2, positions[choice_num])
            if wait:
                wait -= 1
            else:
                if toggle:
                    current_img = cls_img1[choice_num]
                    toggle = 0
                else:
                    current_img = cls_img2[choice_num]
                    toggle = 1
                wait = 4            
            self.screen.blit(current_img, positions[choice_num])
            
            self.screen.blit(self.help['menu'], self.help_pos)
            
    def select_weapons(self):
        ''' the player selects the weapon for their leader character'''
        
        #grab available weapons based on class
        cls = self.px['cls']
        wpns = self.wpns[cls]
        handed = self.handed[cls]
        #populate weapon image list and positions list based on wpns list
        positions = []
        wpn_img1 = []
        wpn_img2 = []
        txt_img = []
        y_pos = 170
        this_font = pygame.font.Font(os.path.join('.', 'fonts', 'Trinigan.ttf'), 18)
        color = (0, 0, 0)
        fourth = True
        for section in wpns:
            x_pos = 160
            for weapon in section:
                filename1 = os.path.join('.', 'graphics', 'creationgui', weapon.lower() + '1.png')
                filename2 = os.path.join('.', 'graphics', 'creationgui', weapon.lower() + '2.png')
                wpn_img1.append(pygame.image.load(filename1).convert_alpha())
                wpn_img2.append(pygame.image.load(filename2).convert_alpha())
                txt_img.append(this_font.render(weapon, 1, color))
                positions.append((x_pos, y_pos))
                x_pos += 140
            #if there arent 4 items in positions when it finishes the first loop, 
            if len(positions) < 4:
                positions.append(positions[-1])
                wpn_img1.append(wpn_img1[-1])
                wpn_img2.append(wpn_img2[-1])
                txt_img.append(txt_img[-1])
                fourth = False
            y_pos += 200
        #special image for locking out the bottom row
        filename1 = os.path.join('.', 'graphics', 'creationgui', 'handed1.png')
        filename2 = os.path.join('.', 'graphics', 'creationgui', 'handed2.png')
        wpn_img1.append(pygame.image.load(filename1).convert_alpha())
        wpn_img2.append(pygame.image.load(filename2).convert_alpha())
        
        #rendering fonts images for drawing in the loop
        heavy_txt = this_font.render('(heavy)', 1, color)        
        this_font = pygame.font.Font(os.path.join('.', 'fonts', 'Trinigan.ttf'), 64)  
        title_txt = this_font.render(self.menu_player + 'Select Your Weapons', 1, color)
        this_font = pygame.font.Font(os.path.join('.', 'fonts', 'Trinigan.ttf'), 24)  
        primary_txt = this_font.render('Primary:', 1, color)
        secondary_txt = this_font.render('Secondary:', 1, color)

        handed_confirm = pygame.image.load(os.path.join('.', 'graphics', 'creationgui', 'confirmhandedbg.png')).convert_alpha()
        this_font = pygame.font.Font(os.path.join('.', 'fonts', 'Trinigan.ttf'), 24)  
        confirm_txt = this_font.render('No secondary due to heavy primary. Confirm?', 1, color)
        txt_x = (400 - confirm_txt.get_width()) / 2 
        txt_y = (60 - confirm_txt.get_height()) / 2
        handed_confirm.blit(confirm_txt, (txt_x, txt_y))

        def pressed(key):
            return self.pressed_key == key
        
        #initializing variables for the event processing loop
        phase = 1  
        pw_num = 0
        prev_wpn = 1
        wait = 0
        toggle = 1
        current_img = wpn_img1[0]
        if 0 in handed:
            is_handed = True
            sw_num = 8
        else:
            is_handed = False
            sw_num = 0
         
        #event processing loop
        while True:
            pygame.display.flip()
            self.clock.tick(15)
            
            keys = pygame.key.get_pressed()
            for event in pygame.event.get():
                if event.type == pg.KEYDOWN:
                    self.pressed_key = event.key
        
            if pressed(pg.K_1):
                self.snd['menu']['select'].play()
                wait = 0
                toggle = 1
                if phase == 1:
                    prev_wpn = pw_num
                    pw_num = 0
                else:
                    if not is_handed:
                        prev_wpn = sw_num
                        sw_num = 4
            elif pressed(pg.K_2):
                self.snd['menu']['select'].play()
                wait = 0
                toggle = 1
                if phase == 1:
                    prev_wpn = pw_num
                    pw_num = 1
                else:
                    if not is_handed:
                        prev_wpn = sw_num
                        sw_num = 5
            elif pressed(pg.K_3):
                self.snd['menu']['select'].play()
                wait = 0
                toggle = 1
                if phase == 1:
                    prev_wpn = pw_num
                    pw_num = 2
                else:
                    if not is_handed:
                        prev_wpn = sw_num
                        sw_num = 6
            elif pressed(pg.K_4):
                self.snd['menu']['select'].play()
                wait = 0
                toggle = 1
                if phase == 1:
                    prev_wpn = pw_num
                    if fourth:
                        pw_num = 3
                    else:
                        pw_num = 2
                else:
                    if not is_handed:
                        prev_wpn = sw_num
                        sw_num = 7
            elif pressed(pg.K_SPACE) or pressed(pg.K_RETURN):
                self.snd['menu']['confirm'].play()
                wait = 0
                toggle = 1
                if phase == 1:
                    phase = 2
                    self.px['pw'] = wpns[0][pw_num]
                    prev_wpn = None
                    self.screen.blit(self.wood2, positions[pw_num])
                    self.screen.blit(wpn_img1[pw_num], positions[pw_num])
                    self.pressed_key = None 
                else:       
                    self.page += 1
                    if sw_num < 8:
                        self.px['sw'] = wpns[1][sw_num - 4]
                    else: 
                        self.px['sw'] = None
                    self.pressed_key = None 
                    break
            elif pressed(pg.K_ESCAPE) or pressed(pg.K_BACKSPACE):
                self.snd['menu']['cancel'].play()
                wait = 0
                toggle = 1
                if phase == 2:
                    phase = 1
                    abs_y = 150
                    self.pressed_key = None
                else:
                    self.page -= 1
                    self.pressed_key = None
                    break
            elif pressed(pg.K_h):
                self.toggle_help_display()
            self.pressed_key = None                               
                
            #draw background, weapons, and text
            self.screen.fill((0, 0, 0))
            self.screen.blit(self.background, (0, 0))
            for img, pos, txt in zip(wpn_img1, positions, txt_img):
                self.screen.blit(self.wood1, pos)
                self.screen.blit(img, pos)
                txt_x = (96 - txt.get_width()) / 2 + pos[0]
                txt_y = pos[1] + 100
                self.screen.blit(txt, (txt_x, txt_y))
            #(heavy), 'primary' and 'secondary', title text
            for i in handed:
                pos = positions[i]            
                txt_x = (96 - txt.get_width()) / 2 + pos[0]
                txt_y = pos[1] + 125
                self.screen.blit(heavy_txt, (txt_x, txt_y))
            txt_x = (800 - title_txt.get_width()) / 2
            self.screen.blit(title_txt, (txt_x, 60))
            txt_x = (160 - (primary_txt.get_width() / 2) ) - 80
            self.screen.blit(primary_txt, (txt_x, 200))
            txt_x = (160 - (secondary_txt.get_width() / 2) ) - 80
            self.screen.blit(secondary_txt, (txt_x, 400))
            
            #checking for handedness, drawing as necessary, setting wpn_num
            if phase == 1:
                if pw_num in handed:
                    sw_num = 8
                    is_handed = True
                else:
                    sw_num = 4
                    is_handed = False
                wpn_num = pw_num
            else:
                wpn_num = sw_num
                
            #disable secondary weapons if primary is 2-handed
            for i in xrange(4, 8):
                h_pos = (positions[i][0] - 5, positions[i][1] - 5)
                if is_handed:
                    self.screen.blit(wpn_img1[8], h_pos)
                    if phase == 2:
                        x_pos = (800 - handed_confirm.get_width()) / 2 + 20
                        self.screen.blit(handed_confirm, (x_pos, 385))
                else:
                    self.screen.blit(self.wood1, positions[i])
                    self.screen.blit(wpn_img1[i], positions[i])
            
            #animation frame changes every 4th screen frame to slow it down
            if wait:
                wait -= 1
            else:
                if toggle:
                    current_img = wpn_img1[wpn_num]
                    toggle = 0
                else:
                    current_img = wpn_img2[wpn_num]
                    toggle = 1
                wait = 4               
            #draw: restore previous weapon, draw current weapon
            if phase == 2:
                self.screen.blit(self.wood2, positions[pw_num])
                self.screen.blit(wpn_img1[pw_num], positions[pw_num])
            if wpn_num < 8:
                self.screen.blit(self.wood2, positions[wpn_num])                
                self.screen.blit(current_img, positions[wpn_num])
            else:
                pass # some confirmation that they will forgo secondary wpn
            
            
            self.screen.blit(self.help['menu'], self.help_pos)
    
    def select_style(self):
        ''' The player selects from 4 leadership styles. 
        this affects roster options and team stat bonus'''
        keys = pygame.key.get_pressed()
        cls = self.px['cls']
        self.px['style'] = 'Power'
        
        positions = [(240, 170), (460, 170), (240, 350), (460, 350)]
        styles = ['Power', 'Strategy', 'Efficiency', 'Fortune']
        this_font = pygame.font.Font(os.path.join('.', 'fonts', 'Trinigan.ttf'), 24)
        color = (0, 0, 0)
        ldr_img1 = []
        ldr_img2 = []
        txt_img = []
        for ldr in styles:
            filename1 = os.path.join('.', 'graphics', 'creationgui', ldr.lower() + '1.png')
            filename2 = os.path.join('.', 'graphics', 'creationgui', ldr.lower() + '2.png')
            ldr_img1.append(pygame.image.load(filename1).convert_alpha())
            ldr_img2.append(pygame.image.load(filename2).convert_alpha())
            txt_img.append(this_font.render(ldr, 1, color))

        #render title for drawing later
        this_font = pygame.font.Font(os.path.join('.', 'fonts', 'Trinigan.ttf'), 64)  
        title_txt = this_font.render(self.menu_player + 'Select Your Leadership Style', 1, color)
            
        def pressed(key):
            return self.pressed_key == key

        wait = 4
        toggle = 0
        ldr_num = 0
        prev_ldr = 1
        current_img = ldr_img1[0]
        while True:
            pygame.display.flip()
            self.clock.tick(15)
            
            for event in pygame.event.get():
                if event.type == pg.KEYDOWN:# and flag == 0:
                    self.pressed_key = event.key
        
            if pressed(pg.K_1):
                self.snd['menu']['select'].play()
                self.px['style'] = 'Power'
                prev_ldr = ldr_num
                ldr_num = 0
                wait = 0
            elif pressed(pg.K_2):
                self.snd['menu']['select'].play()
                self.px['style'] = 'Strategy'
                prev_ldr = ldr_num
                ldr_num = 1
                wait = 0
            elif pressed(pg.K_3):
                self.snd['menu']['select'].play()
                self.px['style'] = 'Efficiency'
                prev_ldr = ldr_num
                ldr_num = 2
                wait = 0
            elif pressed(pg.K_4):
                self.snd['menu']['select'].play()
                self.px['style'] = 'Fortune'
                prev_ldr = ldr_num
                ldr_num = 3
                wait = 0
            elif pressed(pg.K_SPACE) or pressed(pg.K_RETURN):
                self.snd['menu']['confirm'].play()
                self.page += 1
                self.pressed_key = None
                break
            elif pressed(pg.K_ESCAPE) or pressed(pg.K_BACKSPACE):
                self.snd['menu']['cancel'].play()
                self.page -= 1
                self.pressed_key = None
                break
            elif pressed(pg.K_h):
                self.toggle_help_display()
            
            self.pressed_key = None 
            
            if wait:
                wait -= 1
            else:
                if toggle:
                    current_img = ldr_img1[ldr_num]
                    toggle = 0
                else:
                    current_img = ldr_img2[ldr_num]
                    toggle = 1
                wait = 4
            #draw background, wood, ldr images, ldr text
            self.screen.fill((0, 0, 0))
            self.screen.blit(self.background, (0, 0))
            for img, pos, txt in zip(ldr_img1, positions, txt_img):
                self.screen.blit(self.wood1, pos)
                self.screen.blit(img, pos)
                txt_x = (96 - txt.get_width()) / 2 + pos[0]
                txt_y = pos[1] + 100
                self.screen.blit(txt, (txt_x, txt_y))
            #draw page title
            txt_x = (800 - title_txt.get_width()) / 2
            self.screen.blit(title_txt, (txt_x, 60))
            
            self.screen.blit(self.wood2, positions[ldr_num])       
            self.screen.blit(current_img, positions[ldr_num])
            
            self.screen.blit(self.help['menu'], self.help_pos)
    
    def select_team(self, player = 1):
        self.wood1sm = pygame.image.load(os.path.join('.', 'graphics', 'creationgui', 'wood1sm.png')).convert()
        self.wood2sm = pygame.image.load(os.path.join('.', 'graphics', 'creationgui', 'wood2sm.png')).convert()
        #grab available roster based on leadership style from a file
        f = open(os.path.join('.', 'configs', self.px['style'].lower() + 'team.txt'))
        roster = []
        for line in f:
            roster.append(line.split())
        #build image lists and do initial draw
        self.screen.blit(self.background, (0, 0))
        positions = []
        cls_img1 = []
        cls_img2 = []
        txt_img = []
        y_pos = 135
        this_text = pygame.font.Font(os.path.join('.', 'fonts', 'Trinigan.ttf'), 14)  
        color = (0, 0, 0)
        for slot in roster:
            x_pos = 190
            pos_l = []
            slot_imgs1 = []
            slot_imgs2 = []
            cls_txts = []
            for cls in slot:
                filename1 = os.path.join('.', 'graphics', 'creationgui', cls.lower() + '1sm.png')
                filename2 = os.path.join('.', 'graphics', 'creationgui', cls.lower() + '2sm.png')
                slot_imgs1.append(pygame.image.load(filename1).convert_alpha())
                slot_imgs2.append(pygame.image.load(filename2).convert_alpha())
                cls_txts.append(this_text.render(cls, 1, color))
                pos_l.append((x_pos, y_pos))
                x_pos += 100
            cls_img1.append(slot_imgs1)
            cls_img2.append(slot_imgs2)
            txt_img.append(cls_txts)
            positions.append(pos_l)
            y_pos += 100
        
         
        #render txt for later
        this_font = pygame.font.Font(os.path.join('.', 'fonts', 'Trinigan.ttf'), 54)  
        title_txt = this_font.render(self.menu_player + 'Select Your Team', 1, color)
         
        #render slot number txts
        this_font = pygame.font.Font(os.path.join('.', 'fonts', 'Trinigan.ttf'), 20)  
        slot_txts = []
        slot_positions = []
        for i in xrange(4):
            slot_txt = 'Roster slot ' + str(i + 1) + ':'
            slot_txts.append(this_font.render(slot_txt, 1, color))
            txt_x = (160 - (slot_txts[i].get_width() / 2) ) - 60
            txt_y = 150 + 100 * i
            slot_positions.append((txt_x, txt_y))
            

            
        
        pygame.display.flip()
        cls = 0
        
        def pressed(key):
            return self.pressed_key == key            
        
        prev_phase = None
        prev_cls = 1
        cls_num = 0
        phase = 0
        wait = 0
        toggle = 1
        team = []
        while True:
            keys = pygame.key.get_pressed()
            pygame.display.flip()
            self.clock.tick(15)
        
            for event in pygame.event.get():
                if event.type == pg.KEYDOWN:
                    self.pressed_key = event.key
        
            if pressed(pg.K_1):
                self.snd['menu']['select'].play()
                wait = 0
                toggle = 1
                if phase <= 3:
                    prev_cls = cls_num
                    cls_num = 0
            elif pressed(pg.K_2) and len(roster[phase]) >= 2:
                self.snd['menu']['select'].play()
                wait = 0
                toggle = 1
                if phase <= 3:
                    prev_cls = cls_num
                    cls_num = 1
            elif pressed(pg.K_3) and len(roster[phase]) >= 3:
                self.snd['menu']['select'].play()
                wait = 0
                toggle = 1
                if phase <= 3:
                    prev_cls = cls_num
                    cls_num = 2
            elif pressed(pg.K_4) and len(roster[phase]) >= 4:
                self.snd['menu']['select'].play()
                wait = 0
                toggle = 1
                if phase <= 3:
                    prev_cls = cls_num
                    cls_num = 3
            elif pressed(pg.K_5) and len(roster[phase]) >= 5:
                self.snd['menu']['select'].play()
                wait = 0
                toggle = 1
                if phase <= 3:
                    prev_cls = cls_num
                    cls_num = 4
            elif pressed(pg.K_SPACE) or pressed(pg.K_RETURN):
                self.snd['menu']['confirm'].play()
                wait = 0
                toggle = 1
                team.append(cls_num)
                if phase < 3:
                    prev_phase = None
                    self.screen.blit(self.wood2sm, positions[phase][cls_num])
                    self.screen.blit(cls_img1[phase][cls_num], positions[phase][cls_num])
                    cls_num = 0
                    prev_cls = 1
                    phase += 1
                    self.pressed_key = None 
                else:       
                    self.page += 1
                    self.pressed_key = None 
                    break
            elif pressed(pg.K_ESCAPE) or pressed(pg.K_BACKSPACE):
                self.snd['menu']['cancel'].play()
                wait = 0
                toggle = 1
                if phase > 0:
                    prev_phase = phase
                    prev_cls = cls_num
                    cls_num = team.pop()
                    phase -= 1
                    self.pressed_key = None
                else:
                    self.page -= 1
                    self.pressed_key = None
                    break
            elif pressed(pg.K_h):
                self.toggle_help_display()
            
            self.pressed_key = None 
            
            #redraw everything
            self.screen.fill((0, 0, 0))
            self.screen.blit(self.background, (0, 0))
            txt_x = (800 - title_txt.get_width()) / 2
            self.screen.blit(title_txt, (txt_x, 60))
            for slot_imgs1, cls_txts, pos_l in zip(cls_img1, txt_img, positions):
                for cls_img, cls_txt, pos in zip(slot_imgs1, cls_txts, pos_l):
                    self.screen.blit(self.wood1sm, pos)
                    self.screen.blit(cls_img, pos)
                    txt_x = (64 - cls_txt.get_width()) / 2 + pos[0]
                    txt_y = pos[1] + 72
                    self.screen.blit(cls_txt, (txt_x, txt_y))
            #drawing row text ('Roster Slot #:')
            for slot_txt, pos in zip(slot_txts, slot_positions):
                self.screen.blit(slot_txt, pos)
            
            #redraw the depressed wood button for each already existing choice
            for i, j in enumerate(team):
                self.screen.blit(self.wood2sm, positions[i][j])
                self.screen.blit(cls_img1[i][j], positions[i][j])
            
            if wait:
                wait -= 1
            else:
                if toggle:
                    current_img = cls_img1[phase][cls_num]
                    toggle = 0
                else:
                    current_img = cls_img2[phase][cls_num]
                    toggle = 1
                wait = 4            
                
            self.screen.blit(self.wood2sm, positions[phase][cls_num])
            self.screen.blit(current_img, positions[phase][cls_num])
            
            self.screen.blit(self.help['menu'], self.help_pos)
            
        i = 0
        self.px['team'] = []
        for cls_num in team:
            this_cls = roster[i][cls_num]
            self.px['team'].append(this_cls)
            i += 1

    def stat_main(self):
        pygame.key.set_repeat()
        ap1 = Spearman('a')
        self.sprites.add(ap1)
        ap1.p_weapon = Javelin()
        ap2 = Swordsman('a')
        ap2.p_weapon = Broadsword()
        bp1 = Spearman('b')
        bp1.p_weapon = Javelin()
        self.team_a.append(ap1)
        self.team_a.append(ap2)
        self.team_b.append(bp1)
        
        
        self.set_team_pos(self.team_a)
        self.set_team_pos(self.team_b, 'b')
        
        self.screen.blit(self.background, (0,0))
        pygame.display.flip()
        
        a_panel = StatPanel(self.team_a)
        
        stat_image = a_panel.update()
        
        self.screen.blit(stat_image, (self.screen.get_width() - 96, 0)) 
        pygame.display.flip()
            
    def toggle_help_display(self):
        if self.help_visible:
            for page in self.help.values():
                page.set_alpha(0)
            self.help_visible = False
        else:
            for page in self.help.values():
                page.set_alpha(255)
            self.help_visible = True
            
        
        
#player test main()
def player_main():
    player = Swordsman()
    which = ''
    while which <> 'quit':
        which = raw_input('what stat would you like to know?')
        try:
            print player.stats[which]
        except KeyError:
            print "stat doesnt exist!"
 
#highlight test main() 
def high_main():
    class TWeapon(object): #temp weapon class for testing
        def __init__(self):
            self.d_range = 1
            self.i_range = None
    
    clock = pygame.time.Clock()
    pygame.init()
    pygame.event.set_blocked(pg.MOUSEMOTION)
    pygame.display.set_mode((640, 320))
    screen = pygame.display.get_surface()
    my_map = Map()
    image, overlays = my_map.render()
    screen.blit(image, (0, 0))
    pygame.display.flip()
    clock.tick(1)
    guy = Swordsman()
    guy.x, guy.y = 0, 0
    guy.stats['mvt'] = int(input('what is the players mvt stat?'))
    primary = TWeapon()
    #secondary = TWeapon()
    guy.p_weapon = primary
    primary.d_range = int(input('what is the range of the weapon?'))
    valid_moves, valid_coords = my_map.get_valid_moves(guy)
    #print valid_coords
    valid_atk = my_map.get_valid_atk(guy, valid_coords)
    my_map.highlight_valid_squares(valid_moves, valid_atk)
    image, overlays = my_map.render()
    screen.blit(image, (0, 0))
    pygame.display.flip()
    for i in xrange(45):
        clock.tick(15)
      
#main() asks what to test and runs relevant test method
def main():
    choice = '2'
    while choice != '5':
        # print '1 - test map selection'
        # print '2 - test full game'
        # print '3 - run Game().main()'
        # print '4 - test Victory Display'
        # print '5 - quit'
        # choice = raw_input('which option?')
        if choice == '1':
            this = Game()
            this.background = pygame.image.load(os.path.join('.', 'graphics', 'creationgui', 'bg.png')).convert_alpha()
            this.choose_map()
        elif choice == '2':
            the_game = Game()
            the_game.intro()
            the_game.start_2p()
        elif choice == '3':
            Game().main()
        elif choice == '4':
            Game().show_victory_screen('a', 1)
            Game().show_victory_screen('b', (5, 5))
        elif choice == '5':
            print 'quitting'
        else:
            print 'invalid choice'
    
            
if __name__ == "__main__":
    pygame.mixer.pre_init(22050, -16, 2, 1024)
    pygame.init()
    pygame.event.set_blocked(pg.MOUSEMOTION)
    pygame.display.set_mode((800, 600))
    pygame.display.set_caption('Bright Flame Tactics by gr3yh47')
    main()
    quit()
    