Пример #1
0
 def move_scient(self, src, dest):
     Battlefield.move_scient(self, src, dest)
     xpos, ypos = dest
     self.grid[xpos][ypos].contents.rect.topleft = \
     self.grid[xpos][ypos].rect.x, self.grid[xpos][ypos].rect.y
     self.set_tile_color(src, grey)
     return True #need this for logging.
Пример #2
0
 def __init__(self,  position, grid, tilesize, tiles):
     #NOTE: This object has Player information that a battlefield does not have.
     #pane_area = (((tilesize* tiles[0]) + tilesize/2), ((tilesize * tiles[1]) +4))
     pane_area = ((34 * (tiles[0] + 1) + 5), (30 * tiles[1]) + 5)
     Battlefield.__init__(self)
     
     Pane.__init__(self, pane_area, title=None)
     self.bgcolor = black
     self.rect.x, self.rect.y = position
     
     self.grid = grid
     self.contentimgs = pygame.sprite.RenderUpdates()
     self.defender = battle.Player()
     self.attacker = battle.Player()
     self.defender.squads = [self.trans_squad(yaml_store.load('yaml/pt_0.yaml'))]
     self.attacker.squads = [self.trans_squad(yaml_store.load('yaml/pt_1.yaml'))]
     
     self.defsquad = self.defender.squads[0]
     self.atksquad = self.attacker.squads[0]
     
     self.defender.name = 'Defender'
     self.defsquad.num  = '1'
     
     self.attacker.name = 'Attacker'
     self.atksquad.num  = '2'
             
     self.squads = (self.defsquad, self.atksquad)
     self.units = self.get_units()
     for u in self.units:
         u.draw_text()
     self.get_contents_image()
Пример #3
0
 def place_nescient(self, nescient, dest):
     nsci = nescient 
     Battlefield.place_nescient(self, nsci, dest)
     r,s,hexh,rech,size = nsci.hexparams
     nsci.image.fill(black)
     for part in nsci.body:
         if part != None:
             xpos, ypos = nsci.body[part].location
             p_i = nsci.rects[part]
             if ypos&1:
                 p_i.topleft = [((xpos * p_i.width) + .5*p_i.width), (ypos*(hexh + s))]
             else:
                 p_i.topleft = [(xpos * p_i.width), (ypos*(hexh + s))]
             nsci.image.blit(nsci.hex, p_i)
     self.contentimgs.add(nsci)
Пример #4
0
    def __init__(self, grid=Grid(), defender=None, attacker=None):
        self.grid = grid
        self.defender = defender
        self.attacker = attacker
        #player/battlefield logic for testing
        if self.defender == None:
            self.defender = Player('Defender', squads=[rand_squad()])
        if self.attacker == None:
            self.attacker = Player('Attacker', squads=[rand_squad()])
        self.battlefield = Battlefield(grid, self.defender.squads[0],
                                       self.attacker.squads[0])

        self.state = State()
        self.players = (self.defender, self.attacker)
        self.map = self.unit_map()
        self.winner = None
        self.units = self.map_unit()
        self.log = Log(self.players, self.units, self.battlefield.grid)
        self.log['owners'] = self.log.get_owners()
        self.state['old_defsquad_hp'] = self.battlefield.defsquad.hp()
        self.whose_turn = self.defender
Пример #5
0
 def __init__(self, grid=Grid(), defender=None, attacker=None):
     self.grid = grid
     self.defender = defender
     self.attacker = attacker
     #player/battlefield logic for testing
     if self.defender == None:
         self.defender = Player('Defender', squads=[rand_squad()])
     if self.attacker == None:
         self.attacker = Player('Attacker', squads=[rand_squad()])
     self.battlefield = Battlefield(grid, self.defender.squads[0],
                                    self.attacker.squads[0])
     
     self.state = State()
     self.players = (self.defender, self.attacker)
     self.map = self.unit_map() 
     self.winner = None
     self.units = self.map_unit()
     self.log = Log(self.players, self.units, self.battlefield.grid)
     self.log['owners'] = self.log.get_owners()
     self.state['old_defsquad_hp'] = self.battlefield.defsquad.hp()
     self.whose_turn = self.defender
Пример #6
0
class Game(object):
    """Almost-state-machine that maintains game state."""
    def __init__(self, grid=Grid(), defender=None, attacker=None):
        self.grid = grid
        self.defender = defender
        self.attacker = attacker
        #player/battlefield logic for testing
        if self.defender == None:
            self.defender = Player('Defender', squads=[rand_squad()])
        if self.attacker == None:
            self.attacker = Player('Attacker', squads=[rand_squad()])
        self.battlefield = Battlefield(grid, self.defender.squads[0],
                                       self.attacker.squads[0])
        
        self.state = State()
        self.players = (self.defender, self.attacker)
        self.map = self.unit_map() 
        self.winner = None
        self.units = self.map_unit()
        self.log = Log(self.players, self.units, self.battlefield.grid)
        self.log['owners'] = self.log.get_owners()
        self.state['old_defsquad_hp'] = self.battlefield.defsquad.hp()
        self.whose_turn = self.defender
    
    def unit_map(self):
        """mapping of unit ids to objects, used for serialization."""
        mapping = PersistentMapping()
        for unit in self.battlefield.units: mapping[unit] = id(unit)
        return mapping
    
    def map_unit(self):
        units = PersistentMapping()
        for (k,v) in self.map.items(): units[v] = k
        return units
    
    def map_locs(self):
        """maps unit name unto locations, only returns live units"""
        locs = PersistentMapping()
        for unit in self.map:
            loc = unit.location
            if loc[0] >= 0:
                locs[self.map[unit]] = loc
        return locs
    
    def HPs(self):
        """Hit points by unit."""
        HPs =PersistentMapping()
        for unit in self.map:
            hp = unit.hp
            if hp > 0:
                HPs[self.map[unit]] = hp
        return HPs
        
    def update_unit_info(self):
        """returns HPs, Locs."""
        HPs   = PersistentMapping()
        locs  = PersistentMapping()
        
        for unit in self.map:
            num = self.map[unit]
            loc = unit.location
            if loc[0] >= 0:
                locs[num] = loc
                HPs[num] = unit.hp
        
        return HPs, locs
        
    def map_queue(self):
        """apply unit mapping to units in queue."""
        old = self.battlefield.get_dmg_queue()
        if isinstance(old, dict):
            new = PersistentMapping()
            for key in old.keys():
                new[str(id(key))] = old[key]
            return new
        else:
            return None
    
    def map_result(self, result):
        if result != None:
            for t in result:
                if isinstance(t[0], Unit):
                    t[0] = id(t[0])
            return result
    
    def map_action(self, action):
        """replaces unit refrences to referencing their hash."""
        new = Action(**action)
        if new['unit'] != None:
            new['unit'] = id(new['unit'])
        else:
            new['unit'] = None
            #raise TypeError("Acting unit cannont be 'NoneType'")
        return new
    
    def last_message(self):
        text = self.log['messages'][-1]['result']
        if text != None:
            return self.log['messages'][-1]['result']
        else:
            return ["There was no message."]
    
    def process_action(self, action):
        action['when'] = now()
        action['num']  = num = self.state['num']
        if action['type'] == 'timed_out':
            text = [["failed to act."]]
        elif action['type'] == 'pass':
            text = [["Action Passed."]]
        elif action['type'] == 'move': #TODO fix move in hex_battlefield.
            text = self.battlefield.move_scient(action['unit'].location,
                                              action['target'])
            if text:
                text = [[id(action['unit']), action['target']]]
        
        elif action['type'] == 'attack':
            text = self.battlefield.attack(action['unit'], action['target'])
        else:
            raise Exception("Action is of unknown type")
        
        self.log['actions'].append(self.map_action(action))
        self.log['messages'].append(Message(num, self.map_result(text)))
        
        if num % 4 == 0: #explain please.
            self.apply_queued()
        else:
            self.state.check(self)
        
        #switches whose_turn.
        if self.whose_turn == self.defender:
            self.whose_turn = self.attacker
        else:
            self.whose_turn = self.defender
        if num % 4 == 0:
            return {'command': self.log['actions'][-1], 'response': self.log['messages'][-1],
                    'applied': self.log['applied'][-1]}
        else:
            return {'command': self.log['actions'][-1], 'response': self.log['messages'][-1]}
            
    
    def apply_queued(self):
        """queued damage is applied to units from this state"""
        text = self.battlefield.apply_queued()
        self.log['applied'].append(Message(self.state['num'], self.map_result(text)))
        self.state.check(self)
    
    def last_state(self):
        """Returns location and HP of all units. As well as proximity to winning conditions."""
        try:
            return self.log['states'][-1]
        except:
            return None
    
    def initial_state(self):
        """Returns stuff to create the client side of the game"""
        return Initial_state(self.log)
    
    def end(self, condition):
        """game over state, handles log closing, writes change list for world"""
        log = self.log
        self.state['game_over'] = True
        log['states'].append(self.state)
        log.close(self.winner, condition)
        #make change list
        victors = PersistentList()
        prisoners = PersistentList()

        #split survivors into victors and prisoners
        for unit in log['states'][-1]['HPs'].keys():
            if log['winner'].name == log['owners'][unit]:
                victors.append(unit)
            else:
                prisoners.append(unit)
        #calculate awards
        awards    = PersistentMapping() #should be a stone.
        self.log['change_list'] = Battle_changes(victors, prisoners, awards)
        raise Exception("Game Over")
Пример #7
0
class Game(object):
    """Almost-state-machine that maintains game state."""
    def __init__(self, grid=Grid(), defender=None, attacker=None):
        self.grid = grid
        self.defender = defender
        self.attacker = attacker
        #player/battlefield logic for testing
        if self.defender == None:
            self.defender = Player('Defender', squads=[rand_squad()])
        if self.attacker == None:
            self.attacker = Player('Attacker', squads=[rand_squad()])
        self.battlefield = Battlefield(grid, self.defender.squads[0],
                                       self.attacker.squads[0])

        self.state = State()
        self.players = (self.defender, self.attacker)
        self.map = self.unit_map()
        self.winner = None
        self.units = self.map_unit()
        self.log = Log(self.players, self.units, self.battlefield.grid)
        self.log['owners'] = self.log.get_owners()
        self.state['old_defsquad_hp'] = self.battlefield.defsquad.hp()
        self.whose_turn = self.defender

    def unit_map(self):
        """mapping of unit ids to objects, used for serialization."""
        mapping = PersistentMapping()
        for unit in self.battlefield.units:
            mapping[unit] = id(unit)
        return mapping

    def map_unit(self):
        units = PersistentMapping()
        for (k, v) in self.map.items():
            units[v] = k
        return units

    def map_locs(self):
        """maps unit name unto locations, only returns live units"""
        locs = PersistentMapping()
        for unit in self.map:
            loc = unit.location
            if loc[0] >= 0:
                locs[self.map[unit]] = loc
        return locs

    def HPs(self):
        """Hit points by unit."""
        HPs = PersistentMapping()
        for unit in self.map:
            hp = unit.hp
            if hp > 0:
                HPs[self.map[unit]] = hp
        return HPs

    def update_unit_info(self):
        """returns HPs, Locs."""
        HPs = PersistentMapping()
        locs = PersistentMapping()

        for unit in self.map:
            num = self.map[unit]
            loc = unit.location
            if loc[0] >= 0:
                locs[num] = loc
                HPs[num] = unit.hp

        return HPs, locs

    def map_queue(self):
        """apply unit mapping to units in queue."""
        old = self.battlefield.get_dmg_queue()
        if isinstance(old, dict):
            new = PersistentMapping()
            for key in old.keys():
                new[str(id(key))] = old[key]
            return new
        else:
            return None

    def map_result(self, result):
        if result != None:
            for t in result:
                if isinstance(t[0], Unit):
                    t[0] = id(t[0])
            return result

    def map_action(self, action):
        """replaces unit refrences to referencing their hash."""
        new = Action(**action)
        if new['unit'] != None:
            new['unit'] = id(new['unit'])
        else:
            new['unit'] = None
            #raise TypeError("Acting unit cannont be 'NoneType'")
        return new

    def last_message(self):
        text = self.log['messages'][-1]['result']
        if text != None:
            return self.log['messages'][-1]['result']
        else:
            return ["There was no message."]

    def process_action(self, action):
        action['when'] = now()
        action['num'] = num = self.state['num']
        if action['type'] == 'timed_out':
            text = [["failed to act."]]
        elif action['type'] == 'pass':
            text = [["Action Passed."]]
        elif action['type'] == 'move':  #TODO fix move in hex_battlefield.
            text = self.battlefield.move_scient(action['unit'].location,
                                                action['target'])
            if text:
                text = [[id(action['unit']), action['target']]]

        elif action['type'] == 'attack':
            text = self.battlefield.attack(action['unit'], action['target'])
        else:
            raise Exception("Action is of unknown type")

        self.log['actions'].append(self.map_action(action))
        self.log['messages'].append(Message(num, self.map_result(text)))

        if num % 4 == 0:  #explain please.
            self.apply_queued()
        else:
            self.state.check(self)

        #switches whose_turn.
        if self.whose_turn == self.defender:
            self.whose_turn = self.attacker
        else:
            self.whose_turn = self.defender
        if num % 4 == 0:
            return {
                'command': self.log['actions'][-1],
                'response': self.log['messages'][-1],
                'applied': self.log['applied'][-1]
            }
        else:
            return {
                'command': self.log['actions'][-1],
                'response': self.log['messages'][-1]
            }

    def apply_queued(self):
        """queued damage is applied to units from this state"""
        text = self.battlefield.apply_queued()
        self.log['applied'].append(
            Message(self.state['num'], self.map_result(text)))
        self.state.check(self)

    def last_state(self):
        """Returns location and HP of all units. As well as proximity to winning conditions."""
        try:
            return self.log['states'][-1]
        except:
            return None

    def initial_state(self):
        """Returns stuff to create the client side of the game"""
        return Initial_state(self.log)

    def end(self, condition):
        """game over state, handles log closing, writes change list for world"""
        log = self.log
        self.state['game_over'] = True
        log['states'].append(self.state)
        log.close(self.winner, condition)
        #make change list
        victors = PersistentList()
        prisoners = PersistentList()

        #split survivors into victors and prisoners
        for unit in log['states'][-1]['HPs'].keys():
            if log['winner'].name == log['owners'][unit]:
                victors.append(unit)
            else:
                prisoners.append(unit)
        #calculate awards
        awards = PersistentMapping()  #should be a stone.
        self.log['change_list'] = Battle_changes(victors, prisoners, awards)
        raise Exception("Game Over")
Пример #8
0
 def flush_units(self):
     Battlefield.flush_units(self)
     self.contentimgs.empty()
Пример #9
0
 def bury(self, unit):
     unit.remove(unit.groups())
     Battlefield.bury(self, unit)
Пример #10
0
 def place_object(self, unit, dest):
     Battlefield.place_object(self, unit, dest)
     """