Exemplo n.º 1
0
def landTest():
    # Sustainability Result
    result = ""

    # Initialize plot
    fig, ax = plt.subplots()

    # Look at the change over a period of time
    generations = 10

    # Initialize a land
    l = Land(10, 10)
    result += l.sustanabilityAssessment(0) + "\n"
    im = ax.imshow(l.digitLand)
    im.figure.savefig("../output/Land3/Land3-Gen-0.png")

    for i in range(generations):
        fileName = "../output/Land3/Land3-Gen-" + str(i + 1) + ".png"
        l = l.newGen()
        result += l.sustanabilityAssessment(i + 1) + "\n"
        heat = ax.imshow(l.digitLand)
        heat.figure.savefig(fileName)

    f = open("../output/Land3/Sustainability Assessment.txt", "w")
    f.write(result)
    f.close()
Exemplo n.º 2
0
    def load(self, host="localhost", port=6499):
        print "Tuner.load " + str(port)

        # Calibrate page
        self.calibrate = Calibrate(changefunc=self.onChange,
                                   host=host,
                                   port=port)
        self.tabs.addTab(self.calibrate.get_widget(), "Calibrate")

        # Preflight page
        self.preflight = Preflight(changefunc=self.onChange,
                                   host=host,
                                   port=port)
        self.tabs.addTab(self.preflight.get_widget(), "Preflight")

        # Launch page
        self.launch = Launch(changefunc=self.onChange, host=host, port=port)
        self.tabs.addTab(self.launch.get_widget(), "Launch")

        # Circle hold page
        self.circle = Circle(changefunc=self.onChange, host=host, port=port)
        self.tabs.addTab(self.circle.get_widget(), "Circle")

        # Chirp page
        self.chirp = Chirp(changefunc=self.onChange, host=host, port=port)
        self.tabs.addTab(self.chirp.get_widget(), "Chirp")

        # Land page
        self.land = Land(changefunc=self.onChange, host=host, port=port)
        self.tabs.addTab(self.land.get_widget(), "Land")
Exemplo n.º 3
0
def land_operation():
    import land
    from land import Land
    _task = Land(unitypot)

    time.sleep(1)
    _task.start()
    global is_armed
    is_armed = False
Exemplo n.º 4
0
    def load(self, host="localhost", port=6499):
        print "Tuner.load " + str(port)

        # Recalibrate page
        self.recalibrate = Recalibrate(changefunc=self.onChange, host=host,
                                       port=port)
        self.tabs.addTab( self.recalibrate.get_widget(), "Recalibrate" )

        # Preflight page
        self.preflight = Preflight(changefunc=self.onChange, host=host,
                                   port=port)
        self.tabs.addTab( self.preflight.get_widget(), "Preflight" )

        # Launch page
        self.launch = Launch(changefunc=self.onChange, host=host, port=port)
        self.tabs.addTab( self.launch.get_widget(), "Launch" )

        # Circle hold page
        self.circle = Circle(changefunc=self.onChange, host=host, port=port)
        self.tabs.addTab( self.circle.get_widget(), "Circle" )

        # Chirp page
        self.chirp = Chirp(changefunc=self.onChange, host=host, port=port)
        self.tabs.addTab( self.chirp.get_widget(), "Chirp" )

        # Land page
        self.land = Land(changefunc=self.onChange, host=host, port=port)
        self.tabs.addTab( self.land.get_widget(), "Land" )
Exemplo n.º 5
0
def draw_living(screen: pg.Surface, position: te.Terrain, color: pg.Color,
                img: pg.Surface, land: ld.Land):
    #pg.draw.polygon(screen, color, land.polygon_corners(position), width=0)

    l_x, l_y = land.polygon_center(position)
    img_w, img_h = img.get_size()
    img_coord = (l_x - img_w // 2, l_y - img_h // 2)
    screen.blit(img, img_coord)
Exemplo n.º 6
0
    def __init__(self):
        self.game_size = 50
        self.ticks_per_second = 120

        screen_size_x = 800
        screen_size_y = 800

        self.land = Land(self.game_size)
        self.drawer = Drawer(screen_size_x, screen_size_y, self.land)
        self.controller = Controller(self.land, self.drawer)
Exemplo n.º 7
0
def create_world():
    global character, back_ground, land, enemy, city, death, time

    character = Boy()
    death = Death(character)
    enemy = [Enemy() for i in range(5)]
    back_ground = Back_ground()
    land = Land()
    city = City()
    time = get_time()
Exemplo n.º 8
0
    def __init__(self, image, position, villager_id, font, listener,
                 current_leader, skill_images):
        self.role = Role.FOLLOWER
        self.listener = listener
        self.current_leader = current_leader
        self.leadership_term = 0
        # render shouting
        self.message_count = 1
        # for testing to only create one leader
        self.skills = []
        self.skill_adding_list = []
        self.max_health = Constant.VILLAGER_MAX_HP
        self.current_health = self.max_health
        self.current_message = ""
        self.message_countdown = 0
        self.learned_skill_names = []
        self.turning_learned_skills_list = []
        self.dead = False
        self.dead_message_sent = False
        width, height = image.get_rect().size
        center_x, center_y = position
        super().__init__(image, center_x, center_y, height, width)
        self.villager_id = villager_id
        self.font = font
        self.attacked = False
        self.item = []
        self.attack = None

        self.land = Land(self, Constant.LAND_SIZE)

        self.house = None
        self.build_house_countdown = Constant.BUILD_HOUSE_COUNT_DOWN

        threading.Thread.__init__(self)

        self.attack_probability = 0.5
        self.attack_display_count_down = Constant.ATTACK_DISPLAY_COUNT_DOWN
        self.attack_display_count_down_const = Constant.ATTACK_DISPLAY_COUNT_DOWN
        self.attacked = False
        self.attack_power = 1

        self.skill_images = skill_images
Exemplo n.º 9
0
def setCards():
    global rootCards
    rootCards.append(Land("Mountain", RED))
    rootCards.append(
        Creature("Blood Ogre", [2, 1, 0, 0, 0, 0], 2, 2, "Ogre", "Warrior"))
    rootCards.append(
        Creature("Bonebreaker Giant", [4, 1, 0, 0, 0, 0], 4, 4, "Giant"))
    rootCards.append(
        Creature("Chandra's Phoenix", [1, 2, 0, 0, 0, 0], 2, 2, "Phoenix"))
    rootCards.append(
        Creature("Crimson Mage", [1, 1, 0, 0, 0, 0], 2, 1, "Human", "Shaman"))
    rootCards.append(
        Creature("Fiery Hellhound", [1, 2, 0, 0, 0, 0], 2, 2, "Elemental",
                 "Hound"))
    rootCards.append(
        Creature("Flameblast Dragon", [4, 2, 0, 0, 0, 0], 5, 5, "Dragon"))
    rootCards.append(
        Creature("Furyborn Hellkite", [4, 3, 0, 0, 0, 0], 6, 6, "Dragon"))
    rootCards.append(
        Creature("Goblin Arsonist", [0, 1, 0, 0, 0, 0], 1, 1, "Goblin",
                 "Shaman"))
    rootCards.append(
        Creature("Goblin Bangchuckers", [2, 2, 0, 0, 0, 0], 2, 2, "Goblin",
                 "Warrior"))
    rootCards.append(
        Creature("Goblin Chieftain", [1, 2, 0, 0, 0, 0], 2, 2, "Goblin"))
    rootCards.append(
        Creature("Goblin Fireslinger", [0, 1, 0, 0, 0, 0], 1, 1, "Goblin",
                 "Warrior"))
    rootCards.append(
        Creature("Goblin Piker", [1, 1, 0, 0, 0, 0], 2, 1, "Goblin",
                 "Warrior"))
    rootCards.append(
        Creature("Goblin Tunneler", [1, 1, 0, 0, 0, 0], 1, 1, "Goblin",
                 "Rogue"))
    rootCards.append(
        Creature("Gorehorn Minotaurs", [2, 2, 0, 0, 0, 0], 3, 3, "Minotaur",
                 "Warrior"))
    rootCards.append(
        Creature("Grim Lavamancer", [0, 1, 0, 0, 0, 0], 1, 1, "Human",
                 "Wizard"))
    rootCards.append(
        Creature("Inferno Titan", [4, 2, 0, 0, 0, 0], 6, 6, "Giant"))
    rootCards.append(
        Creature("Lightning Elemental", [3, 1, 0, 0, 0, 0], 4, 1, "Elemental"))
    rootCards.append(
        Creature("Manic Vandal", [2, 1, 0, 0, 0, 0], 2, 2, "Human", "Warrior"))
    rootCards.append(
        Creature("Stormblood Berserker", [1, 1, 0, 0, 0, 0], 1, 1, "Human",
                 "Berserker"))
    rootCards.append(
        Creature("Volcanic Dragon", [4, 2, 0, 0, 0, 0], 4, 4, "Dragon"))
    rootCards.append(
        Creature("Wall of Torches", [1, 1, 0, 0, 0, 0], 4, 1, "Wall"))
Exemplo n.º 10
0
 def __init__(self):
     tile_resources = [DESERT, SHEEP, WOOD, WHEAT]
     tile_resources.extend([WOOD, CLAY, SHEEP, WHEAT, ROCK] * 3)
     random.shuffle(tile_resources)
     rolls = [5, 2, 6, 3, 8, 10, 9, 12, 11, 4, 8, 10, 9, 4, 5, 6, 3, 11]
     desert = tile_resources.index(DESERT)
     rolls.insert(desert, 0)
     self.tiles = [Tile(i, tile_resources[i], rolls[i]) for i in range(19)]
     self.land = [Land(i) for i in range(54)]
     self.paths = [Path(i) for i in range(72)]
     self.robber = [t.resource for t in self.tiles].index(DESERT)
Exemplo n.º 11
0
 def initialize_all(self):
     print("Welcome to Kafustrok. Light blesses you. ")
     for i in range(self._DIMENSION):
         for j in range(self._DIMENSION):
             self._lands[i][j] = Land()
     for i in range(self._total_num):
         pos = self.get_un_occupied_position()
         if i < self._m:
             self.lands[pos.x][pos.y].occupied_obj = Monster(pos.x, pos.y, i, self)
         elif i < self._m + self._e:
             self.lands[pos.x][pos.y].occupied_obj = Elf(pos.x,pos.y, i - self._m, self)
         elif i < self._m + self._e + self._w:
             self.lands[pos.x][pos.y].occupied_obj = Warrior(pos.x, pos.y, i - self._m - self._e, self)
             self._teleportable_obj.append(self.lands[pos.x][pos.y].occupied_obj)
         else:
             self.lands[pos.x][pos.y].occupied_obj = Potion(pos.x, pos.y, i - self._m - self._e - self._w, self)
             self._teleportable_obj.append(self.lands[pos.x][pos.y].occupied_obj)
Exemplo n.º 12
0
    def __init__(self,
                 width=0,
                 height=0,
                 torus=False,
                 time=0,
                 step_in_year=0,
                 number_of_families=family_setting,
                 number_of_monkeys=0,
                 monkey_birth_count=0,
                 monkey_death_count=0,
                 monkey_id_count=0,
                 number_of_humans=0,
                 grid_type=human_setting,
                 run_type=run_setting,
                 human_id_count=0):
        # change the # of families here for graph.py, but use server.py to change # of families in the movement model
        # torus = False means monkey movement can't 'wrap around' edges
        super().__init__()
        self.width = width
        self.height = height
        self.time = time  # time increases by 1/73 (decimal) each step
        self.step_in_year = step_in_year  # 1-73; each step is 5 days, and 5 * 73 = 365 days in a year
        self.number_of_families = number_of_families
        self.number_of_monkeys = number_of_monkeys  # total, not in each family
        self.monkey_birth_count = monkey_birth_count
        self.monkey_death_count = monkey_death_count
        self.monkey_id_count = monkey_id_count
        self.number_of_humans = number_of_humans
        self.grid_type = grid_type  # string 'with_humans' or 'without_humans'
        self.run_type = run_type  # string with 'normal_run' or 'first_run'
        self.human_id_count = human_id_count

        # width = self._readASCII(vegetation_file)[1] # width as listed at the beginning of the ASCII file
        # height = self._readASCII(vegetation_file)[2] # height as listed at the beginning of the ASCII file
        width = 85
        height = 100

        self.grid = MultiGrid(
            width, height, torus)  # creates environmental grid, sets schedule
        # MultiGrid is a Mesa function that sets up the grid; options are between SingleGrid and MultiGrid
        # MultiGrid allows you to put multiple layers on the grid

        self.schedule = RandomActivation(
            self)  # Mesa: Random vs. Staged Activation
        # similar to NetLogo's Ask Agents - determines order (or lack of) in which each agents act

        empty_masterdict = {
            'Outside_FNNR': [],
            'Elevation_Out_of_Bound': [],
            'Household': [],
            'PES': [],
            'Farm': [],
            'Forest': [],
            'Bamboo': [],
            'Coniferous': [],
            'Broadleaf': [],
            'Mixed': [],
            'Lichen': [],
            'Deciduous': [],
            'Shrublands': [],
            'Clouds': [],
            'Farmland': []
        }

        # generate land
        if self.run_type == 'first_run':
            gridlist = self._readASCII(
                vegetation_file
            )[0]  # list of all coordinate values; see readASCII function below
            gridlist2 = self._readASCII(elevation_file)[
                0]  # list of all elevation values
            gridlist3 = self._readASCII(household_file)[
                0]  # list of all household coordinate values
            gridlist4 = self._readASCII(pes_file)[
                0]  # list of all PES coordinate values
            gridlist5 = self._readASCII(farm_file)[
                0]  # list of all farm coordinate values
            gridlist6 = self._readASCII(forest_file)[
                0]  # list of all managed forest coordinate values
            # The '_populate' function below builds the environmental grid.
            for x in [Elevation_Out_of_Bound]:
                self._populate(empty_masterdict, gridlist2, x, width, height)
            for x in [Household]:
                self._populate(empty_masterdict, gridlist3, x, width, height)
            for x in [PES]:
                self._populate(empty_masterdict, gridlist4, x, width, height)
            for x in [Farm]:
                self._populate(empty_masterdict, gridlist5, x, width, height)
            for x in [Forest]:
                self._populate(empty_masterdict, gridlist6, x, width, height)
            for x in [
                    Bamboo, Coniferous, Broadleaf, Mixed, Lichen, Deciduous,
                    Shrublands, Clouds, Farmland, Outside_FNNR
            ]:
                self._populate(empty_masterdict, gridlist, x, width, height)
            self.saveLoad(empty_masterdict, 'masterdict_veg', 'save')
            self.saveLoad(self.grid, 'grid_veg', 'save')
            self.saveLoad(self.schedule, 'schedule_veg', 'save')

        # Pickling below
        load_dict = {
        }  # placeholder for model parameters, leave this here even though it does nothing

        if self.grid_type == 'with_humans':
            empty_masterdict = self.saveLoad(load_dict, 'masterdict_veg',
                                             'load')
            self.grid = self.saveLoad(self.grid, 'grid_veg', 'load')

        if self.grid_type == 'without_humans':
            empty_masterdict = self.saveLoad(load_dict,
                                             'masterdict_without_humans',
                                             'load')
            self.grid = self.saveLoad(load_dict, 'grid_without_humans', 'load')
        masterdict = empty_masterdict

        startinglist = masterdict['Broadleaf'] + masterdict[
            'Mixed'] + masterdict['Deciduous']
        # Agents will start out in high-probability areas.
        for coordinate in masterdict['Elevation_Out_of_Bound'] + masterdict['Household'] + masterdict['PES']    \
            + masterdict['Farm'] + masterdict['Forest']:
            if coordinate in startinglist:
                startinglist.remove(
                    coordinate
                )  # the original starting list includes areas that monkeys
                # cannot start in

        # Creation of resources (yellow dots in simulation)
        # These include Fuelwood, Herbs, Bamboo, etc., but right now resource type and frequency are not used
        if self.grid_type == 'with_humans':
            for line in _readCSV('hh_survey.csv')[1:]:  # see 'hh_survey.csv'
                hh_id_match = int(line[0])
                resource_name = line[
                    1]  # frequency is monthly; currently not-used
                frequency = float(
                    line[2]
                ) / 6  # divided by 6 for 5-day frequency, as opposed to 30-day (1 month)
                y = int(line[5])
                x = int(line[6])
                resource = Resource(
                    _readCSV('hh_survey.csv')[1:].index(line), self, (x, y),
                    hh_id_match, resource_name, frequency)
                self.grid.place_agent(resource, (int(x), int(y)))
                resource_dict.setdefault(hh_id_match, []).append(resource)
                if self.run_type == 'first_run':
                    self.saveLoad(resource_dict, 'resource_dict', 'save')

        # Creation of land parcels
        land_parcel_count = 0

        # individual land parcels in each household (non-gtgp and gtgp)
        for line in _readCSV(
                'hh_land.csv')[2:]:  # exclude headers; for each household:
            age_1 = float(line[45])
            gender_1 = float(line[46])
            education_1 = float(line[47])
            hh_id = int(line[0])
            hh_size = 0  # calculate later

            total_rice = float(line[41])
            if total_rice in [-2, -3, -4]:
                total_rice = 0
            gtgp_rice = float(line[42])
            if gtgp_rice in [-2, -3, -4]:
                gtgp_rice = 0
            total_dry = float(line[43])
            if total_dry in [-2, -3, -4]:
                total_dry = 0
            gtgp_dry = float(line[44])
            if gtgp_dry in [-2, -3, -4]:
                gtgp_dry = 0
            # non_gtgp_area = float(total_rice) + float(total_dry) - float(gtgp_dry) - float(gtgp_rice)
            # gtgp_area = float(gtgp_dry) + float(gtgp_rice)

            for i in range(
                    1, 6
            ):  # for each household, which has up to 5 each of possible non-GTGP and GTGP parcels:
                # non_gtgp_area = float(line[i + 47].replace("\"",""))
                # gtgp_area = float(line[i + 52].replace("\"",""))
                non_gtgp_area = float(total_rice) + float(total_dry) - float(
                    gtgp_dry) - float(gtgp_rice)
                gtgp_area = float(gtgp_dry) + float(gtgp_rice)

                if gtgp_area in [-2, -3, -4]:
                    gtgp_area = 0
                if non_gtgp_area in [-2, -3, -4]:
                    non_gtgp_area = 0

                if non_gtgp_area > 0:
                    gtgp_enrolled = 0
                    non_gtgp_output = float(line[i].replace("\"", ""))
                    pre_gtgp_output = 0
                    land_time = float(line[i + 25].replace(
                        "\"", ""))  # non-gtgp travel time
                    plant_type = float(line[i + 10].replace(
                        "\"", ""))  # non-gtgp plant type
                    land_type = float(line[i + 30].replace(
                        "\"", ""))  # non-gtgp land type

                    if land_type not in [-2, -3, -4]:
                        land_parcel_count += 1
                        if non_gtgp_output in [-3, '-3', -4, '-4']:
                            non_gtgp_output = 0
                        if pre_gtgp_output in [-3, '-3', -4, '-4']:
                            pre_gtgp_output = 0
                        lp = Land(land_parcel_count, self, hh_id,
                                  gtgp_enrolled, age_1, gender_1, education_1,
                                  gtgp_dry, gtgp_rice, total_dry, total_rice,
                                  land_type, land_time, plant_type,
                                  non_gtgp_output, pre_gtgp_output, hh_size,
                                  non_gtgp_area, gtgp_area)
                        self.schedule.add(lp)

                if gtgp_area > 0:
                    gtgp_enrolled = 1
                    pre_gtgp_output = 0
                    non_gtgp_output = float(line[i].replace("\"", ""))
                    land_time = float(line[i + 20].replace(
                        "\"", ""))  # gtgp travel time
                    plant_type = float(line[i + 15].replace(
                        "\"", ""))  # gtgp plant type
                    land_type = float(line[i + 35].replace(
                        "\"", ""))  # gtgp land type
                    if land_type not in [-3, '-3', -4, '-4']:
                        land_parcel_count += 1
                        if non_gtgp_output in [-3, '-3', -4, '-4']:
                            non_gtgp_output = 0
                        if pre_gtgp_output in [-3, '-3', -4, '-4']:
                            pre_gtgp_output = 0
                        lp = Land(land_parcel_count, self, hh_id,
                                  gtgp_enrolled, age_1, gender_1, education_1,
                                  gtgp_dry, gtgp_rice, total_dry, total_rice,
                                  land_type, land_time, plant_type,
                                  non_gtgp_output, pre_gtgp_output, hh_size,
                                  non_gtgp_area, gtgp_area)
                        self.schedule.add(lp)

        # Creation of humans (brown dots in simulation)
        self.number_of_humans = 0
        self.human_id_count = 0
        line_counter = 0
        for line in _readCSV(
                'hh_citizens.csv')[1:]:  # exclude headers; for each household:
            hh_id = int(line[0])
            line_counter += 1
            starting_position = (
                int(_readCSV('household.csv')[line_counter][4]),
                int(_readCSV('household.csv')[line_counter][3]))
            try:
                resource = random.choice(resource_dict[str(
                    hh_id)])  # random resource point for human
                resource_position = resource.position
                resource_frequency = resource.frequency
                # to travel to, among the list of resource points reported by that household; may change later
                # to another randomly-picked resource
            except KeyError:
                resource_position = starting_position  # some households don't collect resources
                resource_frequency = 0
            hh_gender_list = line[1:10]
            hh_age_list = line[10:19]
            hh_education_list = line[19:28]
            hh_marriage_list = line[28:37]
            # creation of non-migrants
            for list_item in hh_age_list:
                if str(list_item) == '-3' or str(list_item) == '':
                    hh_age_list.remove(list_item)
            for x in range(len(hh_age_list) - 1):
                person = []
                for item in [
                        hh_age_list, hh_gender_list, hh_education_list,
                        hh_marriage_list
                ]:
                    person.append(item[x])
                age = float(person[0])
                gender = int(person[1])
                education = int(person[2])
                marriage = int(person[3])
                if marriage != 1:
                    marriage = 6
                if 15 < age < 59:
                    work_status = 1
                elif 7 < age < 15:
                    work_status = 5
                else:
                    work_status = 6
                mig_years = 0
                migration_network = int(line[37])
                income_local_off_farm = int(line[57])
                resource_check = 0
                mig_remittances = int(line[48])
                past_hh_id = hh_id
                migration_status = 0
                death_rate = 0
                gtgp_part = 0
                non_gtgp_area = 0

                if str(gender) == '1':
                    if 0 < age <= 10:
                        age_category = 0
                    elif 10 < age <= 20:
                        age_category = 1
                    elif 20 < age <= 30:
                        age_category = 2
                    elif 30 < age <= 40:
                        age_category = 3
                    elif 40 < age <= 50:
                        age_category = 4
                    elif 50 < age <= 60:
                        age_category = 5
                    elif 60 < age <= 70:
                        age_category = 6
                    elif 70 < age <= 80:
                        age_category = 7
                    elif 80 < age <= 90:
                        age_category = 8
                    elif 90 < age:
                        age_category = 9
                elif str(gender) != "1":
                    if 0 < age <= 10:
                        age_category = 10
                    elif 10 < age <= 20:
                        age_category = 11
                    elif 20 < age <= 30:
                        age_category = 12
                    elif 30 < age <= 40:
                        age_category = 13
                    elif 40 < age <= 50:
                        age_category = 14
                    elif 50 < age <= 60:
                        age_category = 15
                    elif 60 < age <= 70:
                        age_category = 16
                    elif 70 < age <= 80:
                        age_category = 17
                    elif 80 < age <= 90:
                        age_category = 18
                    elif 90 < age:
                        age_category = 19
                children = 0
                if gender == 2:
                    if marriage == 1 and age < 45:
                        children = random.randint(0,
                                                  4)  # might already have kids
                    birth_plan_chance = random.random()
                    if birth_plan_chance < 0.03125:
                        birth_plan = 0
                    elif 0.03125 <= birth_plan_chance < 0.1875:
                        birth_plan = 1
                    elif 0.1875 <= birth_plan_chance < 0.5:
                        birth_plan = 2
                    elif 0.5 <= birth_plan_chance < 0.8125:
                        birth_plan = 3
                    elif 0.8125 <= birth_plan_chance < 0.96875:
                        birth_plan = 4
                    else:
                        birth_plan = 5
                elif gender != 2:
                    birth_plan = 0
                last_birth_time = random.uniform(0, 1)
                human_demographic_structure_list[age_category] += 1
                if str(person[0]) != '' and str(person[0]) != '-3' and str(
                        person[1]) != '-3':  # sorts out all blanks
                    self.number_of_humans += 1
                    self.human_id_count += 1
                    human = Human(
                        self.human_id_count,
                        self,
                        starting_position,
                        hh_id,
                        age,  # creates human
                        resource_check,
                        starting_position,
                        resource_position,
                        resource_frequency,
                        gender,
                        education,
                        work_status,
                        marriage,
                        past_hh_id,
                        mig_years,
                        migration_status,
                        gtgp_part,
                        non_gtgp_area,
                        migration_network,
                        mig_remittances,
                        income_local_off_farm,
                        last_birth_time,
                        death_rate,
                        age_category,
                        children,
                        birth_plan)
                    if self.grid_type == 'with_humans':
                        self.grid.place_agent(human, starting_position)
                        self.schedule.add(human)

            # creation of migrant
            hh_migrants = line[
                38:43]  # age, gender, marriage, education of migrants
            if str(hh_migrants[0]) != '' and str(hh_migrants[0]) != '-3'\
                    and str(hh_migrants[1]) != '' and str(hh_migrants[1]) != '-3':  # if that household has any migrants, create migrant person
                self.number_of_humans += 1
                self.human_id_count += 1
                age = float(hh_migrants[0])
                gender = float(hh_migrants[1])
                education = int(hh_migrants[2])
                marriage = int(hh_migrants[3])
                mig_years = int(hh_migrants[4])
                if 15 < age < 59:
                    work_status = 1
                elif 7 < age < 15:
                    work_status = 5
                else:
                    work_status = 6
                past_hh_id = hh_id
                hh_id = 'Migrated'
                migration_status = 1
                migration_network = int(line[37])

                last_birth_time = random.uniform(0, 1)

                total_rice = float(line[43])
                gtgp_rice = float(line[44])
                total_dry = float(line[45])
                gtgp_dry = float(line[46])
                income_local_off_farm = float(line[57])
                if total_rice in ['-3', '-4', -3, None]:
                    total_rice = 0
                if total_dry in ['-3', '-4', -3, None]:
                    total_dry = 0
                if gtgp_dry in ['-3', '-4', -3, None]:
                    gtgp_dry = 0
                if gtgp_rice in ['-3', '-4', -3, None]:
                    gtgp_rice = 0
                if (gtgp_dry + gtgp_rice) != 0:
                    gtgp_part = 1
                else:
                    gtgp_part = 0
                non_gtgp_area = ((total_rice) + (total_dry)) \
                                - ((gtgp_dry) + (gtgp_rice))
                resource_check = 0
                mig_remittances = int(line[48])
                death_rate = 0
                if gender == 1:  # human male (monkeys are 0 and 1, humans are 1 and 2)
                    if 0 < age <= 10:
                        age_category = 0
                    elif 10 < age <= 20:
                        age_category = 1
                    elif 20 < age <= 30:
                        age_category = 2
                    elif 30 < age <= 40:
                        age_category = 3
                    elif 40 < age <= 50:
                        age_category = 4
                    elif 50 < age <= 60:
                        age_category = 5
                    elif 60 < age <= 70:
                        age_category = 6
                    elif 70 < age <= 80:
                        age_category = 7
                    elif 80 < age <= 90:
                        age_category = 8
                    elif 90 < age:
                        age_category = 9
                elif gender != 1:
                    if 0 < age <= 10:
                        age_category = 10
                    elif 10 < age <= 20:
                        age_category = 11
                    elif 20 < age <= 30:
                        age_category = 12
                    elif 30 < age <= 40:
                        age_category = 13
                    elif 40 < age <= 50:
                        age_category = 14
                    elif 50 < age <= 60:
                        age_category = 15
                    elif 60 < age <= 70:
                        age_category = 16
                    elif 70 < age <= 80:
                        age_category = 17
                    elif 80 < age <= 90:
                        age_category = 18
                    elif 90 < age:
                        age_category = 19
                children = 0
                if gender == 2:
                    if marriage == 1 and age < 45:
                        children = random.randint(0,
                                                  4)  # might already have kids
                    birth_plan_chance = random.random()
                    if birth_plan_chance < 0.03125:
                        birth_plan = 0
                    elif 0.03125 <= birth_plan_chance < 0.1875:
                        birth_plan = 1
                    elif 0.1875 <= birth_plan_chance < 0.5:
                        birth_plan = 2
                    elif 0.5 <= birth_plan_chance < 0.8125:
                        birth_plan = 3
                    elif 0.8125 <= birth_plan_chance < 0.96875:
                        birth_plan = 4
                    else:
                        birth_plan = 5
                elif gender != 2:
                    birth_plan = 0
                human_demographic_structure_list[age_category] += 1
                human = Human(
                    self.human_id_count,
                    self,
                    starting_position,
                    hh_id,
                    age,  # creates human
                    resource_check,
                    starting_position,
                    resource_position,
                    resource_frequency,
                    gender,
                    education,
                    work_status,
                    marriage,
                    past_hh_id,
                    mig_years,
                    migration_status,
                    gtgp_part,
                    non_gtgp_area,
                    migration_network,
                    mig_remittances,
                    income_local_off_farm,
                    last_birth_time,
                    death_rate,
                    age_category,
                    children,
                    birth_plan)
                if self.grid_type == 'with_humans':
                    self.grid.place_agent(human, starting_position)
                    self.schedule.add(human)

        # Creation of monkey families (moving agents in the visualization)
        for i in range(self.number_of_families
                       ):  # the following code block creates families
            starting_position = random.choice(startinglist)
            saved_position = starting_position
            from families import Family
            family_size = random.randint(
                25, 45)  # sets family size for each group--random integer
            family_id = i
            list_of_family_members = []
            family_type = 'traditional'  # as opposed to an all-male subgroup
            split_flag = 0  # binary: 1 means its members start migrating out to a new family
            family = Family(family_id, self, starting_position, family_size,
                            list_of_family_members, family_type,
                            saved_position, split_flag)
            self.grid.place_agent(family, starting_position)
            self.schedule.add(family)
            global_family_id_list.append(family_id)

            # Creation of individual monkeys (not in the visualization submodel, but for the demographic submodel)
            for monkey_family_member in range(
                    family_size
            ):  # creates the amount of monkeys indicated earlier
                id = self.monkey_id_count
                gender = random.randint(0, 1)
                if gender == 1:  # gender = 1 is female, gender = 0 is male. this is different than with humans (1 or 2)
                    female_list.append(id)
                    last_birth_interval = random.uniform(0, 2)
                else:
                    male_maingroup_list.append(
                        id)  # as opposed to the all-male subgroup
                    last_birth_interval = -9999  # males will never give birth
                mother = 0  # no parent check for first generation
                choice = random.random(
                )  # 0 - 1 float - age is determined randomly based on weights
                if choice <= 0.11:  # 11% of starting monkey population
                    age = random.uniform(0, 1)  # are randomly aged befween
                    age_category = 0  # ages 0-1
                    demographic_structure_list[0] += 1
                elif 0.11 < choice <= 0.27:  # 16% of starting monkey population
                    age = random.uniform(1, 3)  # are randomly aged befween
                    age_category = 1  # ages 1-3
                    demographic_structure_list[1] += 1
                elif 0.27 < choice <= 0.42:  # 15% of starting monkey population
                    age = random.uniform(3, 7)  # are randomly aged between
                    age_category = 2  # ages 3-7
                    demographic_structure_list[2] += 1
                elif 0.42 < choice <= 0.62:  # 11% of starting monkey population
                    age = random.uniform(7, 10)  # are randomly aged befween
                    age_category = 3  # ages 7-10
                    demographic_structure_list[3] += 1
                elif 0.62 < choice <= 0.96:  # 34% of starting monkey population
                    age = random.uniform(10, 25)  # are randomly aged befween
                    age_category = 4  # ages 10-25
                    demographic_structure_list[4] += 1
                    if gender == 1:
                        if id not in reproductive_female_list:
                            reproductive_female_list.append(id)
                    # starting representation of male defection/gender ratio
                    structure_convert = random.random()
                    if gender == 0:
                        if structure_convert < 0.6:
                            gender = 1
                            last_birth_interval = random.uniform(0, 3)
                            if id not in reproductive_female_list:
                                reproductive_female_list.append(id)
                elif 0.96 < choice:  # 4% of starting monkey population
                    age = random.uniform(25, 30)  # are randomly aged between
                    age_category = 5  # ages 25-30
                    demographic_structure_list[5] += 1
                    gender = 1
                monkey = Monkey(id, self, gender, age, age_category, family,
                                last_birth_interval, mother)
                self.number_of_monkeys += 1
                self.monkey_id_count += 1
                list_of_family_members.append(monkey.unique_id)
                self.schedule.add(monkey)
Exemplo n.º 13
0
def main():


    open_canvas()
    global mainback
    mainback = Mainback()
    global start
    start = False

    while(start == False):
        handle_events()
        clear_canvas()
        mainback.draw()
        update_canvas()
        delay(0.08)

    #클래스 선언
    global hero
    hero = Hero()
    rabbit = Rabbit()
    rabbit_group = [Rabbit() for i in range(600)]
    land = Land()
    wood = Wood()
    global torch
    torch = Torch()
    global fire
    fire = Fire()
    eskimo = Eskimo()
    attack_fire = Attack_fire()
    attack_fire_group = [Attack_fire() for i in range(100)]
    background = BackGround()
    global ui
    ui = Ui()
    firewood = Firewood()
    firewood_group = [Firewood() for i in range(600)]

    #변수 선언
    rabbit_group_counter = 0
    rabbit_group_collision_counter = 0
    attack_group_counter = 0
    attack_group_update_counter = 0
    attack_group_collision_counter = 0
    rabbit_alive_counter = 0
    attack_group_alive_check = False
    attack_group_alive_counter = 0
    attack_group_limit = 20
    rabbit_group_draw_counter = 0
    firewood_num_counter = 0
    firewood_num_update_counter = 0
    firewood_collide_counter = 0
    rabbit_group_counter2 = 0
    rabbit_jump = False
    rabbit_num = 10
    firewood_num = 10
    rack_block = 0
    eskimo_counter = 0


    global running
    running = True



    while running:
        #핸들 이벤트
        handle_events()

        #업데이트
        hero.update()
        background.update()
        land.update()
        wood.update()
        fire.update()
        torch.update()
        eskimo.update()
        ui.update(hero.x, hero.y, hero.ability)
        for rabbit in rabbit_group: # 토끼 업데이트
            if(rabbit_group_counter == rabbit_num):
                rabbit_group_counter = 0
                break
            if(rabbit.alive):
                rabbit.update()
            rabbit_group_counter += 1

        # for rabbit in rabbit_group: # 토끼 업데이트
        #     if(rabbit_group_counter2 == 1):
        #         print("%d" % rabbit.x)
        #         break
        #     rabbit_group_counter2 += 1

        for attack_fire in attack_fire_group: # 공격불 업데이트
            if(attack_group_update_counter == hero.attack_num):
                attack_fire.init_direction()
                attack_fire.alive = True # 공격불이 활성화 됨
                attack_fire.init_fire()
                attack_group_update_counter = 0
                break
            if(attack_fire.alive):
                attack_fire.update()
            attack_group_update_counter += 1

        for firewood in firewood_group: # 장작 업데이트
            if(firewood_num_update_counter == firewood_num):
                firewood_num_update_counter = 0
                break
            firewood.update()
            firewood_num_update_counter += 1

        #함수
        for rabbit in rabbit_group: #토끼와 히어로의 충돌체크
            if(rabbit_group_collision_counter == rabbit_num):
                rabbit_group_collision_counter = 0
                break
            if(collision(rabbit, hero)):
                rabbit.y += 50
                mainback.hero_die = True
                mainback.die_sound()
                running = False
            rabbit_group_collision_counter += 1

        for rabbit in rabbit_group: # 토끼와 공격불의 충돌체크
            if(rack_block == rabbit_num):
                rack_block = 0
                break
            for attack_fire in attack_fire_group:
                if(attack_group_collision_counter == hero.attack_num):
                    attack_group_collision_counter = 0
                    break
                if(collision(rabbit, attack_fire) and rabbit.alive and attack_fire.alive):
                    attack_fire.alive = False
                    rabbit.alive = False
                    rabbit.die = True
                    hero.kill += 1
                attack_fire.die = False
                attack_group_collision_counter += 1
            rack_block += 1

        for attack_fire in attack_fire_group:
            if(eskimo_counter == hero.attack_num):
                eskimo_counter = 0
                break
            if(collision(eskimo, attack_fire)):
                 attack_fire.alive = False
                 eskimo.x -= 10
                 eskimo.hp -= 1
                 if(eskimo.hp == 0):
                    mainback.eskimo_die = True
                    running = False
                    mainback.win_sound()
            attack_fire.die = False
            eskimo_counter += 1
        if(collision(wood, hero)): # 나무와 주인공 충돌체크
            fire.collide = True
            if(ui.firewood_num != 0):
                fire.life += ui.firewood_num*250
                ui.firewood_num = 0
        else:
            fire.collide = False


        if(collision(eskimo, hero)): # 주인공과 에스키모 충돌체크
            mainback.hero_die = True
            running = False
            mainback.die_sound()

        for firewood in firewood_group: # 장작과 주인공 충돌체크
            if(firewood_collide_counter == firewood_num):
                firewood_collide_counter = 0
                break
            if(collision(firewood, hero) and firewood.die == False):
                ui.firewood_num += 1
                firewood.die = True
            firewood_collide_counter += 1

        for rabbit in rabbit_group: # 토끼 출현!
            if(rabbit_alive_counter == rabbit_num):
                break
            if(rabbit.die == False):
                rabbit.alive = True
                rabbit_alive_counter += 1

        if(fire.die): # 불이 꺼지면 토끼들이 마구마구 몰려온다.
            rabbit_num = 500

        for attack_fire in attack_fire_group: # 불 스킬 존재 유무
            if(attack_fire.alive):
                attack_group_alive_counter = 0
                break
            attack_group_alive_counter += 1
            if(attack_group_alive_counter == hero.attack_num):
                hero.attack_num = 0


        for attack_fire in attack_fire_group: # 화면 밖을 벗어나면 불 스킬 사망 판정
            if(attack_fire.x >= 900 or attack_fire.x <= -100):
                attack_fire.alive = False
        print("stage = %d" % background.stage)
        #스테이지
        if(hero.kill == 10 and background.stage == 1):
            print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
            rabbit_num += 20
            hero.ability += 10
            firewood_num += 5
            background.stage = 2
        if(hero.kill == 30 and background.stage == 2):
            rabbit_num += 30
            firewood_num += 10
            hero.ability += 10
            background.stage = 3
            background.stage3_music()
        if(hero.kill == 60 and background.stage == 3):
            rabbit_num += 40
            firewood_num += 15
            hero.ability += 10
            background.stage = 4
        if(hero.kill == 80 and background.stage == 4):
            rabbit_num += 50
            firewood_num += 20
            hero.ability += 10
            background.stage = 5
            eskimo.alive = True
            background.stage5_music()
        if(background.stage == 5):
            rabbit_jump = True

        if(rabbit_jump):
             for rabbit in rabbit_group:
                 rabbit.y += 5

        # print("%d" % hero.attack_num)
        print("킬 수 : %d num : %d" % (hero.kill, rabbit_num))
        clear_canvas()


        #그리기
        background.draw()
        fire.draw()
        wood.draw()
        torch.draw()
        hero.draw()
        eskimo.draw()
        # eskimo.draw_bb()
        # hero.draw_bb()
        for rabbit in rabbit_group: # 적토끼 출력
            if(rabbit_group_draw_counter == rabbit_num):
                rabbit_group_draw_counter = 0
                break
            if(rabbit.alive):
                rabbit.draw()
            rabbit_group_draw_counter += 1
            # rabbit.draw_bb()
        for attack_fire in attack_fire_group: # 공격 불 출력
            if(attack_group_counter == hero.attack_num):
                attack_group_counter = 0
                break
            if(attack_fire.alive):
                attack_fire.draw()
            # attack_fire.draw_bb()
            attack_group_counter += 1
        for firewood in firewood_group: # 장작 출력
            if(firewood_num_counter == firewood_num):
                firewood_num_counter = 0
                break
            firewood.draw()
            firewood_num_counter += 1
        land.draw()
        ui.draw()



        update_canvas()

        delay(0.06)

    while(mainback.hero_die or mainback.eskimo_die):
        handle_events()
        clear_canvas()
        mainback.draw()
        update_canvas()
        delay(0.08)



    close_canvas()
Exemplo n.º 14
0
def hovedprogram():
    #Pa grunn av usikkerhet om det fungerer pa deres maskiner kommenterer jeg det som er under ut!
    #Gjerne prov a uncomment det, da det skal finne tilgjengelige txt filer i dir deres

    #Finner pathen til dir som man er i
    # path = os.getcwd()
    # #Setter os til den directorien
    # os.chdir(path)
    # #Printer menneskesetning og space
    # print("\n")
    # print("Du har folgende txt filer i mappen: ")
    # #Sjekker hvilke filer som finnes i dir som er txt filer
    # for file in glob.glob("*.txt"):
    #     #Printer alle filene med txt filending
    #     print(file)
    #
    # print("\n")

    #Printer menneskesetning med input for a gi bruker muligheten til a velge fil
    print("Oppgi navnet paa filen med smittedata som du vil lese inn i programmet")
    fileToRead = input()
    #Apner denne filen som bruker velger
    f = open(fileToRead, "r")

    land = {}
    datoer = []
    #Gar gjennom listen
    for x in f:
        #lager et nytt element i array for hvert komma
        infoDeltOpp = x.split(",")
        #Gar gjennom listen
        for index,t in enumerate(infoDeltOpp):
            #Sjekker om anforselstegn finnes i elementet i listen
            if '"' in t:
                #Fjerner anforselstegn
                infoDeltOpp[index] = t.replace('"', '')
        #Slettes siste element i listen
        del infoDeltOpp[-1]

        #Lager dato som er forstaelig for klassen
        midl = re.compile("([a-zA-Z]+)([0-9]+)")
        mnd = midl.match(infoDeltOpp[2]).group(1)
        dag = midl.match(infoDeltOpp[2]).group(2)
        ar = int(infoDeltOpp[3])

        #Konverterer mnd til int format ved a sjekke hva de de er i tekstformat
        if mnd == "Jan":
            mnd = 1
        if mnd == "Feb":
            mnd = 2
        if mnd == "Mar":
            mnd = 3
        if mnd == "Apr":
            mnd = 4
        if mnd == "May":
            mnd = 5
        if mnd == "Jun":
            mnd = 6
        if mnd == "Jul":
            mnd = 7
        if mnd == "Aug":
            mnd = 8
        if mnd == "Sep":
            mnd = 9
        if mnd == "Oct":
            mnd = 10
        if mnd == "Nov":
            mnd = 11
        if mnd == "Dec":
            mnd = 12

        #Definerer en dato
        dato = datetime(ar, int(mnd), int(dag))

        #Sjekker om datoen finnes i listen over unike datoer
        if dato in datoer:
            #Hvis den finnes der, skal den ikke legges til i listen
            pass
        #Hvis den ikke finnes blir den lagt til i listen over unike datoer
        else:
            datoer.append(dato)

        #Henter ut koden for landet
        id = infoDeltOpp[1]
        #Sjekker om koden finnes i ordboken land
        if id in land:
            #Dersom den gjor det legges ny info om land og antall smittede til
            land[id].append([infoDeltOpp[0], infoDeltOpp[4], dato])
        else:
            #Hvis den ikke er i listen legges det til et nytt key value par med key=landskoden og value til navnet pa landet og antall smittede
            land[infoDeltOpp[1]] = [[infoDeltOpp[0], infoDeltOpp[4], dato]]

    #Gar gjennom datoer i datoer listen
    for index,datoz in enumerate(datoer):
        #Setter variabelen ar lik det man far fra a datetime konvertert
        ar = datoz.strftime("%Y")
        #Setter variabelen mnd lik det man far fra mnd datetime konvertert
        mnd = datoz.strftime("%m")
        #Setter dag lik det datetime konvertert
        dag = datoz.strftime("%d")
        #Lager datoobjekt pa datoer
        nyDato = Dato(ar,mnd,dag)
        #Setter key i datoer ordboken lik den nye datoen som er et objekt
        datoer[index] = nyDato

    #Leser fra land ordboken
    for key,value in land.items():
        #Setter navn lik obj i value
        navn = value[0][0]
        #Lager et landobjekt med key og navnet til landet
        landObj = Land(key,navn)
        #Gar gjennom elementene i value
        for elements in value:
            #Gar gjennom datoene i datoer
            for dates in datoer:
                #Sjekker om datoen i ordboken er lik som datoen til objektet
                if elements[2] == dates.hentDato():
                    #Hvis den er lik settes den lik datoobjektet
                    elements[2] = dates
            #Lager et smitteobjekt med dato og smittetall
            smittede = Smitte(elements[2],int(elements[1]))
            #Henter ut info om objektet
            datoSmittede,antallSmittede = smittede.hentInfo()
            #Legger til info om smitte i landobjektet
            landObj.addSmittede(antallSmittede)
            #Setter elementet lik objektet smitte
            elements[1] = smittede
            #Setter landinfo lik landobjektet
            elements[0] = landObj
    #Printer menyvalgene
    #Den ene funksjonen er ikke utarbeidet og derfor ikke aktiv i koden
    print("Trykk c for a skrive ut data for et land du velger")
    print("Trykk d for a skrive ut smittedata for alle land pa en gitt dato")
    print("Trykk g for a opprette en region med smittedata for en gruppe land")
    print("Trykk m for a finne hvilken dato smitten okte mest for en region")
    # print("Trykk n for a legge til ny info i databasen")
    print("Trykk p for a plotte smittegrafene for et gitt land")
    print("Trykk q for a avslutte")
    print("Trykk r for a fjerne alle smitteobjekter med smittetall 0 som kommer tidligere enn forste dag med smitte")
    print("Trykk w for a skrive ut data pa fil som kan brukes som input til programmet")
    #Lager en var som holder den brukeren skriver inn
    userChoice = input()
    #Dersom userChoice ikke er q gar vi inn i whileloopen
    while userChoice != "q":
        #Sjekker om userChoice er d
        if userChoice == "d":
            #Dersom den er d printer vi brukerinput for a fa aar,mnd og dag
            print("Skriv inn aar i tall: ")
            userAr = input()
            print("Skriv inn mnd i tall: ")
            userMnd = input()
            print("Skriv inn dag i tall: ")
            userDag = input()
            #Kaller funksjonen hentSmittedeDato og gir den landordboken og brukerinput
            hentSmittedeDato(land, userAr, userMnd, userDag)
        #Sjekker om userChoice er r
        if userChoice == "r":
            #Kaller funksjonen fjernSmitteTall
            fjernSmitteTall(land)
        #Sjekker om userChoice er g
        if userChoice == "g":
            #Dersom den er g, printer vi input til brukeren
            print("Skriv inn navn paa regionen: ")
            userRegion = input()
            print("Skriv inn kode for regionen: ")
            userKode = input()
            print("Skriv inn antall land du vil legge til: ")
            numOfLand = input()

            #Definerer en liste som skal holde landene som skal legges til i regionen
            landListe = []
            #Printer menneskesetning som forteller hvordan de skal legges inn
            print("Skriv inn navn: ")
            print("VIKITG: SKRIV LANDET PA ENGELSK")
            #Lager for loop som kjorer x antall basert pa brukerinput
            for index,x in enumerate(range(0,int(numOfLand))):
                #Lager input for hvilke land som skal legges til
                print("Land #" + repr(index + 1) + ":")
                landInput = input()
                #Legger til stringen i listen landListe
                landListe.append(landInput)
            #Kaller funksjonen opprettRegion som far landordboken og userinput
            opprettRegion(land, userRegion, userKode, landListe)
        #Sjekker om userChoice er m
        if userChoice == "m":
            #Printer space
            print("\n")
            #Printer menneskesetning
            print("Her er listen over regioner")
            #Gar gjennom regionordboken
            for key,value in region.items():
                #Printer liste over regioner
                print(" - " + value.hentRegionKode())
            #Printer space
            print("\n")
            #Printer userinput for a velge regionskode
            print("Skriv inn kode pa regionen du vil se statistikk om")
            userKode = input()
            #Kaller findHighest funksjonen og gir den regionskoden som bruker oppgir
            findHighest(userKode)
        #Sjekker om userChoice er w
        if userChoice == "w":
            #Kaller funksjonen skrivTilFil
            skrivTilFil(land)
        #Sjekker om userChoice er c
        if userChoice == "c":
            #Printer menneskesetning som gir info om hvordan soke pa land
            print("Skriv inn landet du vil hente data om: ")
            print("VIKITG: SKRIV LANDET PA ENGELSK")
            userLand = input()
            #Kaller funksjonen skrivUtLand og gir ordboken land og userinput som argument
            skrivUtLand(land, userLand)
        #Sjekker om userChoice er p
        if userChoice == "p":
            #Printer menneskesetning om hvordan land som skal plottes
            print("Skriv inn landet du vil plotte")
            print("VIKITG: SKRIV LANDET PA ENGELSK")
            userLand = input()
            #Kaller pa funksjonen plotLand og gir userinput og ordboken
            plotLand(land,userLand)
        #Printer menyvalgene
        #Den ene funksjonen er ikke utarbeidet og derfor ikke aktiv i koden
        print("Trykk c for a skrive ut data for et land du velger")
        print("Trykk d for a skrive ut smittedata for alle land pa en gitt dato")
        print("Trykk g for a opprette en region med smittedata for en gruppe land")
        print("Trykk m for a finne hvilken dato smitten okte mest for en region")
        # print("Trykk n for a legge til ny info i databasen")
        print("Trykk p for a plotte smittegrafene for et gitt land")
        print("Trykk q for a avslutte")
        print("Trykk r for a fjerne alle smitteobjekter med smittetall 0 som kommer tidligere enn forste dag med smitte")
        print("Trykk w for a skrive ut data pa fil som kan brukes som input til programmet")
        #Oppdaterer userChoice med det nye valget til brukeren
        userChoice = input()
Exemplo n.º 15
0
def draw_highlighted_terrain(screen: pg.Surface,
                             terrain: Dict[te.Terrain,
                                           Terrain_package], land: ld.Land):
    for t, t_info in terrain.items():
        pg.draw.polygon(screen, t_info.color, land.polygon_corners(t), width=0)
Exemplo n.º 16
0
            Vehicle(arena, randint(100, 280), int((i * 30) + 280), 0, i)
        )  #paramentro x porto in un range da 150 a 480 (+ 20% del canvas) in modo da permettere alla rana di muoversi almeno nei primi momenti di gioco
        veicoli.append(
            Vehicle(arena, randint(350, 480), int((i * 30) + 280), 0, i))
        veicoli.append(
            Vehicle(arena, randint(530, 680), int((i * 30) + 280), 0, i))
    else:
        veicoli.append(
            Vehicle(arena, randint(100, 280), int((i * 30) + 280), 1, i))
        veicoli.append(
            Vehicle(arena, randint(350, 480), int((i * 30) + 280), 1, i))
        veicoli.append(
            Vehicle(arena, randint(530, 680), int((i * 30) + 280), 1, i))
frog.append(Frog(arena, 250, 440))
fiume = Fiume(arena, 0, 80)
land.append(Land(arena, 0, 0, 600, 44))
land.append(Land(arena, 0, 44, 42, 30))
land.append(Land(arena, 90, 44, 80, 30))
land.append(Land(arena, 216, 44, 80, 30))
land.append(Land(arena, 343, 44, 80, 30))
land.append(Land(arena, 472, 44, 80, 30))
land.append(Land(arena, 600, 44, 40, 30))
score = [0, 0, 0, 0, 0]
playgame = False


def update():
    global playgame
    if (frog[0].getdeath() == 3):
        pygame.mixer.music.pause()
        g2d.fill_canvas((0, 0, 0))
Exemplo n.º 17
0
TANK_COLOR_P2 = (219, 163, 82)
SHELL_COLOR = (255, 255, 255)
TEXT_COLOR = (255, 255, 255)

# Timer used to create delays before action (prevent accidental button press)
game_timer = 0

# Tank 1 = Left
tank1 = Tank("left", TANK_COLOR_P1)
# Tank 2 = Right
tank2 = Tank("right", TANK_COLOR_P2)

# Only fire one shell at a time, a single shell object can be used for both player 1 and player 2
shell = Shell(SHELL_COLOR)

ground = Land(GROUND_COLOR, (WIDTH, HEIGHT))

# Get positions of tanks from ground generator
tank1.set_position(ground.get_tank1_position())
tank2.set_position(ground.get_tank2_position())


def draw():
    global game_state
    screen.fill(SKY_COLOR)
    ground.draw(screen)
    tank1.draw(screen)
    tank2.draw(screen)
    if (game_state == "player1" or game_state == "player1fire"):
        screen.draw.text("Player 1\nPower " + str(tank1.get_gun_power()) + "%",
                         fontsize=30,
Exemplo n.º 18
0
def init():
    global gameOver
    global gameWin
    gameOver = False
    gameWin = False

    global dictOfCards
    global heroes
    global decks
    dictOfCards = {}
    heroes = []
    decks = {}

    dictOfCards['Eowyn'] = Hero('Eowyn', 1, 1, 3, 4, 'Spirit', 9)
    dictOfCards['Eleanor'] = Hero('Eleanor', 1, 2, 3, 1, 'Spirit', 7)
    dictOfCards['Thalin'] = Hero('Thalin', 2, 2, 4, 1, 'Tactics', 9)
    dictOfCards['Wandering Took'] = Ally('Wandering Took', 1, 1, 2, 1,
                                         'Spirit', 2)
    dictOfCards['Lorien Guide'] = Ally('Lorien Guide', 1, 1, 2, 0, 'Spirit', 3)
    dictOfCards['Northern Tracker'] = Ally('Northern Tracker', 2, 2, 3, 1,
                                           'Spirit', 4)
    dictOfCards['Veteran Axehand'] = Ally('Veteran Axehand', 2, 1, 2, 0,
                                          'Tactics', 2)
    dictOfCards['Gondorian Spearman'] = Ally('Gondorian Spearman', 1, 1, 1, 0,
                                             'Tactics', 2)
    dictOfCards['Horseback Archer'] = Ally('Horseback Archer', 2, 1, 2, 0,
                                           'Tactics', 3)
    dictOfCards['Beorn'] = Ally('Beorn', 3, 3, 6, 1, 'Tactics', 6)
    dictOfCards['Gandalf'] = Ally('Gandalf', 4, 4, 4, 4, 'Neutral', 5)

    dictOfCards['Flies and Spiders'] = Quest('Flies and Spiders',
                                             'Passage through Mirkwood', 8)
    dictOfCards['A fork in the road'] = Quest('A fork in the road',
                                              'Passage through Mirkwood', 2)
    dictOfCards['Beorns Path'] = Quest('Beorns Path',
                                       'Passage through Mirkwood', 10)

    dictOfCards['Dol Guldur Orcs'] = Enemy('Dol Guldur Orcs', 2, 0, 3, 10, 2)
    dictOfCards['Chieftan Ufthak'] = Enemy('Chieftan Ufthak', 3, 3, 6, 35, 2)
    dictOfCards['Dol Guldur Beastmaster'] = Enemy('Dol Guldur Beastmaster', 3,
                                                  1, 5, 35, 2)
    dictOfCards['Necromancers Pass'] = Land('Necromancers Pass', 3, 2)
    dictOfCards['Enchanted Stream'] = Land('Enchanted Stream', 2, 2)
    dictOfCards['Forest Spider'] = Enemy('Forest Spider', 2, 1, 4, 25, 2)
    dictOfCards['Old Forest Road'] = Land('Old Forest Road', 1, 3)
    dictOfCards['East Bight Patrol'] = Enemy('East Bight Patrol', 3, 1, 2, 5,
                                             3)
    dictOfCards['Black Forest Bats'] = Enemy('Black Forest Bats', 1, 0, 2, 15,
                                             1)
    dictOfCards['Forest Gate'] = Land('Forest Gate', 2, 4)
    dictOfCards['King Spider'] = Enemy('King Spider', 3, 1, 3, 20, 2)
    dictOfCards['Hummerhorns'] = Enemy('Hummerhorns', 2, 0, 3, 40, 1)
    dictOfCards['Ungoliants Spawn'] = Enemy('Ungoliants Spawn', 5, 2, 9, 32, 3)
    dictOfCards['Great Forest Web'] = Land('Great Forest Web', 2, 2)
    dictOfCards['Mountains of Mirkwood'] = Land('Mountains of Mirkwood', 2, 3)

    heroes.append(dictOfCards['Eowyn'])
    heroes.append(dictOfCards['Eleanor'])
    heroes.append(dictOfCards['Thalin'])

    playerDeck = RegularDeck('Player Deck')
    playerDeck.addCard(dictOfCards['Wandering Took'], 3)
    playerDeck.addCard(dictOfCards['Lorien Guide'], 3)
    playerDeck.addCard(dictOfCards['Northern Tracker'], 3)
    playerDeck.addCard(dictOfCards['Veteran Axehand'], 3)
    playerDeck.addCard(dictOfCards['Gondorian Spearman'], 3)
    playerDeck.addCard(dictOfCards['Horseback Archer'], 3)
    playerDeck.addCard(dictOfCards['Beorn'], 1)
    playerDeck.addCard(dictOfCards['Gandalf'], 3)
    decks['Player Deck'] = playerDeck

    questDeck = QuestDeck('Passage through Mirkwood')
    questDeck.addCard(dictOfCards['Flies and Spiders'], 1)
    decks['Quest Deck'] = questDeck

    # encounterDeck = RegularDeck('Encounter Deck')
    # encounterDeck.addCard(dictOfCards['Dol Guldur Orcs'], 4)
    # encounterDeck.addCard(dictOfCards['Enchanted Stream'], 4)
    # encounterDeck.addCard(dictOfCards['Black Forest Bats'], 4)
    # encounterDeck.addCard(dictOfCards['Hummerhorns'], 4)
    # encounterDeck.addCard(dictOfCards['Old Forest Road'], 4)
    # encounterDeck.addCard(dictOfCards['Forest Spider'], 4)
    # encounterDeck.addCard(dictOfCards['East Bight Patrol'], 4)
    # decks['Encounter Deck'] = encounterDeck

    # ---------------- Full Version -----------------------------

    # questDeck = QuestDeck('Passage through Mirkwood')
    # questDeck.addCard(dictOfCards['Flies and Spiders'], 1)
    # questDeck.addCard(dictOfCards['A fork in the road'], 1)
    # questDeck.addCard(dictOfCards['Beorns Path'], 1)
    # decks['Quest Deck'] = questDeck

    encounterDeck = RegularDeck('Encounter Deck')
    encounterDeck.addCard(dictOfCards['Dol Guldur Orcs'], 3)
    encounterDeck.addCard(dictOfCards['Chieftan Ufthak'], 1)
    encounterDeck.addCard(dictOfCards['Dol Guldur Beastmaster'], 2)
    encounterDeck.addCard(dictOfCards['Necromancers Pass'], 2)
    encounterDeck.addCard(dictOfCards['Enchanted Stream'], 2)
    encounterDeck.addCard(dictOfCards['Forest Spider'], 4)
    encounterDeck.addCard(dictOfCards['Old Forest Road'], 2)
    encounterDeck.addCard(dictOfCards['East Bight Patrol'], 1)
    encounterDeck.addCard(dictOfCards['Black Forest Bats'], 1)
    encounterDeck.addCard(dictOfCards['Forest Gate'], 2)
    encounterDeck.addCard(dictOfCards['King Spider'], 2)
    encounterDeck.addCard(dictOfCards['Hummerhorns'], 1)
    encounterDeck.addCard(dictOfCards['Ungoliants Spawn'], 1)
    encounterDeck.addCard(dictOfCards['Great Forest Web'], 2)
    encounterDeck.addCard(dictOfCards['Mountains of Mirkwood'], 3)
    decks['Encounter Deck'] = encounterDeck
Exemplo n.º 19
0
class Tuner(QtGui.QWidget):
    def __init__(self, host="localhost", port=6499):
        super(Tuner, self).__init__()
        self.default_title = "Aura Tasks"
        #self.chirp = None
        #self.circle = None
        #self.land = None
        self.initUI()
        self.load(host=host, port=port)
        self.clean = True

    def initUI(self):
        self.setWindowTitle( self.default_title )
        layout = QtGui.QVBoxLayout()
        self.setLayout(layout)

        # Main work area
        self.tabs = QtGui.QTabWidget()
        layout.addWidget( self.tabs )

        #self.overview = Overview(changefunc=self.onChange)
        #self.tabs.addTab( self.overview.get_widget(), "Overview" );

        # 'File' button bar
        file_group = QtGui.QFrame()
        layout.addWidget(file_group)
        file_layout = QtGui.QHBoxLayout()
        file_group.setLayout( file_layout )

        save = QtGui.QPushButton('Save')
        save.clicked.connect(self.save)
        file_layout.addWidget(save)

        quit = QtGui.QPushButton('Quit')
        quit.clicked.connect(self.quit)
        file_layout.addWidget(quit)

        file_layout.addStretch(1)

        self.resize(800, 700)
        self.show()

    def load(self, host="localhost", port=6499):
        print "Tuner.load " + str(port)

        # Recalibrate page
        self.recalibrate = Recalibrate(changefunc=self.onChange, host=host,
                                       port=port)
        self.tabs.addTab( self.recalibrate.get_widget(), "Recalibrate" )

        # Preflight page
        self.preflight = Preflight(changefunc=self.onChange, host=host,
                                   port=port)
        self.tabs.addTab( self.preflight.get_widget(), "Preflight" )

        # Launch page
        self.launch = Launch(changefunc=self.onChange, host=host, port=port)
        self.tabs.addTab( self.launch.get_widget(), "Launch" )

        # Circle hold page
        self.circle = Circle(changefunc=self.onChange, host=host, port=port)
        self.tabs.addTab( self.circle.get_widget(), "Circle" )

        # Chirp page
        self.chirp = Chirp(changefunc=self.onChange, host=host, port=port)
        self.tabs.addTab( self.chirp.get_widget(), "Chirp" )

        # Land page
        self.land = Land(changefunc=self.onChange, host=host, port=port)
        self.tabs.addTab( self.land.get_widget(), "Land" )

    def save(self):
        print "called for save, but does nothing yet"

    def quit(self):
        global data_fetcher_quit
        data_fetcher_quit = True
        QtCore.QCoreApplication.instance().quit()

    def onChange(self):
        #print "parent onChange() called!"
        #result = self.rebuildTabNames()
        #if result:
        #    self.rebuildWingLists()
        self.clean = False

    def isClean(self):
        return self.clean

    def setClean(self):
        self.clean = True
Exemplo n.º 20
0
# player2fire - player 2 fired
# game_over_1 / game_over_2 - show who won 1 = player 1 won etc.
game_state = "player1"

# switch button mode from angle to power
key_mode = "angle"

# Tank 1 = Left
tank1 = Tank(display, "left", TANK_COLOR_P1)
# Tank 2 = Right
tank2 = Tank(display, "right", TANK_COLOR_P2)

# Only fire one shell at a time, a single shell object can be used for both player 1 and player 2
shell = Shell(display, SHELL_COLOR)

ground = Land(display, GROUND_COLOR)


def run_game():
    global key_mode, game_state

    while True:
        ## Draw methods
        display.set_pen(*SKY_COLOR)
        display.clear()
        ground.draw()
        tank1.draw()
        tank2.draw()

        if (game_state == "player1fire" or game_state == "player2fire"):
            shell.draw()
Exemplo n.º 21
0
class Tuner(QtGui.QWidget):
    def __init__(self, host="localhost", port=6499):
        super(Tuner, self).__init__()
        self.default_title = "Aura Tasks"
        #self.chirp = None
        #self.circle = None
        #self.land = None
        self.initUI()
        self.load(host=host, port=port)
        self.clean = True

    def initUI(self):
        self.setWindowTitle(self.default_title)
        layout = QtGui.QVBoxLayout()
        self.setLayout(layout)

        # Main work area
        self.tabs = QtGui.QTabWidget()
        layout.addWidget(self.tabs)

        #self.overview = Overview(changefunc=self.onChange)
        #self.tabs.addTab( self.overview.get_widget(), "Overview" );

        # 'File' button bar
        file_group = QtGui.QFrame()
        layout.addWidget(file_group)
        file_layout = QtGui.QHBoxLayout()
        file_group.setLayout(file_layout)

        save = QtGui.QPushButton('Save')
        save.clicked.connect(self.save)
        file_layout.addWidget(save)

        quit = QtGui.QPushButton('Quit')
        quit.clicked.connect(self.quit)
        file_layout.addWidget(quit)

        file_layout.addStretch(1)

        self.resize(800, 700)
        self.show()

    def load(self, host="localhost", port=6499):
        print "Tuner.load " + str(port)

        # Calibrate page
        self.calibrate = Calibrate(changefunc=self.onChange,
                                   host=host,
                                   port=port)
        self.tabs.addTab(self.calibrate.get_widget(), "Calibrate")

        # Preflight page
        self.preflight = Preflight(changefunc=self.onChange,
                                   host=host,
                                   port=port)
        self.tabs.addTab(self.preflight.get_widget(), "Preflight")

        # Launch page
        self.launch = Launch(changefunc=self.onChange, host=host, port=port)
        self.tabs.addTab(self.launch.get_widget(), "Launch")

        # Circle hold page
        self.circle = Circle(changefunc=self.onChange, host=host, port=port)
        self.tabs.addTab(self.circle.get_widget(), "Circle")

        # Chirp page
        self.chirp = Chirp(changefunc=self.onChange, host=host, port=port)
        self.tabs.addTab(self.chirp.get_widget(), "Chirp")

        # Land page
        self.land = Land(changefunc=self.onChange, host=host, port=port)
        self.tabs.addTab(self.land.get_widget(), "Land")

    def save(self):
        print "called for save, but does nothing yet"

    def quit(self):
        QtCore.QCoreApplication.instance().quit()

    def onChange(self):
        #print "parent onChange() called!"
        #result = self.rebuildTabNames()
        #if result:
        #    self.rebuildWingLists()
        self.clean = False

    def isClean(self):
        return self.clean

    def setClean(self):
        self.clean = True
Exemplo n.º 22
0
                        default=False,
                        help="logger level DEBUG")
    parser.add_argument("-g",
                        "--generate_data",
                        action="store_true",
                        default=False,
                        help="generate data files")
    parser.add_argument("-i",
                        "--generate_images",
                        action="store_true",
                        default=False,
                        help="generate corresponding images (heightmaps, ...)")
    parser.add_argument("-m",
                        "--generate_map",
                        choices=["topography", "temperature", "humidity"],
                        default="",
                        help="generate map")
    parser.add_argument("-s",
                        "--map_size",
                        type=int,
                        default=1024,
                        help="map size")
    args = parser.parse_args()
    # log
    log_level = logging.DEBUG if args.show_debug_info else logging.INFO
    logging.basicConfig(level=log_level)
    log.info("Land Creator")
    # land
    land = Land()
    land.execute(args)
Exemplo n.º 23
0
def land_operation():
    import land
    from land import Land
    _task = Land()
    _task.start()
Exemplo n.º 24
0
class Villager(Image, threading.Thread):

    lock = threading.RLock()
    # for testing purpose only want to create one leader
    leader_taken = False

    def __init__(self, image, position, villager_id, font, listener,
                 current_leader, skill_images):
        self.role = Role.FOLLOWER
        self.listener = listener
        self.current_leader = current_leader
        self.leadership_term = 0
        # render shouting
        self.message_count = 1
        # for testing to only create one leader
        self.skills = []
        self.skill_adding_list = []
        self.max_health = Constant.VILLAGER_MAX_HP
        self.current_health = self.max_health
        self.current_message = ""
        self.message_countdown = 0
        self.learned_skill_names = []
        self.turning_learned_skills_list = []
        self.dead = False
        self.dead_message_sent = False
        width, height = image.get_rect().size
        center_x, center_y = position
        super().__init__(image, center_x, center_y, height, width)
        self.villager_id = villager_id
        self.font = font
        self.attacked = False
        self.item = []
        self.attack = None

        self.land = Land(self, Constant.LAND_SIZE)

        self.house = None
        self.build_house_countdown = Constant.BUILD_HOUSE_COUNT_DOWN

        threading.Thread.__init__(self)

        self.attack_probability = 0.5
        self.attack_display_count_down = Constant.ATTACK_DISPLAY_COUNT_DOWN
        self.attack_display_count_down_const = Constant.ATTACK_DISPLAY_COUNT_DOWN
        self.attacked = False
        self.attack_power = 1

        self.skill_images = skill_images

    def pickTile(self, tile):
        """
        
        Check which tile is clicked by mouse, and applied its benefits to Villager
        
        :param tile: Tile 
        :return: 
        """
        if tile.mature:
            if tile.tile_type == Constant.TILE_TYPE_PLANT:
                self.current_health_up_with_amount(
                    Constant.PLANT_HEALTH_INCREASE)
            elif tile.tile_type == Constant.TILE_TYPE_ANIMAL:
                self.current_health_up_with_amount(
                    Constant.ANIMAL_HEALTH_INCREASE)
            tile.un_mature()

    def addHouse(self):
        """
        
        Add a house Object to Villager
         
        """
        self.house = House(self.x, self.y)

    # armour
    def addItemToLeftHand(self, image, item_name, image_scale):
        """
        
        Adding a item to the left hand side of the villager
        
        :param image: Image 
        :param item_name:  str
        :param image_scale: int
        :return: 
        """
        width, height = image.get_rect().size
        temp_item_center_x = self.x + width * image_scale // 2
        temp_item_center_y = self.y + width * image_scale
        temp_item = Item(image, temp_item_center_x, temp_item_center_y,
                         item_name, image_scale)
        self.item.append(temp_item)

    # sword
    def addItemToRightHand(self, image, item_name, image_scale):
        """

        Adding a item to the right hand side of the villager

        :param image: Image 
        :param item_name:  str
        :param image_scale: int
        :return: 
        """
        width, height = image.get_rect().size
        temp_item_center_x = self.x - width * image_scale
        temp_item_center_y = self.y
        temp_item = Item(image, temp_item_center_x, temp_item_center_y,
                         item_name, image_scale)
        self.item.append(temp_item)

    def being_attacked(self, hp_decrement):
        """
        
        if villager is attcked set the hp down
        
        :param hp_decrement: int
        
        """
        self.current_health_down_with_amount(hp_decrement)

    def add_skill(self, skill_name):
        """
        
        Add skill Object to player's skill list
        
        :param skill_name: str 
         
        """
        skill_num = len(self.skills)
        image = self.skill_images[skill_name]

        # each row render four skill, then go up
        one_skill = Skill(
            skill_name, image, self.x - self.width / 2 -
            ((image.get_rect().size)[0] * Constant.SKILL_IMAGE_SCALE_VILLAGER)
            / 2, (self.y + self.height / 2) - (int(skill_num) * int(
                (image.get_rect().size)[1] *
                Constant.SKILL_IMAGE_SCALE_VILLAGER)),
            Constant.SKILL_IMAGE_SCALE_VILLAGER, False)
        self.skills.append(one_skill)

    def run(self):
        while (not self.dead) and (not self.listener.stopped):
            # consuming the parsed JSON message from the queue
            request = self.listener.request_queue.get()

            request_type = request[Constant.MESSAGE_TYPE]
            # according to the type of the request applying corresponding methods to villager
            if request_type == Constant.VILLAGER_DEAD:
                self.dead = True
                continue
            if request_type == Constant.APPEND and self.role == Role.LEADER:
                if not request[Constant.NEW_ENTRIES]:
                    self.reclaim_authority()
            elif request_type == Constant.LEADERSHIP:
                self.set_leadership(request)
            elif request_type == Constant.REQUEST_VOTE:
                self.set_candidate(request)
            elif request_type == Constant.REQUEST_VOTE_REPLY:
                self.vote(request)
            elif request_type == Constant.REQUEST_COMMAND_ACK and self.role == Role.LEADER:
                self.leader_receive_learn(request)
            elif request_type == Constant.APPEND_REPLY:
                self.learning_skill(request)
            elif request_type == Constant.COMMIT_INDEX:
                self.learned_skill(request)
            if self.current_health == 0:
                debug_print("Villager" + str(self.villager_id) + " is dead")
                self.dead = True

        if self.listener.stopped:
            print(str(self.villager_id) + "'s listener is dead")
            self.dead = True
        if self.dead:
            # if dead send the JSON to cooresponding remote Raft peer to ask it to terminate
            data = {
                Constant.MESSAGE_TYPE: "villager_killed",
                Constant.PEER_ID: self.listener.peer_id
            }
            try:
                self.listener.socket.sendall(
                    str.encode(json.dumps(data) + "\n"))
                print("villager killed message sent")
            except ConnectionResetError:
                print("connection dead")
            print("villager killed message sent")
            self.listener.stop_listener()
            self.dead_message_sent = True

    def reclaim_authority(self):
        """
        Display a dialgue box to show the string 'I'm the leader'
        
        """
        self.set_message(Constant.AUTHORITY_MESSAGE)

    def set_leadership(self, request):
        """
        
        trying to set the leader by this leadership request dictionary
        
        :param request: dict
        """
        term = request[Constant.SENDER_TERM]
        # if there is still a leader and the term number of JSON messag is smaller than
        # current term ignore this outdated leader messge
        if self.current_leader and self.current_leader.leadership_term > term:
            return
        self.role = Role.LEADER
        self.leadership_term = term
        self.set_message(Constant.NEW_LEADER_MESSAGE)

    def set_candidate(self, request):
        """
        
        set villager to candidate by this request_vote request
        
        :param request: dict
        """
        term = request[Constant.SENDER_TERM]
        # abort the outdated request_vote message
        if self.current_leader and self.current_leader.leadership_term > term:
            return
        self.role = Role.CANDIDATE
        self.set_message(Constant.CANDIDATE_MESSAGE)

    def vote(self, request):
        term = request[Constant.SENDER_TERM]
        if self.current_leader and self.current_leader.leadership_term > term:
            return
        vote_for = request[Constant.VOTE_PEER_ID][4:]
        debug_print(type(request[Constant.VOTE_GRANTED]))
        if request[Constant.VOTE_GRANTED] == True:
            self.set_message(Constant.VOTE_MESSAGE.format(vote_for))

    def leader_receive_learn(self, request):
        skill_name = request[Constant.REQUEST_COMMAND_LIST][0]
        index = int(request[Constant.INDEX])
        if index == len(self.skills):
            self.add_skill(skill_name)
            while self.skill_adding_list:
                length = len(self.skills)
                if self.skill_adding_list[0][0] == length:
                    skill = self.skill_adding_list.pop(0)
                    self.add_skill(skill[1])
                else:
                    break
        elif index > len(self.skills):
            self.skill_adding_list.append((index, skill_name))
            self.skill_adding_list.sort()

    def learning_skill(self, request):
        result = request[Constant.APPEND_RESULT]
        if result and self.current_leader:
            index = int(request[Constant.LAST_LOG_INDEX])
            if (index >= len(self.skills)) and (index < len(
                    self.current_leader.skills)):
                for i in range(len(self.skills), index + 1):
                    self.add_skill(self.current_leader.skills[i].skill_name)

    def learned_skill(self, request):
        debug_print("in learned_skill")
        if not request:
            while self.turning_learned_skills_list and self.turning_learned_skills_list[
                    0][0] == len(self.learned_skill_names):

                skill = self.turning_learned_skills_list.pop(0)
                self.learned_skill(skill[1])
            return
        index = int(request[Constant.INDEX])
        debug_print("index is" + str(index))
        debug_print("skills: ")
        debug_print(self.skills)

        if (index < len(self.skills)) and (index == len(
                self.learned_skill_names)):
            skill_name = self.skills[index].skill_name
            debug_print("skill name: " + skill_name)
        else:
            while self.turning_learned_skills_list and self.turning_learned_skills_list[
                    0][0] == len(self.learned_skill_names):
                skill = self.turning_learned_skills_list.pop(0)
                self.learned_skill(skill[1])
            self.turning_learned_skills_list.append((index, request))
            self.turning_learned_skills_list.sort()
            debug_print("returned in else")
            return
        if skill_name not in Constant.SKILLS:
            debug_print("not in skills")
            return
        if skill_name == Constant.ARMOUR:
            self.addItemToLeftHand(ConstantImage.ARMOUR_IMAGE_SPRITE,
                                   Constant.ITEM_NAME_ARMOUR,
                                   Constant.ARMOUR_IMAGE_SCLAE)
        elif skill_name == Constant.SWORD:
            self.addItemToRightHand(ConstantImage.SWORD_IMAGE_SPRITE,
                                    Constant.ITEM_NAME_SWORD,
                                    Constant.SWORD_IMAGE_SCALE)
        elif skill_name == Constant.ANIMAL:
            for tile in self.land.tiles:
                if tile.tile_type == Constant.TILE_TYPE_ANIMAL:
                    tile.display_plant_or_animal = True
        elif skill_name == Constant.PLANT:
            for tile in self.land.tiles:
                if tile.tile_type == Constant.TILE_TYPE_PLANT:
                    tile.display_plant_or_animal = True
        elif skill_name == Constant.HOUSE:
            self.addHouse()
        self.skills[index].greyed = False
        self.skills[index].applied = True
        debug_print("set skill greyed false")
        self.learned_skill_names.append(skill_name)

    def set_message(self, message):
        self.current_message = message
        self.message_countdown = Constant.MESSAGE_TIME

    def max_health_up(self):
        self.max_health += 1

    def max_health_down(self):
        self.max_health -= 1

    def current_health_up(self):
        self.current_health += 1

    def current_health_down(self):
        self.current_health -= 1

    def current_health_up_with_amount(self, hp_increment):
        self.current_health += hp_increment
        if self.current_health > self.max_health:
            self.current_health = self.max_health

    def attack_monster_or_not(self, monster):

        if (Constant.SWORD not in self.learned_skill_names) or self.attacked or \
                (Constant.SWORD in self.learned_skill_names):
            return

        self.attacked = random.random() >= self.attack_probability

        if self.attacked and self.attack_power > 0:
            monster.set_attack(self.attack_power)
            self.attack = AttackAnimation(
                ConstantImage.VILLAGER_ATTACK_IMAGE_SPRITE, monster.x,
                monster.y, Constant.VILLAGER_ATTACK_IMAGE_SCALE)
            self.attack_display_count_down = self.attack_display_count_down_const

        else:
            self.attacked = False

    def current_health_down_with_amount(self, hp_decrement):

        if self.house is not None and self.house.display_house:
            self.house.house_durability_decrement_with_amount(hp_decrement)
            if self.house.current_durability <= 0:
                self.house.display_house = False
            return

        if Constant.ARMOUR in self.learned_skill_names:
            hp_decrement -= Constant.ITEM_ARMOUR_DEFEND_POWER_ADD

        if hp_decrement >= self.current_health:
            self.current_health = 0
            self.dead = True
            return
        self.current_health -= hp_decrement

    def build_house(self):
        if self.house:
            if not self.house.display_house:
                if self.build_house_countdown == Constant.BUILD_HOUSE_COUNT_DOWN:
                    self.set_message(Constant.BUILD_HOUSE_MESSAGE)
                    self.build_house_countdown -= 1
                elif self.build_house_countdown > 0:
                    self.build_house_countdown -= 1
                else:
                    self.house.display_house = True
                    self.build_house_countdown = Constant.BUILD_HOUSE_COUNT_DOWN

    def render_attack(self, screen):
        if self.attacked and self.attack_display_count_down != 0:
            self.attack.render(screen)
            self.attack_display_count_down -= 1
            if self.attack_display_count_down <= 0:
                self.attacked = False

    def render(self, screen):

        if self.house and self.house.display_house:
            self.house.render(screen)

        super().render(screen)

        for one_skill in self.skills:
            one_skill.render(screen)

        self.land.render(screen)
        name = self.font.render("Villager " + str(self.villager_id), 1,
                                Constant.BLACK)
        screen.blit(
            name, (self.x - name.get_width() // 2, self.y + self.height // 2))

        if self.role != Role.FOLLOWER:
            if self.role == Role.LEADER:
                title = "Leader"
                role = self.font.render(title, 1, Constant.BLACK)
                screen.blit(role, (self.x - role.get_width() // 2, self.y +
                                   self.height // 2 + role.get_height() + 2))

        if self.message_countdown > 0:
            message = self.font.render(self.current_message, 1, Constant.BLACK)
            screen.blit(message,
                        (self.x - message.get_width() // 2,
                         self.y - self.height // 2 - message.get_height() - 2))
            self.message_countdown -= 1

        pygame.draw.rect(
            screen, Constant.GRAY,
            pygame.Rect((self.x - self.width // 2, self.y - self.height // 2),
                        (self.width, Constant.HEAL_BAR_HEIGHT)))
        pygame.draw.rect(
            screen, Constant.RED,
            pygame.Rect((self.x - self.width // 2, self.y - self.height // 2),
                        (self.width * (self.current_health / self.max_health),
                         Constant.HEAL_BAR_HEIGHT)))

        for one_item in self.item:
            one_item.render(screen)