def new_rogue_player(game_state):
    player = new_player(game_state)
    player.set_child(Health(20))
    player.set_child(DataPoint(DataTypes.CLASS, Class.ROGUE))
    return player def new_steam_cloud(game_state, density):
    cloud = Composite()
    set_cloud_components(game_state, cloud, density)
    cloud.graphic_char.color_fg = colors.WHITE
    cloud.set_child(CloudActor())
    cloud.set_child(DataPoint(DataTypes.CLONE_FUNCTION, new_steam_cloud))
    cloud.set_child(DataPoint(DataTypes.CLOUD_TYPE, CloudTypes.STEAM))
    return cloud class Dungeon(object):
    def __init__(self, game_state):
        self.level_count = 10
        self._dungeon_levels = [None]
        self.game_state = game_state

    def get_dungeon_level(self, depth):
        if depth >= self.level_count:
            self.game_state.has_won = True
            return None
        while len(self._dungeon_levels) <= depth:
            self._dungeon_levels.append(self._generate_dungeon_level(len(self._dungeon_levels)))
        return self._dungeon_levels[depth]

    def __getstate__(self):
        return dict(self.__dict__)

    def __setstate__(self, state):
        self.__dict__.update(state)

    def _generate_dungeon_level(self, depth):
        self.game_state.draw_loading_screen("Generating Dungeon...")
        size = 600 + depth * 20

        dungeon_level = time_it("dungeon_level_generation",
                                (lambda: dungeongenerator.generate_dungeon_floor(size, depth)))
        minimum_monsters = int(4 + depth * 1.2)
        monsters_to_spawn = random.randrange(minimum_monsters, minimum_monsters + 3)
        monsters = from_table_pick_n_items_for_depth(dungeon_table, monsters_to_spawn,
                                                     depth, self.game_state)
        print monsters
        for monster in monsters:
            sleep_chance = 0.25
            if sleep_chance > random.random():
                monster.set_child(TryPutToSleep())
            spawner.place_piece_on_random_walkable_tile(monster, dungeon_level)

        if depth == (len(self._dungeon_levels) - 1):
            jericho = monster.new_jericho(self.game_state)
            spawner.place_piece_on_random_walkable_tile(jericho, dungeon_level)

        place_items_in_dungeon(dungeon_level, self.game_state)

        #dungeon_level.print_statistics()

        dungeon_level.dungeon = self
        return dungeon_level class ReflexiveDungeon(object):
    def __init__(self, dungeon_level):
        self.dungeon_level = dungeon_level
        self.dungeon_level.dungeon = self

    def get_dungeon_level(self, depth):
        return self.dungeon_level def dungeon_level_from_file(file_name):
    lines = read_file(file_name)
    return dungeon_level_from_lines(lines) def teleport_monsters(player):
    positions = (player.dungeon_level.value.get_walkable_positions(player, player.position.value))
    random_positions = random.sample(positions, len(positions))
    max_tries = 30
    while len(player.vision.get_seen_entities()) > 0 and max_tries > 0:
        entity = player.vision.get_seen_entities()[0]
        for position in random_positions:
            teleport_successful = entity.mover.try_move(position)
            if teleport_successful:
                break
        max_tries -= 1 def new_player(game_state):
    """
    A composite component representing the player character.
    """
    player = Composite()
    player.set_child(DataPoint(DataTypes.GAME_STATE, game_state))

    player.set_child(DataPoint(DataTypes.RACE, Races.HUMAN))

    player.set_child(DataPoint(DataTypes.ENERGY, -gametime.single_turn))
    player.set_child(DataPoint(DataTypes.UNARMED_CRIT_CHANCE, 0.15))
    player.set_child(DataPoint(DataTypes.CRIT_CHANCE, 0.0))
    player.set_child(DataPoint(DataTypes.ACCURACY, 10))
    player.set_child(DataPoint(DataTypes.STRENGTH, 5))
    player.set_child(DataPoint(DataTypes.EVASION, 10))
    player.set_child(DataPoint(DataTypes.ARMOR, 4))
    player.set_child(DataPoint(DataTypes.STEALTH, 6))

    player.set_child(DataPoint(DataTypes.COUNTER_ATTACK_CHANCE, 0.0))
    player.set_child(DataPoint(DataTypes.DEFENCIVE_ATTACK_CHANCE, 0.0))
    player.set_child(DataPoint(DataTypes.OFFENCIVE_ATTACK_CHANCE, 0.0))

    player.set_child(Flag("is_player"))
    player.set_child(Flag("is_named"))
    player.set_child(StatusFlags([StatusFlags.CAN_OPEN_DOORS, StatusFlags.IS_ALIVE]))

    player.set_child(DataPoint(DataTypes.GAME_PIECE_TYPE, GamePieceTypes.ENTITY))

    player.set_child(DataPoint(DataTypes.MOVEMENT_SPEED, gametime.single_turn))
    player.set_child(DataPoint(DataTypes.MELEE_SPEED, gametime.single_turn))
    player.set_child(DataPoint(DataTypes.THROW_SPEED, gametime.double_turn))
    player.set_child(DataPoint(DataTypes.SHOOT_SPEED, gametime.single_turn))
    player.set_child(DataPoint(DataTypes.THROW_ITEM_SPEED, gametime.single_turn))
    player.set_child(DataPoint(DataTypes.CAST_SPEED, gametime.single_turn))

    player.set_child(DataPoint(DataTypes.SIGHT_RADIUS, constants.COMMON_SIGHT_RADIUS))
    player.set_child(DataPoint(DataTypes.FACTION, Factions.PLAYER))
    player.set_child(DataPoint(DataTypes.INTELLIGENCE, IntelligenceLevel.NORMAL))

    player.set_child(DungeonLevel())
    player.set_child(Position())

    player.set_child(Mover())
    player.set_child(PlayerStepper())

    player.set_child(UnarmedAttacker())
    player.set_child(ThrowRockAttacker())
    player.set_child(Dodger())
    player.set_child(ArmorChecker())
    player.set_child(ResistanceChecker())

    player.set_child(Description("CO", "The Brave"))
    player.set_child(GraphicChar(None, colors.WHITE, icon.GUNSLINGER_THIN))
    player.set_child(StatusDescriptionBar())
    player.set_child(CharPrinter())

    player.set_child(HealthModifier())
    player.set_child(BleedWhenDamaged())
    player.set_child(LoseParalyzeWhenDamaged())

    set_counter_attack(player)
    set_attack_enemy_i_step_next_to(player)
    set_attack_enemy_stepping_next_to_me(player)

    player.set_child(PlayerThrowStoneAction())

    player.set_child(DungeonMask())
    player.set_child(Vision())
    player.set_child(AwarenessChecker())

    player.set_child(MemoryMap())
    player.set_child(Inventory())
    player.set_child(InputActor())
    player.set_child(Path())
    player.set_child(Equipment())
    player.set_child(EffectQueue())
    player.set_child(PickUpItemAction())
    player.set_child(LeaveCorpseOnDeath())
    return player def new_rogue_player(game_state):
    player = new_player(game_state)
    player.set_child(Health(20))
    player.set_child(DataPoint(DataTypes.CLASS, Class.ROGUE))
    return player def save(game_state):
    game_state.draw_loading_screen("Saving...")
    save_file = open(get_save_file_name(), 'wb')
    time_it("save", lambda: pickle.dump(game_state, save_file, -1))
    save_file.close() def delete_save_file_of_game_state():
    file_name = get_save_file_name()
    if os.path.isfile(file_name):
        os.remove(file_name) def new_gun(game_state):
    gun = Composite()
    set_item_components(gun, game_state)
    set_ranged_weapon_components(gun)
    gun.set_child(RangeWeaponType(RangeWeaponType.GUN))
    gun.set_child(Description("Gun",
                              "This was once a fine weapon, \
                               but age has torn it real bad.\n\
                               The wooden handle is dry and gray, \
                               you see rust eating into the iron pipe."))
    gun.set_child(GraphicChar(None, colors.WHITE, icon.GUN))
    gun.set_child(DataPoint(DataTypes.WEAPON_RANGE, 15))
    gun.set_child(accuracy_item_stat(13))
    gun.set_child(damage_item_stat(5, 25))
    gun.set_child(BleedAttackEffect(1))

    gun.set_child(CritChanceBonusEffect(0.3))
    gun.set_child(crit_multiplier_item_stat(2.0))

    gun.set_child(DataPoint(DataTypes.WEIGHT, 5))
    return gun def new_sling(game_state):
    sling = Composite()
    set_item_components(sling, game_state)
    set_ranged_weapon_components(sling)
    sling.set_child(RangeWeaponType(RangeWeaponType.SLING))
    sling.set_child(Description("Sling",
                                "This weapon propels rocks more effectively than throwing them would."))
    sling.set_child(GraphicChar(None, colors.ORANGE, icon.SLING))
    sling.set_child(DataPoint(DataTypes.WEAPON_RANGE, 4))
    sling.set_child(DataPoint(DataTypes.WEIGHT, 3))
    sling.set_child(accuracy_item_stat(5))
    sling.set_child(damage_item_stat(1, 3))

    sling.set_child(CritChanceBonusEffect(0.2))
    sling.set_child(crit_multiplier_item_stat(2.0))

    sling.set_child(StunAttackEffect(1))

    return sling def new_dagger(game_state):
    """
    A composite component representing a Knife item.
    """
    c = Composite()
    set_item_components(c, game_state)
    set_melee_weapon_component(c)
    c.set_child(Description("Dagger", "A trusty dagger, small and precise but will only inflict small wounds."))
    c.set_child(GraphicChar(None, colors.GRAY, icon.DAGGER))
    c.set_child(DataPoint(DataTypes.WEIGHT, 5))
    c.set_child(DamageType(DamageTypes.CUTTING))

    c.set_child(damage_item_stat(1, 3))
    c.set_child(accuracy_item_stat(15))

    c.set_child(CritChanceBonusEffect(0.2))
    c.set_child(crit_multiplier_item_stat(3.5))

    c.set_child(ExtraSwingAttackEffect(0.20))
    c.set_child(BleedAttackEffect(0.10))

    return c
from player_class import new_rogue_player
from cloud import new_steam_cloud
from dungeon import Dungeon, ReflexiveDungeon
from dungeonlevelfactory import dungeon_level_from_file
from mover import teleport_monsters
from player import new_player
from player_class import new_rogue_player
from save import save, delete_save_file_of_game_state
from weapon import new_gun, new_sling, new_dagger
import colors
import dungeonfeature
import gametime
import libtcodpy
import monster
import camera
import console
import constants
import gui
import item
import menufactory
import messenger
import rectfactory
import settings
import state
import statestack
import turn
import weapon
    def __getstate__(self):
        state = {
            "player": self.player,
            "dungeon": self.dungeon
        }
        print "get gs"
        return state

    def __setstate__(self, state):
        print "*****gamestate ", state.__class__
        print "set gs"
        self.player = state["player"]
        self.dungeon = state["dungeon"]
        self._init_caches_and_flags()

    def _init_gui(self):
        self.entity_stack_panel = gui.StackPanelVertical((0, 0))
        self.entity_stack_panel.append(gui.EntityStatusList(self.player, constants.LEFT_SIDE_BAR_WIDTH, vertical_space=0))
        self.entity_stack_panel.append(gui.PlayerStatusBox(rectfactory.player_status_rect(), self.player))
        self.gui_dock = gui.UIDock(rectfactory.full_screen_rect())
        self.gui_dock.bottom_left = self.entity_stack_panel
        self.command_list_bar = gui.CommandListPanel(rectfactory.right_side_menu_rect())
        self.gui_dock.bottom_right = self.command_list_bar
        self._message_display = gui.MessageDisplay(rectfactory.message_display_rect(), vertical_space=0)

    def _init_bg(self):
        for x in range(constants.GAME_STATE_WIDTH):
            for y in range(constants.GAME_STATE_WIDTH):
                console.console.set_colors_and_symbol((x, y), colors.UNSEEN_FG, colors.UNSEEN_BG, " ",
                                                      console=self._background_console)

    def signal_new_level(self):
        self.camera.center_on_entity(self.player)
        self.dungeon_needs_redraw = True
        if not self.first_round:
            save(self)

    def start_prompt(self, prompt_state):
        self.menu_prompt_stack.push(prompt_state)
        self.menu_prompt_stack.main_loop()

    def signal_should_redraw_screen(self):
        self._should_draw = True

    # most of the time the drawing is handled in EntityScheduler,
    # right before the player acts.
    # if a redraw is needed do a force_draw instead.
    def draw(self):
        pass

    def force_draw(self):
        self.camera.update(self.player)
        self.prepare_draw()
        self._should_draw = False
        console.console.flush()

    def prepare_draw(self):
        dungeon_level = self.player.dungeon_level.value
        self._draw_bg()
        if self.dungeon_needs_redraw:
            dungeon_level.draw_all_within_screen(self.camera)
            self.dungeon_needs_redraw = False
        else:
            dungeon_level.draw_close_to_player(self.camera)
        self.player.path.draw(self.camera)
        self.prepare_draw_gui()

    def prepare_draw_gui(self):
        if self._gui_last_update_timestamp < turn.current_turn:
            self._update_gui()
        self._message_display.draw()
        self.gui_dock.draw()

    def update(self):
        self._message_display.update()

        dungeon_level = \
            self.player.dungeon_level.value
        if not dungeon_level is self._last_dungeon_level:
            self.signal_new_level()
        self._last_dungeon_level = dungeon_level

        #self._update_gui()
        dungeon_level.tick(gametime.normal_energy_gain)

        if self.player.health.is_dead():
            self.force_draw()
            game_over_screen = menufactory.game_over_screen(self.current_stack)
            delete_save_file_of_game_state()
            self.current_stack.push(game_over_screen)
        if self.has_won:
            victory_screen = menufactory.victory_screen(self.current_stack)
            delete_save_file_of_game_state()
            self.current_stack.push(victory_screen)

        self.first_round = False

    def _update_gui(self):
        self.entity_stack_panel.update()
        self.command_list_bar.update()
        self._gui_last_update_timestamp = turn.current_turn

    def _draw_bg(self):
        libtcodpy.console_blit(self._background_console, 0, 0, constants.GAME_STATE_WIDTH, constants.GAME_STATE_HEIGHT,
                               0, 0, 0)

    def draw_loading_screen(self, text):
        libtcodpy.console_blit(self._background_console, 0, 0, constants.GAME_STATE_WIDTH, constants.GAME_STATE_HEIGHT,
                               0, 0, 0)
        console.console.print_text((settings.SCREEN_WIDTH / 2 - len(text) / 2,
                                    settings.SCREEN_HEIGHT / 2), text)
        console.console.flush()


class TestGameState(GameStateBase):
    def __init__(self, player_name=""):
        super(TestGameState, self).__init__(player_name)
        reset_globals(self.player)
        start_position = (20, 10)
        self.dungeon_level = dungeon_level_from_file("test.level")

        self.dungeon = ReflexiveDungeon(self.dungeon_level)