Example #1
0
    async def attack(self, target_p, send_message, time):
        """initates the attack from one player onto another

        :param target_p: the player that gets attacked
        :param target_name: the name of the player that gets attacked
        :param send_message: a function that can send a message to discord
        :param time: the time the attack will take
        :param attacker_msg_func: a function to privately message the attacker
        :param target_msg_func: a function to privately message the target
        :return:
        """

        target_p.messages.append(
            "**%s** made an aggressive move against you with these units:\n=============\n%s\n=============\nthey will need %s to arrive"
            % (self.owner_name, Unit.get_units_str(self.rallied_units),
               get_time_str(time * Player.unit_time_f())))

        await send_message(
            "you send out your troops:\n====================\n%s\n====================\nagainst %s\nIt will take %s"
            % (Unit.get_units_str(self.rallied_units), target_p.owner_name,
               get_time_str(time * Player.unit_time_f())))
        attack_units = self.rallied_units.copy(
        )  # self.rallied units will be reset while building the attack function and needs to be stored here

        # add an attack to the attack threads. Also give information about the attacking units for recovery and information printing
        self.attack_threads.append(
            Process(time,
                    self.build_attack_function(target_p, time),
                    "attack %s" % target_p.owner_name,
                    units=attack_units))
Example #2
0
    def test_divide(self):  # name of the method should be begin with test
        self.assertEqual(Unit.divide(10, 5), 2)
        self.assertEqual(Unit.divide(-1, 1), -1)
        self.assertEqual(Unit.divide(-1, -1), 1)

        with self.assertRaises(ValueError):
            Unit.divide(10, 0)
Example #3
0
    def test_player_creation(s):
        with s.assertRaises(ValueError):
            p = Unit.Player('Nome', Inventory.Inventory(), 0, -1, -3, -4, -5,
                            6, 7, 8)
        with s.assertRaises(ValueError):
            p = Unit.Player('Nome', Inventory.Inventory(), 1, 2, 3, 4, 5, 0, 7,
                            -8)
        with s.assertRaises(ValueError):
            p = Unit.Player('Nome', Inventory.Inventory(), 1, 2, 3, 4, 5, 6, 8,
                            8)
        p = Unit.Player('Nome', Inventory.Inventory(), 1, 2, 3, 4, 5, 6, 7, 8)

        s.assertEqual(p.name, 'Nome')
        s.assertEqual(p.max_health, 1)
        # health tem que ser no máximo max_health
        s.assertEqual(p.health, 1)
        s.assertEqual(p.attack, 3)
        s.assertEqual(p.defense, 4)
        s.assertEqual(p.agility, 5)
        s.assertEqual(p.level, 6)
        s.assertEqual(p.exp, 7)
        s.assertEqual(p.exp_to_next, 8)

        s.assertFalse(p.max_health <= 0)
        s.assertFalse(p.health <= 0)
        s.assertFalse(p.attack <= 0)
        s.assertFalse(p.defense <= 0)
        s.assertFalse(p.agility <= 0)
        s.assertFalse(p.level <= 0)
        s.assertFalse(p.exp < 0)
        s.assertFalse(p.exp_to_next <= 0)
Example #4
0
 def counter_attack(self, enemy: Unit):
     if not self.owner.is_alive():
         raise CantDoCauseDead(self.owner)
     if enemy.is_alive():
         enemy.take_damage(self.owner.dmg // 2)
     else:
         raise TargetIsDead()
def loadFromDict(fields):
    countries = [createCountry(countryInfo) for countryInfo in fields["countries"]]
    territories = [createTerritory(tInfo, countries) for tInfo in fields["territories"]]

    for info in fields["territories"]:
        territory = Util.getByName(territories, info["name"])
        territory.connections = [Util.getByName(territories, neighbour) for neighbour in info["connections"]]

    unitInfo = {unitType: UnitInfo(unitType, unitInfo) for unitType, unitInfo in fields["unitCatalogue"].items()}

    units = []
    for unitDef in fields["units"]:
        newUnit = Unit.createUnitFromDict(unitDef, unitInfo, countries, territories)
        units.append(newUnit)

    boughtUnits = []
    for unitDef in fields["buyList"]:
        newUnit = Unit.createBoughtUnitFromDict(unitDef, territories)
        boughtUnits.append(newUnit)

    board = Board(unitInfo, territories, units, countries, fields["currentPhase"], boughtUnits)
    for conflictInfo in fields["pastConflicts"]:
        conflict = Conflict.fromDict(conflictInfo, board)
        board.resolvedConflicts.append(conflict)

    board.currentCountry = Util.getByName(countries, fields["currentCountry"])
    return board
Example #6
0
 def setUp(self):
     self.Side = Battle.Side()
     self.file_path = "./Adventures/CN/units.json"
     self.unit_cav = Unit.ImportUnit(self.file_path, abbrev="Cava", amount=100)
     self.unit_sol = Unit.ImportUnit(self.file_path, abbrev="S", amount=100)
     self.unit_arc = Unit.ImportUnit(self.file_path, abbrev="Arc", amount=100)
     self.Side.add_unit(self.unit_arc)
     self.Side.add_unit(self.unit_sol)
     self.Side.add_unit(self.unit_cav)
Example #7
0
    def createSettler(self, x, y):
        """ 
		Adds a settler to be drawn on the screen at position x, y and returns a reference to this settler.
		"""
        unit = Unit(self.viewspace, self.settsurf, x, y)
        #unit.x = x
        #unit.y = y
        unit.configAnimation(True, 0, 24, 25)
        self.units.append(unit)
        return unit
Example #8
0
	def createSettler(self, x, y):
		""" 
		Adds a settler to be drawn on the screen at position x, y and returns a reference to this settler.
		"""
		unit = Unit (self.viewspace, self.settsurf, x, y)
		#unit.x = x
		#unit.y = y
		unit.configAnimation (True, 0, 24, 25)
		self.units.append(unit)
		return unit
Example #9
0
 def attack(self, enemy: Unit):
     if enemy is self.owner:
         raise AttacksItself()
     if not self.owner.is_alive():
         raise CantDoCauseDead(self.owner)
     if enemy.is_alive():
         enemy.take_damage(self.owner.dmg)
         enemy.counter_attack(self.owner)
     else:
         raise TargetIsDead()
def AddUnitAndParentsToOrganization(unit, employees, organization):
    curUnitJson = unit
    curUnit = Unit.Unit(curUnitJson["Name"], curUnitJson["Id"], None, employees, [])
    while curUnitJson["Parent"] != None:
        prevUnitJson = curUnitJson
        curUnitJson = curUnitJson["Parent"]
        curUnit.ParentId = curUnitJson["Id"]
        newUnit = Unit.Unit(curUnitJson["Name"], curUnitJson["Id"],None, [], [])
        newUnit.AddChild(curUnit)
        curUnit = newUnit
    organization.AddChain(curUnit)
    return
Example #11
0
    def draw(self):
        """
        use the values to set up the general frame and lines, fill particular zone with given colors
        """
        A = [(75, 25, 0), (50, 50, 0), (25, 75, 0), (25, 0, 75),
             (18.75, 6.25, 75), (12.5, 12.5, 75), (6.25, 18.75, 75),
             (0, 25, 75), (10, 0, 90), (5, 5, 90), (0, 10, 90)]

        Unit.TriLine(Points=[A[0], A[4]],
                     Sort='',
                     Width=1,
                     Color='black',
                     Style="-",
                     Alpha=0.7,
                     Label='').show()

        Unit.TriLine(Points=[A[1], A[9]],
                     Sort='',
                     Width=1,
                     Color='black',
                     Style="-",
                     Alpha=0.7,
                     Label='').show()

        Unit.TriLine(Points=[A[2], A[6]],
                     Sort='',
                     Width=1,
                     Color='black',
                     Style="-",
                     Alpha=0.7,
                     Label='').show()

        Unit.TriLine(Points=[A[3], A[7]],
                     Sort='',
                     Width=1,
                     Color='black',
                     Style="-",
                     Alpha=0.7,
                     Label='').show()

        Unit.TriLine(Points=[A[8], A[10]],
                     Sort='',
                     Width=1,
                     Color='black',
                     Style="-",
                     Alpha=0.7,
                     Label='').show()

        plt.xticks([])
        plt.yticks([])
Example #12
0
    def __init__(self, file_inst, file_data, file_reg, file_config, file_result):
        self.read_files(file_inst, file_data, file_reg, file_config)
        self.file_result = file_result
        self.all_inst_fetched = False
        self.current_inst = 0
        self.result = dict()
        self.register_status = dict()
        self.flush = False
        self.inst_exec_list = {}
        self.IBUS = 'FREE'
        self.DBUS = 'FREE'
        self.dbus_first_word_ctr = 0
        self.dbus_second_word_ctr = 0

        # Create All Units
        self.IF = Unit('IF',1,False)
        self.ID = Unit('ID',1,True)
        self.EXMULT = Unit('EXMULT',self.EXMULT_cycles,self.EXMULT_pipelined)
        self.EXADD = Unit('EXADD',self.EXADD_cycles,self.EXADD_pipelined)
        self.EXDIV = Unit('EXDIV',self.EXDIV_cycles,self.EXDIV_pipelined)
        self.EXIU = Unit('EXIU',1,True)
        self.EXMEM = Unit('EXMEM',self.EXINT_cycles,False)
        self.WB = Unit('WB',1,True)

        self.icache = ICache(self.ICache_cycles,self.EXINT_cycles)
        
        self.dcache = DCache(256,self.data,self.DCache_cycles,self.EXINT_cycles)
        self.dbus_access = 0
        self.bus_contention = False
Example #13
0
 def test_add_units(self):
     unit = Unit.ImportUnit(self.file_path, abbrev=self.abbrev, amount=200)
     units = []
     units.append(unit)
     units.append(unit)
     self.Side.add_units(units)
     self.assertEqual(len(self.Side.units), 2)
 def get_iteration(self, iteration):
     Side = Battle.Side()
     i = 0
     for unit in self.allowed_units:
         unit = Unit.ImportUnit(self.file_units, name=self.allowed_units[i], amount=iteration[i])
         Side.add_unit(unit)
         i += 1
Example #15
0
def main():
    pygame.init()

    Main.actors = Unit.Actor(Config.actors, Config.actorsx, Config.actorsy)
    Main.buildings = Building.Buildings(Config.actors, Config.actorsx,
                                        Config.actorsy)

    if Config.loadMap == 1:
        with open("Saves/Save.txt", "rb") as fp:
            Config.gameMap = pickle.load(fp)

    while Config.stop == 0:  # Main loop, ends if Config.stop is changed

        # take keyboard input
        if Config.gameMode == 0:
            inputEditor()
        else:
            inputGame()

        if Config.pause == 0: Main.actors.allAct()

        drawAll()  # call the draw map function
        pygame.display.update()  # update map once updated

        # game time
        tempTime = time.time() * 1000
        while tempTime < Config.frameTime + 90:
            tempTime = time.time() * 1000
            pygame.time.wait(1)  # pause for a short while
        Config.frameTime = tempTime

    # If loops exits
    pygame.quit()
    sys.exit()
Example #16
0
    def read(self):
        """
        read the Excel, then use self.show() to show the frame, then Plot points, job done~
        """
        self.show()
        self.draw()
        if ("csv" in self.name):
            raw = pd.read_csv(self.name)
        elif ("xlsx" in self.name):
            raw = pd.read_excel(self.name)
        PointLabels = []

        for i in range(len(raw)):
            
            
            
            if (raw.at[i, 'Label'] in PointLabels or raw.at[i, 'Label'] =='' ):
                TmpLabel =''
            else:
                PointLabels.append(raw.at[i, 'Label'])
                print(raw.at[i, 'Label'])
                TmpLabel = raw.at[i, 'Label']

            Unit.TriPoint((raw.at[i, 'F'], raw.at[i, 'L'], raw.at[i, 'Q']), Size=raw.at[i, 'Size'],
                         Color=raw.at[i, 'Color'], Alpha=raw.at[i, 'Alpha'], Marker=raw.at[i, 'Marker'],
                         Label=TmpLabel).show()

        self.SavePic(name= self.name)
Example #17
0
 def test_damage_multi(self):
     unit = Unit.ImportUnit(self.file_path, name=self.abbrev)
     expected = [20, 40, 60, 80, 100, 120, 140, 160, 180, 200]
     unit.set_amount(5)
     damage = unit.get_damage(total=True)
     print("Damage : " + str(damage))
     self.assertIn(damage, expected)
Example #18
0
    def key_pressed(self, key):
        self.key_states[key] = True
        print("Key ", key, " pressed.")

        if key >= 49 and key <= 57:  #numbers 1 through 9
            if self.key_states[306] == True:  #CTRL
                self.game.selection_controller.set_control_group(key - 48)
            else:
                self.game.selection_controller.get_control_group(key - 48)

        if key == 32:  #space
            x = Unit(self.game.world, 50, 50)

        if key == 27:  #escape
            self.game.selection_controller.clear_selection()

        if key == 113:  #q
            self.game.mouse_controller.currently_building = "Structure"
            print("Started building a structure.")

        if key == 122:  #z
            x = RandomMover(self.game.world, 100, 100)

        if key == 115:  #s
            self.game.selection_controller.stop()
Example #19
0
	def crossover(self,pair):
		"""
		Given two individuals, the method will split their genetic code and generate an offspring which will inherit from both parents
		"""
		pivot = random.randint(0,len(pair[0].dna)-1)
		dna = np.concatenate((pair[0].dna[0:pivot], pair[1].dna[pivot:]))
		off = U.Unit(dna)
		return off
Example #20
0
    def __init__(self, scheme, popsize, mutation=0.01, iterations=1000):
        self.scheme = scheme
        self.population = [Unit(self.scheme) for i in range(popsize)]
        self.iterations = iterations
        self.popsize = popsize
        self.mutation = mutation

        self.lastFitness = None
Example #21
0
 def test_player_methods(s):
     p = Unit.Player('Nome', Inventory.Inventory(), 3, 1, 1, 4, 5, 6, 7, 8)
     s.assertEqual(p.health, 1)
     p.heal(1)
     s.assertEqual(p.health, 2)
     p.heal(10)
     s.assertEqual(p.health, p.max_health)
     with s.assertRaises(ValueError):
         p.heal(-45)
 def test_add_unit(self):
     c_file = {}
     c_file["name"] = "1"
     c_file["file"] = "./Adventures/CN/2.json"
     camp = Adventure.ImportCamp("./Adventures/CN/units.json", c_file)
     unit = Unit.ImportUnit("./Adventures/CN/units.json", name="soldat")
     previous_len = len(camp.units)
     camp.add_unit(unit)
     self.assertEqual(len(camp.units), previous_len + 1)
Example #23
0
 async def print_units(self, author, channel):
     """prints all units a player has"""
     player = self.get_player(author)
     if not player.units:
         await self.send_message(channel, "you have no units")
         return
     units_list = Unit.get_units_str(player.units)
     await self.send_message(
         channel,
         "your units:\n================\n%s\n================" % units_list)
Example #24
0
    def __init__(self, name="qfl_MrMa.xlsx",Label=[u'Q', u'F', u'L:']):
        super().__init__()

        self.raw = ''

        self.Label = Label
        self.name=name
        for i in range(len(self.Labels)):
            self.Tags.append(Unit.Tag(Label=self.Labels[i],
                                 Location=self.TriToBin(self.Locations[i][0], self.Locations[i][1], self.Locations[i][2]),
                                 X_offset=self.Offset[i][0], Y_offset=self.Offset[i][1]))
 def __from_json(jsonObject):
     if ('FirstName' in jsonObject):
         return Employee.Employee(jsonObject["FirstName"],
                                  jsonObject["LastName"], jsonObject["Id"],
                                  jsonObject["Documents"])
     if ('ParentId' in jsonObject):
         return Unit.Unit(jsonObject["Name"], jsonObject["Id"],
                          jsonObject["ParentId"], jsonObject["Employees"],
                          jsonObject["Children"])
     if ("root" in jsonObject):
         return Organization(jsonObject["root"])
Example #26
0
    def reset(self):
        """
		Resets previous results
		"""
        self.collection = []
        for unit in range(self.pop):
            self.collection.append(self.unit_gen(self.func_set, self.var_set))

        self.generation = 0
        self.fit_record = []
        self.best = U.Unit(None)
Example #27
0
    def draw(self):
        """
        use the values to set up the general frame and lines, fill particular zone with given colors
        """

        Unit.TriLine(Points=[(85, 15, 0), (0, 3, 97)], Sort='', Width=1, Color='black', Style="-", Alpha=0.7,
                Label='').show()
        Unit.TriLine(Points=[(45, 0, 55), (0, 75, 25)], Sort='', Width=1, Color='black', Style="-", Alpha=0.7,
                Label='').show()
        Unit.TriLine(Points=[(50, 50, 0), (0, 75, 25)], Sort='', Width=1, Color='black', Style="--", Alpha=0.7,
                Label='').show()
        T0 = (85, 15, 0)
        T1 = (0, 3, 97)
        T2 = (87, 0, 13)
        T3 = (0, 63, 37)
        T4 = self.TriCross(A=[T0,T1] , B=[T2,T3])

        T2 = (87, 0, 13)
        T3 = (0, 63, 37)
        T5 = (45, 0, 55)
        T6 = (0, 75, 25)


        T7 = self.TriCross(A=[T2,T3] , B=[T5,T6])

        Unit.TriLine(Points=[T4, T7], Sort='', Width=1, Color='black', Style="--", Alpha=0.7,
                Label='').show()

        Unit.TriLine(Points=[T7, (0, 63, 37)], Sort='', Width=1, Color='black', Style=":", Alpha=0.7,
                Label='').show()

        y = 3 * np.sqrt(3) * (82 - 7.5 - np.sqrt(15)) / (18 * np.sqrt(3) - 1.5)
        z = 82 - np.power(15, 0.5)
        x = 100 - y - z

        p0 = (85, 15, 0)
        p1 = (0, 3, 97)
        p2 = (18, 0, 82)
        p3 = (0, 36, 64)

        p4 = self.TriCross(A=[p0, p1], B=[p2, p3])

        Unit.TriLine(Points=[(18, 0, 82), p4], Sort='', Width=1, Color='black', Style="-", Alpha=0.7,
                Label='').show()

        self.TriFill(P=[(100, 0, 0), (85, 15, 0), (0, 3, 97), (0, 0, 100)], Color='blue', Alpha=0.13)

        ap0 = (85, 15, 0)
        ap1 = (0, 3, 97)
        ap2 = (0, 75, 25)
        ap3 = (45, 0, 55)


        ap4 = self.TriCross(A=[ap0, ap1], B=[ap2, ap3])

        self.TriFill(P=[(0, 75, 25), (0, 3, 97), ap4], Color='red', Alpha=0.13)

        for i in self.Tags:
            i.show()
Example #28
0
    def crossover(self, pair):
        """
		Given two individuals, the method will split their genetic code and generate an offspring which will inherit from both parents
		"""
        #pdb.set_trace()
        new_element = pair[0].dna.copy()
        p1 = random.choice(new_element.serialize())

        p2_node = random.choice(pair[1].dna.serialize())
        p2 = p2_node.copy()

        p1.replace(p2)

        offspring = U.Unit(new_element)
        return offspring
Example #29
0
    def onePointCross(parent1, parent2):
        index = random.randint(1, len(parent1.values) - 2)
        child1 = Unit([[x for x in row] for row in parent1.scheme])
        child2 = Unit([[x for x in row] for row in parent1.scheme])
        p1_values = [[x for x in row] for row in parent1.values]
        p2_values = [[x for x in row] for row in parent2.values]
        child1.values = p1_values[:index] + p2_values[index:]
        child2.values = p2_values[:index] + p1_values[index:]

        return (child1, child2)
Example #30
0
 def createUnit(self, gender):
     u = Unit.Unit(gender)
     self.equip(u)
     for stat in Class._allStats:
         base = self.__dict__[stat + "Base"]
         x = base / 20
         y = (random.randint(0, 2 * x) + random.randint(0, 2 * x) -
              random.randint(0, 2 * x) - random.randint(0, 2 * x)) / 2
         u.__dict__["_" + stat] = base + x + y
         growthMod = random.gauss(1, 0.1)
         growthMod = min(1.5, growthMod)
         growthMod = max(0.5, growthMod)
         u.__dict__["_" + stat + "GrowthMod"] = growthMod
     u.incrementClassLevel(self.name)
     self.addAbilities(u)
     return u
Example #31
0
    def __init__(self, fitness_func, gene_gen, unit_gen, pop_size, mut_rate,
                 termination, func_set, var_set):
        """
		Methods:
		--------
		fitness_func:	Calculates the problem's fitness value of an individual
		gene_gen:		Generates genetic information
		unit_gen:		Generates the initial population

		Params:
		-------
		pop_size:		Population size
		mut_rate:		Mutation Rate (As the number of genes to be modified)
		termination:	Termintion Condition
		func_set:		Function Set for the internal nodes
		var_set:		Concrete values for the leaves
		
		----------------------------------------------------------------------------

		Local Sets:
		-----------
		collection:		Set of individuals being simuated
		generation:		Current generation being simulated
		best:			Individual with the best fitness overall
		best_time:		Generation in which the current best was generated
		fit_record:		Record of the fitness score from the best, worst and average
		                performers
		
		"""
        self.fitness = fitness_func
        self.gene_gen = gene_gen
        self.unit_gen = unit_gen
        self.pop = pop_size
        self.mut = mut_rate
        self.term = termination
        self.func_set = func_set
        self.var_set = var_set

        self.collection = []
        self.generation = 0

        for unit in range(pop_size):
            self.collection.append(self.unit_gen(self.func_set, self.var_set))

        self.fit_record = []
        self.best = U.Unit(None)
        self.best_time = 0
Example #32
0
    def __init__(self,
                 name="MudStone.xlsx",
                 Label=[u'Clay', u'Sand', u'Silt']):
        super().__init__()

        self.raw = ''

        self.Label = Label
        self.name = name
        for i in range(len(self.Labels)):
            self.Tags.append(
                Unit.Tag(Label=self.Labels[i],
                         Location=self.TriToBin(self.Locations[i][0],
                                                self.Locations[i][1],
                                                self.Locations[i][2]),
                         X_offset=self.Offset[i][0],
                         Y_offset=self.Offset[i][1]))
Example #33
0
    def start_turn(self):
        # Resets all units
        for unit in self.units:
            unit.quantity_not_moved = unit.quantity
            unit.quantity_moved = 0

        # Resets all cities
        for city in self.cities:
            city.selected = False
            city.done = False

        # Runs cities
        for city in self.cities:
            city.run_turn()
            # Checks if a unit was built and spawns it
            if city.soldiers >= 10:
                self.units.append(
                    Unit.Unit(list(city.pos), int(city.soldiers / 10),
                              city.owner))
                city.soldiers %= 10
Example #34
0
 def calculateFinalKilledScore(self):
     score = 0
     for u in self.units:
         score += u.getKilledCount()
     return score*50
 def test_scirun_module_ids(self):
   Unit.check_scirun_python_script_input(__file__)
    
Example #36
0
class Pipeline:
    #get all parameters from file and initialize particular pipeline
    def __init__(self, file_inst, file_data, file_reg, file_config, file_result):
        self.read_files(file_inst, file_data, file_reg, file_config)
        self.file_result = file_result
        self.all_inst_fetched = False
        self.current_inst = 0
        self.result = dict()
        self.register_status = dict()
        self.flush = False
        self.inst_exec_list = {}
        self.IBUS = 'FREE'
        self.DBUS = 'FREE'
        self.dbus_first_word_ctr = 0
        self.dbus_second_word_ctr = 0

        # Create All Units
        self.IF = Unit('IF',1,False)
        self.ID = Unit('ID',1,True)
        self.EXMULT = Unit('EXMULT',self.EXMULT_cycles,self.EXMULT_pipelined)
        self.EXADD = Unit('EXADD',self.EXADD_cycles,self.EXADD_pipelined)
        self.EXDIV = Unit('EXDIV',self.EXDIV_cycles,self.EXDIV_pipelined)
        self.EXIU = Unit('EXIU',1,True)
        self.EXMEM = Unit('EXMEM',self.EXINT_cycles,False)
        self.WB = Unit('WB',1,True)

        self.icache = ICache(self.ICache_cycles,self.EXINT_cycles)
        
        self.dcache = DCache(256,self.data,self.DCache_cycles,self.EXINT_cycles)
        self.dbus_access = 0
        self.bus_contention = False

    def __repr__(self):
        pipeline_state = ""
        for i in range(len(self.inst_exec_list.keys())):
            pipeline_state += '{0: <24}'.format( self.inst_exec_list[i].upper().strip())+"\t"
            pipeline_state += str(self.result[i][0]) + '\t'
            pipeline_state += str(self.result[i][1]) + '\t'
            pipeline_state += str(self.result[i][2]) + '\t'
            pipeline_state += str(self.result[i][3]) + '\t'
            if self.result[i][4]==0:
                pipeline_state += ' N\t'
            else:
                pipeline_state += ' Y\t'
            if self.result[i][5]==0:
                pipeline_state += ' N\t'
            else:
                pipeline_state += ' Y\t'
            if self.result[i][6]==0:
                pipeline_state += ' N\t'
            else:
                pipeline_state += ' Y\t'
            if self.result[i][7]==0:
                pipeline_state += ' N\t'
            else:
                pipeline_state += ' Y\t'
            
            pipeline_state += '\n'
        
        return pipeline_state

    def __str__(self):
        pipeline_state=""
        pipeline_state += self.IF.__str__()+"\n"
        pipeline_state += self.ID.__str__()+"\n"
        pipeline_state += self.EXIU.__str__()+"\n"
        pipeline_state += self.EXMEM.__str__()+"\n"
        pipeline_state += self.EXADD.__str__()+"\n"
        pipeline_state += self.EXMULT.__str__()+"\n"
        pipeline_state += self.EXDIV.__str__()+"\n"
        pipeline_state += self.WB.__str__()+"\n"
        return pipeline_state

    def read_files(self,file_inst, file_data, file_reg, file_config):
        # Read all instructions
        f = open(file_inst)
        self.set_of_instructions = f.readlines()
        f.close()
        
        # Read config file
        try:
            f = open(file_config)
            lines = f.readlines()
            EXADD_params = lines[0].split(':')[1].strip()
            EXMULT_params = lines[1].split(':')[1].strip()
            EXDIV_params = lines[2].split(':')[1].strip()
            EXINT_params = lines[3].split(':')[1].strip()
            ICache_params = lines[4].split(':')[1].strip()
            DCache_params = lines[5].split(':')[1].strip()

            self.EXADD_cycles = int(EXADD_params.split(',')[0].strip(','))
            self.EXADD_pipelined = EXADD_params.split(',')[1].upper().strip()=='YES'
            
            self.EXMULT_cycles = int(EXMULT_params.split(',')[0].strip(','))
            self.EXMULT_pipelined = EXMULT_params.split(',')[1].upper().strip()=='YES'
            
            self.EXDIV_cycles = int(EXDIV_params.split(',')[0].strip(','))
            self.EXDIV_pipelined = EXDIV_params.split(',')[1].upper().strip()=='YES'
            
            self.EXINT_cycles = int(EXINT_params.split()[0].strip(','))

            self.ICache_cycles = int(ICache_params.split()[0].strip(','))
            
            self.DCache_cycles = int(DCache_params.split()[0].strip(','))

            f.close()
        except Exception, e:
            print "Error: Invalid config file"
            exit()

        # Read register file
        file = open(file_reg, 'r')
        regs_string = file.readlines()
        self.registers = {'R'+str(i):int(regs_string[i].strip(),2) for i in range(len(regs_string))}
        self.registers['PC']=0
        
        # Read data file
        self.word_size = 4
        self.base_address = 256
        file = open(file_data, 'r')
        data_string = file.readlines()
        self.data = {self.base_address+(i*self.word_size):int(data_string[i].strip(),2) for i in range(len(data_string))}
Example #37
0
 def __init__(self):
     self.unit = Unit()
Example #38
0
class UnitManager:
    def __init__(self):
        self.unit = Unit()

    
    
    #Everything is shifted by 180 degrees logically because the top of the window is 0 and as your variable increases the entity moves down
    def moveNorth(self):
        y = self.unit.getYLoc()
        self.unit.setYLoc(y - 1)
 
    def moveEast(self):
        x = self.unit.getXLoc()
        self.unit.setXLoc(x + 1)
        
    def moveSouth(self):
        y = self.unit.getYLoc()
        self.unit.setYLoc(y + 1)
        
    def moveWest(self):
        x = self.unit.getXLoc()
        self.unit.setXLoc(x - 1)
        
    def ResizeImage(self, image, size):
        img = ImageTk.PhotoImage(Image.open(image))
        return img
        #return image.resize((size,size), Image.ANTIALIAS)
 def createUnits(unitInfoCollection):
     # Small issue - will create new instance of units that already exist
     return [Unit.createUnitFromDict(unitInfo, board.unitInfoDict, board.countries, board.territories) for unitInfo in unitInfoCollection]