Example #1
0
    def visitPrimary(self, ctx):
        """ それぞれのPrimaryの値をUnitXObjectにラップして,応答する.

            Identifier: variable or function
            literal: number, string, boolean, none
            PAREN=(): expression
            BRACK=[]: list
        """
        unit = Unit()
        if ctx.unit(): unit = self.visitUnit(ctx.unit())

        if ctx.Identifier():
            # Here
            varname = ctx.Identifier().getText()
            unitx_obj = UnitXObject(value=None, varname=varname, unit=unit)
            """
            current_scope = self.get_scopes().peek()
            if varname in current_scope:
                unitx_obj = current_scope[varname]
                if not unit.is_empty():
                    unitx_obj.unit = unit
            else:
                unitx_obj = UnitXObject(value=None, varname=varname, unit=unit)
            """

            found_scope = self.get_scopes().peek().find_scope_of(varname)
            if found_scope:
                unitx_obj = found_scope[varname]
                if not unit.is_empty():
                    unitx_obj.unit = unit
            else:
                unitx_obj = UnitXObject(value=None, varname=varname, unit=unit)
            unitx_obj.token = ctx.Identifier().getSymbol()

        elif ctx.literal():
            unitx_obj = self.visitLiteral(ctx.literal())
            unitx_obj.unit = unit

        elif ctx.start.type == UnitXLexer.LPAREN:
            unitx_obj = self.visitExpression(ctx.expression(i=0))
            if not unit.is_empty():
                unitx_obj.unit = unit
            unitx_obj.token = ctx.start

        elif ctx.start.type == UnitXLexer.LBRACK:
            unitx_objs = []
            for an_expr in ctx.expression():
                an_obj = self.visitExpression(an_expr)
                if not unit.is_empty():
                    an_obj.unit = unit
                unitx_objs.append(an_obj)

            unitx_obj = UnitXObject(value = unitx_objs, varname = None, unit=unit, token=ctx.start)

        else:
            if not self.is_intaractive_run:
                raise Exception("Syntax error. EvalVisitor#visitPrimary") # Never happen.

        assert(isinstance(unitx_obj, UnitXObject))
        return unitx_obj
Example #2
0
    def __init__(self, mainObj, position, yon=4, layer=0, attrDict={}):
        self.type = 'Kurt'
        Unit.__init__(self, mainObj, position, yon, attrDict)

        self.image = self.changeImage('Kurt', yon) # Oyunun başında ilk yüklenen unit resim dosyasi
        self.rect = self.image.get_rect()
        self.rect.topleft = position
        self.layer = layer # LayeredUpdates grubu için gerekiyor
        
        self.colRect = copy(Kurt.colRect[self.yon])
        self.colRect.topleft = (self.colRect.topleft[0] + self.rect.topleft[0], self.colRect.topleft[1] + self.rect.topleft[1])
        
        # çarpışmalarda kullanılan noktalar
        self.colPoints = None
        
        self.tolerans = 0
        self.speed = 4
        
        if self.player.type == Player.human_player:
            self.ai = KurtFSM(self, human=True)
        else:
            self.ai = KurtFSM(self)
        
        # unit'in gerçek pozisyonunu (reel sayılarla) tutar. rect'e atılırken int'e dönüştürülür.
        self.yer = Vector2(*self.colRect.center)
Example #3
0
def generate_one_unit(i, paper, problem_list):
    """
    随机生成一个个体
    """

    unit = Unit()
    unit.id = i + 1

    each_type_count = paper.each_type_count
    while paper.total_score != unit.sum_score:
        unit.problem_list = []
        for j in range(len(each_type_count)):
            one_type_problem = [
                p for p in problem_list
                if p.type == j+1 and is_contain_points(p, paper)]

            for k in range(0, each_type_count[j]):
                length = len(one_type_problem)
                index = randint(0, length - k - 1)
                unit.problem_list.append(one_type_problem[index])
                one_type_problem[index], one_type_problem[length-k-1] = \
                    one_type_problem[length-k-1], \
                    one_type_problem[index]

    return unit
Example #4
0
	def __init__(self, player, sig, model, skeleton, animations, inventory):
		'''
		Constructor
		'''
		Unit.__init__(player, sig, numControllers = 1)
		self.player = player
		self.enabled = False
Example #5
0
    def __init__(self, mainRef, attributes):
        print("Enemy instantiated")
        Unit.__init__(self)
        FSM.__init__(self, 'playerFSM')

        self._mainRef = mainRef
        self._playerRef = mainRef.player
        self._AIworldRef = mainRef.AIworld
        self._enemyListRef = mainRef.enemyList
        self._ddaHandlerRef = mainRef.DDAHandler
        self._stateHandlerRef = mainRef.stateHandler
        self._scenarioHandlerRef = mainRef.scenarioHandler

        #self.topEnemyNode = mainRef.mainNode.attachNewNode('topEnemyNode')
        self.initEnemyNode(mainRef.mainNode)

        utils.enemyDictionary[self.enemyNode.getName()] = self

        self.loadEnemyModel(attributes.modelName)
        self.initAttributes(attributes)
        self.initEnemyAi()

        self.initEnemyDDA()

        self.initEnemyCollisionHandlers()
        self.initEnemyCollisionSolids()

        #self.request('Idle')
        self.request('Disabled')

        # Start enemy updater task
        self.enemyUpdaterTask = taskMgr.add(self.enemyUpdater, 'enemyUpdaterTask')
Example #6
0
 def button_events(self, event):
     # check for clicks on a button 
     # (not in mousebuttondown to allow for mouseover highlight)         
     for button in self.buttons.btn_list:
         if "click" in button.handleEvent(event):
             if button.caption == "B":
                 self.player_command.player_msg = \
                     "That was the round button"
             if button.caption == "hi":
                 self.player_command.player_msg = \
                     "Nothing here but us buttons."
             if button.caption == "MAKE IT SO!":
                 Unit.movement(self.grid_map, self.players)
                 self.player_command.player_msg = ""
     """ check for unit-related button events """
     for player in self.players.active_list:
         for group in player.units:
             for unit in group.group_list:
                 for button in unit.unit_btns:
                     if "click" in button.handleEvent(event):
                         if button.caption == "B":
                             unit.active = "True"
                             unit.txt_status = "Targeting"
                             self.player_command.player_msg = \
                                 "Click on target tile."
                         elif button.caption == "A":
                             unit.txt_status = "A Button"
                         else:
                             unit.txt_status = "Unidentified Button"
Example #7
0
    def __init__(self, is_intaractive_run, an_errhandler):
        """ EvalVisitorを初期化して応答する.
        """
        self.is_test = False
        self.is_intaractive_run = is_intaractive_run
        self.errhandler = an_errhandler
        self.scopes = ScopeList()
        self.is_break = False
        self.is_return = False
        self.return_value = UnitXObject(value=None, varname=None, unit=None, token=None, is_none=True)

        this_dir, _ = os.path.split(__file__)
        data_path = os.path.join(this_dir, Constants.SYSTEM_UNIT_DATA)
        self.unit_manager = UnitManager(data_path) # Sets a database(data/unit_table.dat) for calculating units.
        self.stdlib = Stdlib()
        self.NULL_UNITX_OBJ = UnitXObject(value=None, varname=None, is_none=True, unit=Unit(), token=None)
        
        #
        # Sets a mediator to each classes for a management,
        # because this class is a mediator class.
        # Also, UnitXObject, Unit, Scope classes have to create many new instances.
        # So, We set a mediator by using classmethod.
        #
        self.scopes.set_mediator(self)
        self.unit_manager.set_mediator(self)
        self.stdlib.set_mediator(self)
        UnitXObject.set_mediator(self)
        Unit.set_mediator(self)
        Scope.set_mediator(self)
        DefinedFunction.set_mediator(self)

        UnitXObject.manager = self.get_unit_manager()
        UnitXObject.scopes = self.get_scopes()
Example #8
0
 def __init__(self, constraint, x=0, y=0, direction=(1, 0), kind=0):
     Unit.__init__(self, constraint, x, y, direction, 160, 65)
     if kind:
         self.kind = 'lion'
         self.health = 200
     else:
         self.kind = 'blue'
         self.health = 100
	def update(self, time):
		self.applyForceFrom(-0.1, self.player.getPos())
		
		Unit.update(self, time)
		
		angle = math.atan2(self.player.getY() - self.getY(), \
							self.player.getX() - self.getX())
		self.setH(angle * 180 / math.pi)
Example #10
0
	def handleCubeIntoCollision(self, entry):
		try:
			fromName = entry.getFromNodePath().getParent().getName()
			Unit.collideWithObstacle(self.actors[fromName])
			if fromName == "player" and self.collisionSound.status() is not self.collisionSound.PLAYING:
				self.collisionSound.play()
		except:
			pass
 def value_unit_to_number(self, param, value):
     # string is of the form "32.3L"
     unit = value[-1]
     #v = float(value[:-1])
     v = self.str_to_float(param, value[:-1])
     if (Unit.get(param) != unit):
         v = Unit.convert(unit, Unit.get(param), v)
     return round(v, self.precision)
Example #12
0
    def reduce_unit(self, guide_unit=None):
        """
        Combine similar component units and scale, to form an
        equal Quantity in simpler units.

        Returns underlying value type if unit is dimensionless.
        """
        key = (self.unit, guide_unit)
        if key in Quantity._reduce_cache:
            (unit, value_factor) = Quantity._reduce_cache[key]
        else:
            value_factor = 1.0
            canonical_units = {} # dict of dimensionTuple: (Base/ScaledUnit, exponent)
            # Bias result toward guide units
            if guide_unit is not None:
                for u, exponent in guide_unit.iter_base_or_scaled_units():
                    d = u.get_dimension_tuple()
                    if d not in canonical_units:
                        canonical_units[d] = [u, 0]
            for u, exponent in self.unit.iter_base_or_scaled_units():
                d = u.get_dimension_tuple()
                # Take first unit found in a dimension as canonical
                if d not in canonical_units:
                    canonical_units[d] = [u, exponent]
                else:
                    value_factor *= (u.conversion_factor_to(canonical_units[d][0])**exponent)
                    canonical_units[d][1] += exponent
            new_base_units = {}
            for d in canonical_units:
                u, exponent = canonical_units[d]
                if exponent != 0:
                    assert u not in new_base_units
                    new_base_units[u] = exponent
            # Create new unit
            if len(new_base_units) == 0:
                unit = dimensionless
            else:
                unit = Unit(new_base_units)
            # There might be a factor due to unit conversion, even though unit is dimensionless
            # e.g. suppose unit is meter/centimeter
            if unit.is_dimensionless():
                unit_factor = unit.conversion_factor_to(dimensionless)
                if unit_factor != 1.0:
                    value_factor *= unit_factor
                    # print "value_factor = %s" % value_factor
                unit = dimensionless
            Quantity._reduce_cache[key] = (unit, value_factor)
        # Create Quantity, then scale (in case value is a container)
        # That's why we don't just scale the value.
        result = Quantity(self._value, unit)
        if value_factor != 1.0:
            # __mul__ strips off dimensionless, if appropriate
            result = result * value_factor
        if unit.is_dimensionless():
            assert unit is dimensionless # should have been set earlier in this method
            if is_quantity(result):
                result = result._value
        return result
Example #13
0
	def handleUnitIntoCollision(self, entry):
		try:
			fromName = entry.getFromNodePath().getParent().getName()
			intoName = entry.getIntoNodePath().getParent().getName()
			Unit.collideWithUnit(self.actors[intoName], self.actors[fromName])
			if (fromName == "player" or intoName == "player") and self.collisionSound.status() is not self.collisionSound.PLAYING:
				self.collisionSound.play()
		except:
			pass
Example #14
0
 def test_hero_attack(self):
     hero = Unit(100, 100, 5)
     hero.learn(Spell('a', 10, 10, 2))
     self.dungeon.spawn(hero)
     self.dungeon.move_hero('down')
     self.dungeon.move_hero('down')
     self.assertEqual('Nothing in casting range 2',
                      self.dungeon.hero_attack(by="spell"))
     self.dungeon.move_hero('down')
     self.assertIsInstance(self.dungeon.hero_attack(by='spell'), Fight)
Example #15
0
	def __init__(self, models = None, anims = None, sphereString = None, game = None, xStart = 0, yStart = 0, zStart = 0):
		Unit.__init__(self, models, anims, sphereString, game, xStart, yStart, zStart)
		
		#set up sounds
		self.deathSound = game.loader.loadSfx(SFX_PATH + "enemy_death.wav")
		
		self.randomMovement = 0
		self.randomMovementMax = 30 * 7
		self.minRandomVel = 1000
		self.maxRandomVel = 2000
Example #16
0
    def __init__(self, name, title, health, mana, mana_regen):
        self.name = name
        self.title = title
        self.mana_regen = mana_regen
        Unit.__init__(self, health, mana, name)

        self.phisical_damage = 0
        self.magic_damage = 0

        self.max_equiped_weapons = 0
        self.max_learned_spells = 0
Example #17
0
 def __init__(self, sport, xparam, yparam, xvals = None, yvals = None):
     self.xparam = xparam
     self.yparam = yparam
     self.sport = sport
     if (xvals is None):
         xvals = []
     if (yvals is None):
         yvals = []
     self.xvals = xvals
     self.yvals = yvals
     self.xlabel = self.xparam + " (%s)"%(Unit.get(self.xparam))
     self.ylabel = self.yparam + " (%s)"%(Unit.get(self.yparam))
Example #18
0
	def __init__(self, team, sig, model, numControllers, keyinput):
		'''
		Constructor
		'''
		self.input = keyinput
		
		self.model = loader.loadModel(model)
		
		tankNode = render.attachNewNode(ActorNode("tank-physics"))
		tankNode.detachNode()
		self.tankNode = tankNode
		actorNode = tankNode.node()
		base.physicsMgr.attachPhysicalNode(actorNode)
		
		actorNode.getPhysicsObject().setMass(1000)
		
		fromObject = tankNode.attachNewNode(CollisionNode('tank-coll'))
		fromObject.node().addSolid(CollisionSphere(0, 0, 0, 1))
		self.model.reparentTo(tankNode)
		
		pusher = PhysicsCollisionHandler()
		pusher.addCollider(fromObject,tankNode)
		
		base.cTrav.addCollider(fromObject, pusher)
		
		fromObject.show()
		
		Unit.__init__(self, sig, numControllers)
		self.enabled = False
		self.camera = VehicleCamera(self.tankNode, Vec3(0,-10,5))
		
		self.rotation = Rotation(self.tankNode, self.camera.camNode)
		
		self.engineFN=ForceNode('tank-hover-engine-front-left')
		self.engineFNP=tankNode.attachNewNode(self.engineFN)
		
		self.engineNodes = [NodePath("front-left-engine") ,
							NodePath("front-right-engine"),
							NodePath("back-left-engine")  ,
							NodePath("back-right-engine")  ]
		
		for i in range(0,4):
			self.engineNodes[i].reparentTo(tankNode)
			self.engineNodes[i].setPos(tankNode, ENGINELIST[i])
			blah = loader.loadModel(model)
			blah.reparentTo(self.engineNodes[i])
			blah.setScale(0.1)
		
		self.linearForce = None
		self.rotateForce = None
		
		self.movement = Movement(tankNode)
		self.movement.enable()
Example #19
0
 def test_found_treasure(self):
     hero = Unit(100, 100, 5)
     hero.health = 1
     hero.mana = 1
     self.dungeon.spawn(hero)
     self.dungeon._found_treasure('mana')
     self.assertGreater(hero.mana, 1)
     self.dungeon._found_treasure('health')
     self.assertGreater(hero.health, 1)
     self.dungeon._found_treasure('weapon')
     self.assertNotEqual(hero.weapon, None)
     self.dungeon._found_treasure('spell')
     self.assertNotEqual(hero.spell, None)
 def test_get_new_commands(self):
     ip = "127.0.0.1"
     port = 8080
     unit_id = "3c82ef61-0875-41d3-99ba-101672d79d6b"
     testunit = Unit(ip, unit_id, fallback_units = [])
     # Post five tasks to taskboard
     for _ in xrange(5):
         task = create_valid_task()
         # Posting a task should result in no error
         testunit.post_task(task)
     tasks = testunit.get_new_commands()
     print tasks
     self.assertTrue(len(tasks) == 5)
Example #21
0
 def __init__(self, constraint, x=0, y=0, direction=(1, 0), size=0):
     radius = (size * 15 + 41) / 2
     Unit.__init__(self, constraint, x, y, direction, 80, radius)
     SinkingItem.__init__(self, constraint, x, y, 80, radius)
     self.hungry = False
     self.growth = 0
     # Fish size: 0 - small, 1 - normal, 2 - big
     self.size = size
     self.last_fed = int(time())
     self.grow_time = int(time())
     self.drop_coin = False
     # Prevents multiple coin drops in the same second.
     self.coin_drop_time = time()
 def value_space_unit_to_number(self, param, value):
     # default format is "<value> <unit>"
     if (value == "-"):
         raise InvalidValueException(param, value)
     parts = value.split()
     unit = parts[1]
     if (unit == "min/mi" and (":" in parts[0])):
         v_parts = parts[0].split(":")
         #v = float(v_parts[0]) + float(v_parts[1])/60.0  # convert to float minutes value
         v = self.str_to_float(param, v_parts[0]) + self.str_to_float(param, v_parts[1])/60.0  # convert to float minutes value
     else:
         #v = float(parts[0])
         v = self.str_to_float(param, parts[0])
     if (Unit.get(param) != unit):
         v = Unit.convert(unit, Unit.get(param), v)
     return round(v, self.precision)
Example #23
0
 def dataReceived(self, data):
     if not '\n' in data:
         self.buf += data
         return
     full = (self.buf + data).split("\n")
     self.buf = full[-1]
     for line in full[:-1]:
         json_data = json.loads(line)
         if json_data["message_type"] == "hello":
             global game_map
             print "Hello message"
             units = [Unit.from_dict(u) for u in json_data["units"]]
             bullets = [Bullet.from_dict(b) for b in json_data["bullets"]]
             hero = Hero.from_dict(json_data["hero"])
             commander = Commander.from_dict(json_data["commander"])
             game_map = GameMap(json_data["rows"], json_data["cols"],
                                json_data["map"], hero, commander, units, bullets)
         elif json_data["message_type"] == "update":
             # Drop any removed units/bullets, then update values for remaining
             if len(game_map.units) > len(json_data["units"]):
                 game_map.units = game_map.units[:len(json_data["units"])]
             for i in xrange(len(json_data["units"]) - len(game_map.units)):
                 game_map.units.append(Unit(1, 1999, 1999, 0, 0))
             for u_old, u_new in zip(game_map.units, json_data["units"]):
                 u_old.update_from_dict(u_new)
             if len(game_map.bullets) > len(json_data["bullets"]):
                 game_map.bullets = game_map.bullets[:len(json_data["bullets"])]
             for i in xrange(len(json_data["bullets"]) - len(game_map.bullets)):
                 game_map.bullets.append(Bullet(0, 999, 999, 0, 0))
             for b_old, b_new in zip(game_map.bullets, json_data["bullets"]):
                 b_old.update_from_dict(b_new)
             game_map.hero.update_from_dict(json_data["hero"])
             game_map.commander.update_from_dict(json_data["commander"])
Example #24
0
	def update(self, time):
		"""Run all major player operations each frame"""
		#check for weapon switch key
		if self.controlScheme.keyDown(SWITCH):
			if not self.switchPressed:
				self.switchWeapon()
				self.switchPressed = True
		else:
			self.switchPressed = False
		
		self.targetEnemy()
		
		#check for attack keys
		if self.controlScheme.keyDown(PUSH) and not self.controlScheme.keyDown(PULL):
			self.attack(PUSH, time)
			#include sound
			#self.electricSound.play()
			if self.electricSound.status() is not self.electricSound.PLAYING:
				#self.electricSound.setTime(self.electricSound.getTime())#reset to the current time and play it from there
				self.electricSound.setVolume(.1)
				self.electricSound.play()
		elif self.controlScheme.keyDown(PULL) and not self.controlScheme.keyDown(PUSH):
			self.attack(PULL, time)
			#include sound
			#self.magnetSound.setLoop(True)
			if self.magnetSound.status() is not self.magnetSound.PLAYING:
				#self.magnetSound.setTime(self.magnetSound.getTime())
				self.magnetSound.play()
				
		else:
			self.sustainedAttack = False
			#self.target = None
			if self.electricSound.status() == self.electricSound.PLAYING:
				#self.electricSound.setTime(float(0))#for some reason this is not resetting the time
				self.electricSound.stop()
			if self.magnetSound.status() == self.magnetSound.PLAYING:
				#self.magnetSound.setTime(float(0))#for some reason this is not resetting the time
				self.magnetSound.stop()
				
		#i am of the opinion that sound is somehow completely borked here
		
		#automatically regenerate energy
		self.energy += self.energyRegen * time
		self.energy = min(self.maxEnergy, self.energy)
		
		self.move(time)
		Unit.update(self, time)
Example #25
0
def test_unit_detection(value, expected, unit, templates):
    """Testing different combinations of number formats and all units."""
    for template in templates:
        text = template.format(value)
        found_unit = Unit.find_first_unit(text)
        assert found_unit is not None, 'Nothing found in {!r}'.format(text)
        assert found_unit.value == expected and found_unit.unit == unit
        assert isinstance(found_unit.to_useless(), type(''))
Example #26
0
def test_compound_units(values, expected, units, template):
    """Testing arbitrary compound unit formats."""
    text = template.format(*values)
    found_units = Unit.find_first_unit(text)

    assert found_units is not None
    assert isinstance(found_units, list)

    for i, found_unit in enumerate(found_units):
        assert found_unit.unit == units[i]
        assert found_unit.value == expected[i]
        assert isinstance(found_unit.to_useless(), type(''))
Example #27
0
	def __init__(self, team, sig, model, numControllers, keyinput):
		'''
		Constructor
		'''
		self.input = keyinput
		
		self.model = loader.loadModel(model)
		
		tankNode = render.attachNewNode(ActorNode("tank-physics"))
		tankNode.detachNode()
		self.tankNode = tankNode
		actorNode = tankNode.node()
		base.physicsMgr.attachPhysicalNode(actorNode)
		
		actorNode.getPhysicsObject().setMass(1000)
		
		fromObject = tankNode.attachNewNode(CollisionNode('tank-coll'))
		fromObject.node().addSolid(CollisionSphere(0, 0, 0, 1))
		self.model.reparentTo(tankNode)
		
		pusher = PhysicsCollisionHandler()
		pusher.addCollider(fromObject,tankNode)
		
		base.cTrav.addCollider(fromObject, pusher)
		
		fromObject.show()
		
		Unit.__init__(self, sig, numControllers)
		self.enabled = False
		self.camera = VehicleCamera(self.tankNode, Vec3(0,-10,5))
		
		self.rotation = Rotation(self.tankNode, self.camera.camNode)
		
		self.engineFN=ForceNode('tank-engine')
		self.engineFNP=tankNode.attachNewNode(self.engineFN)
		self.upForce=LinearVectorForce(0,0,20000)
		self.upForce.setMassDependent(1)
		self.engineFN.addForce(self.upForce)
		
		base.physicsMgr.addLinearForce(self.upForce)
    def to_number(self, param, value):
        # convert "11m:15s" to 675
        if (not Unit.is_defined(param)):
            #raise Exception("Unit for the given parameter %s has not been defined" % (param))
            raise InvalidParamException(param)

        if (self.param_formatters.has_key(param)):
            f = self.param_formatters[param]
            v = f(param, value)
        else:
            raise Exception("Unknown parameter %s in ParamFormatter" % (param))

        return v
Example #29
0
    def __init__(self, mainRef):
        print("Player instantiated")
        Unit.__init__(self)
        FSM.__init__(self, 'playerFSM')

        self._hudRef = None
        self._mainRef = mainRef
        self._enemyListRef = mainRef.enemyList
        self._ddaHandlerRef = mainRef.DDAHandler
        self._mapHandlerRef = mainRef.mapHandler
        self._stateHandlerRef = mainRef.stateHandler
        self._scenarioHandlerRef = mainRef.scenarioHandler

        self.playerNode = mainRef.mainNode.attachNewNode('playerNode')

        self.initPlayerAttributes()
        self.initPlayerModel()
        self.initPlayerCamera()
        self.initPlayerAbilities()

        self.initPlayerCollisionHandlers()
        self.initPlayerCollisionSolids()

        self.initPlayerDDA()

        # Start mouse picking and movement
        self.mouseHandler = utils.MouseHandler(self)

        # Start player update task
        playerUpdateTask = taskMgr.add(self.playerUpdate, 'playerUpdateTask')

        # Initialize player FSM state
        self.request('Idle')

        DO = DirectObject()
        DO.accept('shift-mouse1', self.onShiftDown)
        DO.accept('shift-up', self.onShiftUp)

        self._shiftButtonDown = False
Example #30
0
  def import_data(cls):
    filenm ='kegiatan_sub.csv'
    with open(filenm, 'rb') as csvfile:
      reader = csv.DictReader(csvfile, delimiter=';', quotechar='"')
      i = 0
      for row in reader:
        i += 1
        if i/100 ==i/100.0:
          print i
        #print row
        tahun = row['tahun'].strip()
        kegiatan_id = Kegiatan.get_by_kode(row['kegiatan'].strip()).id
        unit_id = Unit.get_by_kode(row['unit'].strip()).id
        no_urut = row['no_urut'].strip()
        data = cls.get_by_kode(tahun, kegiatan_id, unit_id, no_urut)
        if not data:
          data=cls()
          data.kegiatan_id = kegiatan_id
          data.unit_id = unit_id
          data.no_urut = no_urut
          data.created = datetime.now()
          data.create_uid = 1
          data.tahun_id = row['tahun'] 
          #data.level_id = data.kode.count('.')+1
          #data.parent_id = DBSession.query(Rekening.id).filter(Rekening.kode==data.kode[:data.kode.rfind('.')]).scalar()
          data.disabled = 0
          #data.defsign = 1
          #data.program_id=Program.get_by_kode(''.join([row['urusankd'].strip(),'.',row['programkd'].strip()])).id
        data.kode = row['kegiatan']
        data.nama = row['nama'].strip()
        data.amt_lalu = 0
        data.amt_yad  = 0
        data.ppa      = 0
        data.ppas     = 0
        data.ppa_rev  = 0
        data.ppas_rev = 0
        data.pending  = 0
        data.tahunke  = 0
        data.h0yl     = 0
        data.p0yl     = 0
        data.r0yl     = 0
        data.h1yl     = 0
        data.p1yl     = 0
        data.r1yl     = 0
        data.h2yl     = 0
        data.p2yl     = 0
        data.r2yl     = 0

        DBSession.add(data)
    DBSession.flush()
    DBSession.commit()
Example #31
0
    def test_post_task(self):
        ip = "127.0.0.1"
        port = 8080
        unit_id = "3c82ef61-0875-41d3-99ba-101672d79d6b"
        testunit = Unit(ip,
                        unit_id,
                        fallback_units=[uuid.uuid4().hex,
                                        uuid.uuid4().hex])

        task = create_valid_task()
        # Posting a task should result in no error
        testunit.post_task(task)

        # Posting test again should raise an error
        try:
            testunit.post_task(task)
        except HTTPError as e:
            status_code = e.response.status_code

        self.assertTrue(status_code == 500)

        valid_response = self.valid_response
        testunit.post_task(valid_response)
Example #32
0
 def __init__(self, directory, name="design"):
     if name is None:
         name = os.path.split(directory)[1].lower()
     self.name = name
     self.tech_file = os.path.join(directory, name + '.tech')
     self.loc_file = os.path.join(directory, name + '.loc')
     self.nets_file = os.path.join(directory, name + '.nets')
     self.tech = read_technology_file(self.tech_file)
     self.units = read_units(self.loc_file)
     self.udict = dict()  # unit name lookup table
     for unit in self.units:
         self.udict[unit.name] = unit
     #self.lastdir = os.path.normpath(os.path.dirname(file))
     if not os.path.exists(self.nets_file):
         raise Exception("Netlist file not found!")
     self.nets = read_nets(self.nets_file, self.udict)
     self.ndict = dict()  # net name lookup table
     for net in self.nets:
         self.ndict[net.name] = net
     self.width = self.tech['design_width']
     self.height = self.tech['design_height']
     self.chip = Unit("chip", 0, 0, self.width, self.height)
Example #33
0
    def test_get_response(self):
        ip = "127.0.0.1"
        port = 8080
        unit_id = "3c82ef61-0875-41d3-99ba-101672d79d6b"
        testunit = Unit(ip, unit_id, fallback_units=[])
        setup_server([testunit])

        # Create a valid command and response to use in this test
        command, response = create_valid_task()

        # Post a command, no exception
        testunit.post_task(command)

        # Post a response, no exception
        testunit.post_task(response)

        testunit_response = testunit.get_response(command)
        self.assertTrue(isinstance(testunit_response, Task))
        self.assertTrue(testunit_response.task_id == response.task_id)
        print response
Example #34
0
 def addunit(self, charflag, unitdict):
     newunit = Unit(charflag, unitdict)
     createnewstack = True
     #self.unit_list.add(newunit)
     #print "Length: " + str(len(self.unit_list.sprites()) )
     if len(self.unit_list.sprites()) == 0:
         #print "First unit"
         self.unit_list.add(newunit)
     else:
         for unit in self.unit_list:
             #print "unit's stack id: " + str(unit.stack_id)
             #print "new unit's stack id: " + str(newunit.stack_id)
             if newunit.stack_id == unit.stack_id:
                 #print "Adding unit "+ str(newunit.id) + " to stack " + str(unit.stack_id) + "char?: " + str(charflag)
                 #print "---"
                 unit.add_unit(newunit)
                 createnewstack = False
                 break
         if createnewstack:
             #print "New stack for "+ str(unit.id) + " for stack " + str(unit.stack_id) + "char?: " + str(charflag)
             #print "---"
             self.unit_list.add(newunit)
Example #35
0
 def __init__(self, _unit: Unit, **kwargs) -> None:
     super().__init__(wait=False,
                      gravity=Gravity.CENTER,
                      allowed_events=[p.MOUSEBUTTONDOWN, p.KEYDOWN],
                      **kwargs)
     self.unit = _unit
     self.gained_exp = _unit.exp_prev + _unit.gained_exp()
     self.image = gui.Image(_unit.image,
                            die_when_done=False,
                            bg_color=c.MENU_BG)
     self.bar = gui.LifeBar(max=99,
                            value=_unit.exp_prev,
                            blocks_per_row=100,
                            block_size=(2, 10),
                            life_color=c.YELLOW)
     self.label = gui.Label(_("EXP: {experience}") + "\t" +
                            _("LV: {level}"),
                            f.SMALL,
                            txt_color=c.YELLOW)
     self.label.format(**_unit.__dict__)
     self.add_children(self.image, self.bar, self.label)
     self.time = 0
Example #36
0
    def test_get_new_commands(self):
        ip = "127.0.0.1"
        port = 8080
        unit_id = "3c82ef61-0875-41d3-99ba-101672d79d6b"
        testunit = Unit(ip, unit_id, fallback_units=[])
        setup_server([testunit])
        # Post five tasks to taskboard

        for _ in xrange(5):
            command, response = create_valid_task()
            # Posting a task should result in no error
            testunit.post_task(command)
        for _ in xrange(5):
            command, response = create_valid_task()
            # Posting a task should result in no error
            testunit.post_task(response)

        tasks = testunit.get_new_commands()
        for task in tasks:
            self.assertTrue(task.response == {})
Example #37
0
    def spawn_unit(self, player_id, loc):
        # Add new unit to board
        if not self.is_free(loc):
            raise Exception("Cannot spawn unit in location " + str(loc) +
                            " since it is occupied")

        if self.players[player_id].num_units() >= self.unit_limit:
            logger.log(
                10, "Player " + str(player_id) +
                " attempted to spawn new unit, but has reached the spawn limit."
            )
            return

        self.num_total_units_spawned += 1
        unit_id = self.num_total_units_spawned
        new_unit = Unit(self, unit_id, player_id, loc)
        self.board_matrix[loc] = new_unit
        self.turn_handler.add_to_queue(new_unit)
        self.players[player_id].units.add(new_unit)
        logger.log(
            10, "New unit " + str(unit_id) + " spawned by player " +
            str(player_id) + " in location " + str(loc))
Example #38
0
    def test_post_task(self):
        ip = "127.0.0.1"
        port = 8080
        unit_id = "3c82ef61-0875-41d3-99ba-101672d79d6b"
        testunit = Unit(ip,
                        unit_id,
                        fallback_units=[uuid.uuid4().hex,
                                        uuid.uuid4().hex])
        setup_server([testunit])

        command, response = create_valid_task()
        # Posting a task should result in no error
        testunit.post_task(command)

        # Posting test again should raise an error
        try:
            testunit.post_task(command)
        except HTTPError as e:
            status_code = e.response.status_code

        self.assertTrue(status_code == 500)

        # Posting a response to the task should not result in an error
        testunit.post_task(response)
def enter():
    gfw.world.init(['bg', 'monster', 'unit', 'unit', "gameclear"])
    Monster.load_all_images()
    Unit.load_all_images()
    life_gauge.load()
    gameclear.load()

    global selectedUnit

    if load():
        unit = gfw.world.object(gfw.layer.unit, 0)
    else:
        unit = Unit(1)
        selectedUnit = unit
        gfw.world.add(gfw.layer.unit, unit)
        gfw.world.add(gfw.layer.unit, Unit(1))
        gfw.world.add(gfw.layer.unit, Unit(1))
        gfw.world.add(gfw.layer.unit, Unit(1))

        bg = gobj.ImageObject('background.jpg',
                              (canvas_width // 2, canvas_height // 2))
        gfw.world.add(gfw.layer.bg, bg)

    magic_circle = gobj.ImageObject(
        'magic.png', (gobj.magic_circle_pos[0], gobj.magic_circle_pos[1]))
    gfw.world.add(gfw.layer.bg, magic_circle)

    global font, font2
    font = gfw.font.load(gobj.RES_DIR + '/Sweet_story.otf', 50)
    font2 = gfw.font.load(gobj.RES_DIR + '/ConsolaMalgun.ttf', 20)

    global monster_time
    monster_time = 1
    global monster_level
    monster_level = 1
    global monster_level_up_time
    monster_level_up_time = 50
    global unit_time
    unit_time = 50

    global music_bg, end_music
    music_bg = load_music('res/Track 5.mp3')
    music_bg.set_volume(10)
    end_music = load_music('res/Track 26.mp3')
    end_music.set_volume(10)
    music_bg.repeat_play()
Example #40
0
    def NewGame(self, img=None, stats=None, numUnits=None, name=None):
        if img:
            unit = self.AddUnit(
                Unit(
                    self.screen,
                    imgPath=img,
                    highlight=True,
                    name=name,
                ))
            unit.angularVelocity += stats.get('spin', 0) * 10
            self.player = unit
            unit.position = (unit.width, unit.height)

        for i in range(numUnits or int(self.surf.get_width() / 300) + 2):
            self.AddRandomUnit()

        self.AddGravity(self.surf.get_rect().center, random.randint(50, 100))
        for i in range(random.randint(4, int(self.screen.get_width() / 100))):
            self.AddGravity(
                (random.randint(0, self.surf.get_width()),
                 random.randint(0, self.surf.get_height())),
                random.randint(10, 25),
            )
        self.AddRandomBooster()
Example #41
0
    def spawn_unit(self, player, loc, unit_hp=3):
        # Add new unit to board
        if not self.is_free(loc):
            raise Exception("Cannot spawn unit in location " + str(loc) +
                            " since it is occupied")

        if player.num_units() >= self.unit_limit:
            logger.log(
                LoggerLevels.ActionMessage, "Player " + str(player.id) +
                " attempted to spawn new unit, but has reached the spawn limit."
            )
            return False  # Couldn't spawn new unit

        self.num_total_units_spawned += 1
        unit_id = self.num_total_units_spawned
        new_unit = Unit(self, unit_id, player, loc, unit_hp)
        self.board_matrix[loc] = new_unit
        self.turn_handler.add_to_queue(new_unit)
        player.units.add(new_unit)
        logger.log(
            LoggerLevels.ActionMessage,
            "New unit " + str(unit_id) + " spawned by player " +
            str(player.id) + " in location " + str(loc))
        return True  # Spawned new unit
Example #42
0
    def __init__(self, x, y, sprite, window, health, collisonradius, scale):
        Unit.__init__(self, x, y, sprite, window, health, collisonradius,
                      scale)

        # new movment algorithm
        self.last = random.randint(0, 3)
Example #43
0
    for line in fin.readlines():
        tag, addr = line.split()
        if tag == 'PUT':
            break

print 'PUT: %s' % addr

context = zmq.Context()
socket = context.socket(zmq.PUSH)
socket.hwm = 1
socket.connect(addr)

start = time.time()

for n in xrange(8):

    unit = Unit('import time \ntime.sleep(1)'
                )  #Simplistic multi-line code with imports

    # Pickle it
    msg = {'data': pickle.dumps(unit)}
    socket.send(msgpack.packb(msg))
    print '-> %s' % n
    time.sleep(DELAY)

end = time.time()

print end - start

# ------------------------------------------------------------------------------
Example #44
0
 def __rtruediv__(self, other):
     output = Scalar()
     output.value = other / self.value
     output.unit = Unit() / self.unit
     return output
    n_unused = len(unused) if unused is not None else 0

    n_more_in_group = MAX_VAR_PER_GROUP - var_count_in_group
    if n_more_in_group > 0:
        eqns_to_insert = sample(range(1, n_unused), n_more_in_group)
        print(eqns_to_insert)

        for ind in eqns_to_insert:
            child_id = unused[ind].Index
            v.associate_parent(parent_id=eq_id, child_id=child_id)
            print("Associating parent: " + str(eq_id) + ' with: ' + str(child_id))


from unit import Unit
from latex_data import LatexData
un = Unit()

bb_file = open('Icons/big_bang_64x64.jpg', 'rb')
bb_data = bb_file.read()
bb_file.close()

un_ltx = LatexData(latex='the beginning', image=bb_data)

un.update(an_id=1, latex=un_ltx)

# un_file = open('Icons/clipart-green-one-196b.png', 'rb')
# bb_data = bb_file.read()
# bb_file.close()
#
# un_one = LatexData(latex='$1$')
Example #46
0
    def test_init(self):

        unit_feet = Unit('130790')
        unit_feet.load_dictionary(unit_feet_depth)

        unit_metres = Unit('900713')
        unit_metres.load_dictionary(unit_metres_depth)

        integer_parameter = IntegerParameter()
        integer_parameter.name = 'Paper'
        integer_parameter.is_required = True
        integer_parameter.minimum_allowed_value = 1
        integer_parameter.maximum_allowed_value = 5
        integer_parameter.help_text = 'Number of paper'
        integer_parameter.description = (
            'A <b>test _description</b> that is very long so that you need '
            'to read it for one minute and you will be tired after read this '
            'description. You are the best user so far. Even better if you '
            'read this description loudly so that all of your friends will be '
            'able to hear you')
        integer_parameter.unit = unit_feet
        integer_parameter.allowed_units = [unit_feet]
        integer_parameter.value = 3

        widget = IntegerParameterWidget(integer_parameter)

        expected_value = integer_parameter.name
        real_value = widget.label.text()
        message = 'Expected %s get %s' % (expected_value, real_value)
        self.assertEqual(expected_value, real_value, message)

        expected_value = integer_parameter.value
        real_value = widget.get_parameter().value
        message = 'Expected %s get %s' % (expected_value, real_value)
        self.assertEqual(expected_value, real_value, message)

        widget._input.setValue(1.5)

        expected_value = 1
        real_value = widget.get_parameter().value
        message = 'Expected %s get %s' % (expected_value, real_value)
        self.assertEqual(expected_value, real_value, message)

        widget._input.setValue(1.55555)

        expected_value = 1
        real_value = widget.get_parameter().value
        message = 'Expected %s get %s' % (expected_value, real_value)
        self.assertEqual(expected_value, real_value, message)

        widget._input.setValue(7)

        expected_value = 5
        real_value = widget.get_parameter().value
        message = 'Expected %s get %s' % (expected_value, real_value)
        self.assertEqual(expected_value, real_value, message)

        expected_value = 'QLabel'
        real_value = widget._unit_widget.__class__.__name__
        message = 'Expected %s get %s' % (expected_value, real_value)
        self.assertEqual(expected_value, real_value, message)

        expected_value = 'feet'
        real_value = widget._unit_widget.text()
        message = 'Expected %s get %s' % (expected_value, real_value)
        self.assertEqual(expected_value, real_value, message)
Example #47
0
 def exp_or_die(unit1: Unit, unit2: Unit) -> None:
     if unit1.health > 0:
         unit1.gain_exp(unit2)
         room.run_room(ExperienceAnimation(unit1))
     else:
         s.loaded_map.kill_unit(unit1)
Example #48
0
 def test_take_damage_more_damage_than_hp_should_return_0(self):
     npc = Unit(health=20, mana=50)
     npc.take_damage(30)
     self.assertEqual(npc.get_health(), 0)
Example #49
0
from unit import Unit
from unit_stack import UnitStack
from utils import plot_history, SampleDataPointsGenerator, plot_1d
import pdb
from torchviz import make_dot
import numpy as np

# %%
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
torch.set_num_threads(12)

t_sample = 10
mu_size = t_sample
unit_count = 2
units = [Unit(name="unit{}".format(i), layer_index=i, mu_size=mu_size, mu_next_size=mu_size, device=device) for i in range(unit_count)]

network = UnitStack(units)

loss_history = []
mu_awareness = np.ones((t_sample,))

mu_awareness = torch.tensor(mu_awareness, requires_grad=True).float().to(device)
data_generator = SampleDataPointsGenerator()

# %%
# ----------- TRAIN -------------
for i in range(1000):
  loss = network.step(mu_item=next(data_generator), mu_awareness=mu_awareness, train=True)
  # print(loss)
Example #50
0
 def test_create_instance_invalid_input_should_type_error_error(self):
     with self.assertRaises(TypeError):
         Unit(health='asd', mana=100)
Example #51
0
 def test_create_instance_negative_mana_should_raise_value_error(self):
     with self.assertRaises(ValueError):
         Unit(health=20, mana=-20)
Example #52
0
class Vector:
    def __init__(self, x=0, y=0, z=0, name="Vector"):
        self.x = x
        self.y = y
        self.z = z
        self.initial = (x, y)
        self.unit = Unit()
        self.name = name

    def __repr__(self):
        return f"{self.name}: [{self.x}, {self.y}, {self.z}]{self.unit}"

    def reset(self, x=True, y=True):
        if x:
            self.x, _ = self.initial
        if y:
            _, self.y = self.initial

    def magnitude(self):
        return (self.x**2 + self.y**2)**0.5

    def __add__(self, other):
        if self.same_type(other):
            obj = copy(self)
            obj.x = self.x + other.x
            obj.y = self.y + other.y
            return obj
        else:
            raise WrongDimensionsError(
                "you are trying to add two different-sized vectors")

    def __sub__(self, other):
        if self.same_type(other):
            obj = copy(self)
            obj.x = self.x - other.x
            obj.y = self.y - other.y
            return obj
        else:
            raise WrongDimensionsError(
                "you are trying to subtract two different-sized vectors")

    def __mul__(self, other):
        if type(other) == type(Vector()):
            output = 0
            output += self.x * other.x
            output += self.y * other.y
            return output

        if type(other) == type(Scalar()):
            obj = copy(self)
            obj.x *= other.value
            obj.y *= other.value
            return obj

    def __truediv__(self, other):
        if type(other) == type(Scalar()):
            v = Vector(self.x / other.value, self.y / other.value)
            v.unit = self.unit / other.unit
        else:
            v = Vector(self.x / other, self.y / other)
            v.unit = self.unit
        return v

    def cross(self, other):
        if type(other) == type(Vector()):
            output = Vector()
            output.x = self.y * other.z - self.z * other.y
            output.y = other.x * self.z - self.x * other.z
            output.z = self.x * other.y - other.x * self.y
            output.unit = self.unit * other.unit
            return output
        else:
            raise Exception("Invalid Operation")

    def same_type(self, other):
        if type(self) == type(
                other) and self.unit.order() == other.unit.order():
            return True
        else:
            return False
Example #53
0
    def __init__(self, appname, appinfo, model):
        """
        Create an Application object with basic information from an application
        object from a juju status output
        """
        # Default Values
        self.notes = []
        self.units = []
        self.subordinates = []
        self.version = ""
        self.message = ""
        self.relations = {}
        self.endpointbindings = {}
        self.charmlatestrev = -1

        # Required Variables
        self.name = appname
        self.model = model
        self.charm = appinfo["charm"]
        self.series = appinfo["series"]
        self.os = appinfo["os"]
        self.charmorigin = appinfo["charm-origin"]
        self.charmname = appinfo["charm-name"]
        self.charmrev = int(appinfo["charm-rev"])
        self.exposed = appinfo["exposed"]
        self.status = appinfo["application-status"]["current"]

        # Required Dates
        if re.match(r".*Z$", appinfo["application-status"]["since"]):
            self.since = pendulum.from_format(
                appinfo["application-status"]["since"],
                "DD MMM YYYY HH:mm:ss",
                tz="UTC",
            )
        else:
            self.since = pendulum.from_format(
                appinfo["application-status"]["since"], "DD MMM YYYY HH:mm:ssZ"
            )
        model.controller.update_timestamp(self.since)

        # Optional Variables
        if "message" in appinfo["application-status"]:
            self.message = appinfo["application-status"]["message"]
        if "version" in appinfo:
            self.version = appinfo["version"]
        if "relations" in appinfo:
            self.relations = appinfo["relations"]
        if "endpoint-bindings" in appinfo:
            self.endpointbindings = appinfo["endpoint-bindings"]
        if "can-upgrade-to" in appinfo:
            match = re.match(r"\D+(\d+)$", appinfo["can-upgrade-to"])
            self.charmlatestrev = int(match.group(1))
            self.canupgradeto = appinfo["can-upgrade-to"]

        # Calculated Values
        if self.exposed:
            self.notes.append("exposed")
        self.charmid = ""
        match = re.match(r"(cs:~.*)\/(.*)-\d+$", self.charm)
        if match:
            self.charmid = (
                match.group(1) + "/" + self.series + "/" + match.group(2)
            )
        else:
            match = re.match(r"cs:(.*)-\d+$", self.charm)
            if match:
                self.charmid = "cs:" + self.series + "/" + match.group(1)
        if self.charmorigin != "jujucharms":
            self.notes.append("Not from Charm Store")

        # Handle Units
        if "units" in appinfo:
            for unitname, unitinfo in appinfo["units"].items():
                unit = Unit(unitname, unitinfo, self)
                self.units.append(unit)
Example #54
0
addr = None
with open('test.bridge.url', 'r') as fin:
    for line in fin.readlines():
        tag, addr = line.split()
        if tag == 'PUT':
            break

print 'PUT: %s' % addr

context = zmq.Context()
socket = context.socket(zmq.PUSH)
socket.hwm = 1
socket.connect(addr)

start = time.time()

for n in xrange(500):

    unit = Unit('time.sleep', args=(1, ))

    msg = {'data': pickle.dumps(unit)}
    socket.send(msgpack.packb(msg))
    print '-> %s' % n
    time.sleep(DELAY)

end = time.time()

print end - start

# ------------------------------------------------------------------------------
Example #55
0
def parse_battle_info(file_name='battle_info/battle_info.json', luck_factor=0):
    import json
    if is_windows():
        file_name = unix_to_nt(file_name)
    a_units = []
    b_units = []
    team_quantities = [0, 0]
    game_scenario = GameScenario(luck=luck_factor)
    army_file = 'troop_info/army.json'
    navy_file = 'troop_info/navy.json'
    af_file = 'troop_info/air_force.json'
    if is_windows():
        army_file = unix_to_nt(army_file)
        navy_file = unix_to_nt(navy_file)
        af_file = unix_to_nt(af_file)

    with open(file_name, 'r') as f:
        data = json.load(f)
    with open(army_file) as f:
        army_data = json.load(f)
    with open(navy_file) as f:
        navy_data = json.load(f)
    with open(af_file) as f:
        air_force_data = json.load(f)

    if len(data) > 2:
        raise Exception('Esse programa foi feito para rodar em apenas dois times.')
    for team_number, item in enumerate(data):
        team = item['team']
        if team == 1:
            v = a_units
        else:
            v = b_units
        # PARSE ARMY
        for idx, army_item in enumerate(item['army']):
            if army_item.get('unit_type') is None:
                raise Exception('army - classe número ' + str(idx+1) + ' não tem unit_type!')
            if army_item.get('quantity') is None:
                raise Exception('army - classe número ' + str(idx+1) + ' não tem quantity!')
            team_quantities[team_number] += army_item['quantity']

            army_type = army_item['unit_type']
            if army_data['classes'].get(army_type) is None:
                raise Exception('Não existe uma classe de exército chamada ' + str(army_type) + '!')

            batch_size = army_data['classes'][army_type]['batch_size']
            batches = army_item['quantity'] // batch_size
            remaining_batch = army_item['quantity'] % batch_size

            for i in range(batches):
                v.append(Unit(
                    team=team,
                    type=army_type,
                    hp=army_data['classes'][army_type]['hp'],
                    ATK=army_data['classes'][army_type]['ATK'],
                    DEF=army_data['classes'][army_type]['DEF'],
                    cannot_attack=set(army_data['classes'][army_type]['cannot_attack']),
                    advantage_against=set(army_data['classes'][army_type]['advantage_against']),
                    game_scenario=game_scenario,
                    prob_hit=army_data['classes'][army_type]['prob_hit'],
                    multiple=batch_size
                ))
            if remaining_batch > 0:
                v.append(Unit(
                    team=team,
                    type=army_type,
                    hp=army_data['classes'][army_type]['hp'],
                    ATK=army_data['classes'][army_type]['ATK'],
                    DEF=army_data['classes'][army_type]['DEF'],
                    cannot_attack=set(army_data['classes'][army_type]['cannot_attack']),
                    advantage_against=set(army_data['classes'][army_type]['advantage_against']),
                    game_scenario=game_scenario,
                    prob_hit=army_data['classes'][army_type]['prob_hit'],
                    multiple=remaining_batch
                ))
        # PARSE NAVY
        for idx, navy_item in enumerate(item['navy']):
            if navy_item.get('unit_type') is None:
                raise Exception('navy - classe número ' + str(idx+1) + ' não tem unit_type!')
            if navy_item.get('quantity') is None:
                raise Exception('navy - classe número ' + str(idx+1) + ' não tem quantity!')
            team_quantities[team_number] += navy_item['quantity']

            navy_type = navy_item['unit_type']
            if navy_data['classes'].get(navy_type) is None:
                raise Exception('Não existe uma classe de exército chamada ' + str(navy_type) + '!')

            batch_size = navy_data['classes'][navy_type]['batch_size']
            batches = navy_item['quantity'] // batch_size
            remaining_batch = navy_item['quantity'] % batch_size
            for i in range(batches):
                v.append(Unit(
                    team=team,
                    type=navy_type,
                    hp=navy_data['classes'][navy_type]['hp'],
                    ATK=navy_data['classes'][navy_type]['ATK'],
                    DEF=navy_data['classes'][navy_type]['DEF'],
                    cannot_attack=set(navy_data['classes'][navy_type]['cannot_attack']),
                    advantage_against=set(navy_data['classes'][navy_type]['advantage_against']),
                    game_scenario=game_scenario,
                    spot=navy_data['classes'][navy_type]['stealth'],
                    prob_hit=navy_data['classes'][navy_type]['prob_hit'],
                    multiple=batch_size
                ))
            if remaining_batch > 0:
                v.append(Unit(
                    team=team,
                    type=navy_type,
                    hp=navy_data['classes'][navy_type]['hp'],
                    ATK=navy_data['classes'][navy_type]['ATK'],
                    DEF=navy_data['classes'][navy_type]['DEF'],
                    cannot_attack=set(navy_data['classes'][navy_type]['cannot_attack']),
                    advantage_against=set(navy_data['classes'][navy_type]['advantage_against']),
                    game_scenario=game_scenario,
                    spot=navy_data['classes'][navy_type]['stealth'],
                    prob_hit=navy_data['classes'][navy_type]['prob_hit'],
                    multiple=remaining_batch
                ))
        # PARSE AIR FORCE
        for idx, af_item in enumerate(item['air_force']):
            if af_item.get('unit_type') is None:
                raise Exception('air_force - classe número ' + str(idx+1) + ' não tem unit_type!')
            if af_item.get('quantity') is None:
                raise Exception('air_force - classe número ' + str(idx+1) + ' não tem quantity!')
            team_quantities[team_number] += af_item['quantity']

            af_type = af_item['unit_type']
            if air_force_data['classes'].get(af_type) is None:
                raise Exception('Não existe uma classe de exército chamada ' + str(af_type) + '!')

            batch_size = air_force_data['classes'][af_type]['batch_size']
            batches = af_item['quantity'] // batch_size
            remaining_batch = af_item['quantity'] % batch_size
            for i in range(batches):
                v.append(Unit(
                    team=team,
                    type=af_type,
                    hp=air_force_data['classes'][af_type]['hp'],
                    ATK=air_force_data['classes'][af_type]['ATK'],
                    DEF=air_force_data['classes'][af_type]['DEF'],
                    cannot_attack=set(air_force_data['classes'][af_type]['cannot_attack']),
                    advantage_against=set(air_force_data['classes'][af_type]['advantage_against']),
                    game_scenario=game_scenario,
                    prob_hit=air_force_data['classes'][af_type]['prob_hit'],
                    condition_to_hit=air_force_condition,
                    multiple=batch_size
                ))
            if remaining_batch > 0:
                v.append(Unit(
                    team=team,
                    type=af_type,
                    hp=navy_data['classes'][af_type]['hp'],
                    ATK=navy_data['classes'][af_type]['ATK'],
                    DEF=navy_data['classes'][af_type]['DEF'],
                    cannot_attack=set(air_force_data['classes'][af_type]['cannot_attack']),
                    advantage_against=set(air_force_data['classes'][af_type]['advantage_against']),
                    game_scenario=game_scenario,
                    prob_hit=navy_data['classes'][af_type]['prob_hit'],
                    condition_to_hit=air_force_condition(af_type),
                    multiple=remaining_batch
                ))

    game_scenario.set_new_army_size(*team_quantities)

    return a_units, b_units, game_scenario
Example #56
0
class TestUnit(unittest.TestCase):
    def setUp(self):
        self.test_soldier = Unit(health=200, mana=100)
        self.default_weapon = Weapon()
        self.default_spell = Spell()

    def test_create_instance_invalid_input_should_type_error_error(self):
        with self.assertRaises(TypeError):
            Unit(health='asd', mana=100)

    def test_create_instance_negative_health_should_raise_value_error(self):
        with self.assertRaises(ValueError):
            Unit(health=-20, mana=20)

    def test_create_instance_negative_mana_should_raise_value_error(self):
        with self.assertRaises(ValueError):
            Unit(health=20, mana=-20)

    def test_can_cast(self):
        self.setUp()
        n = self.test_soldier
        self.assertFalse(n.can_cast())

    def test_can_cast_not_enough_mana(self):
        self.setUp()
        n = self.test_soldier
        n.learn_spell(Spell('Fireball', damage=50, mana_cost=120, cast_range=3))
        self.assertFalse(n.can_cast())

    def test_can_cast_all_okay(self):
        self.setUp()
        self.test_soldier.learn_spell(self.default_spell)
        self.assertTrue(self.test_soldier.can_cast())

    def test_take_damage_int(self):
        self.setUp()
        npc = self.test_soldier
        npc.take_damage(20)
        self.assertEqual(npc.health, 180)

    def test_take_damage_float(self):
        self.setUp()
        npc = self.test_soldier
        npc.take_damage(10.5)
        self.assertEqual(npc.health, 189.5)

    def test_take_damage_more_damage_than_hp_should_return_0(self):
        npc = Unit(health=20, mana=50)
        npc.take_damage(30)
        self.assertEqual(npc.get_health(), 0)

    def test_take_damage_should_raise_type_error_invalid_input(self):
        self.setUp()
        with self.assertRaises(TypeError):
            npc = self.test_soldier
            npc.take_damage('asd')

    def test_take_damage_raises_value_error_negative_value(self):
        self.setUp()
        with self.assertRaises(ValueError):
            npc = self.test_soldier
            npc.take_damage(-20)

    def test_take_healing_should_not_get_over_max_hp(self):
        self.setUp()
        npc = self.test_soldier
        npc.take_damage(20)
        npc.take_healing(30)
        self.assertEqual(npc.get_health(), 200)

    def test_healing_msg_if_instance_is_dead(self):
        self.setUp()
        npc = self.test_soldier
        npc.health = 0
        self.assertEqual(npc.take_healing(20), 'Cannot heal a corpse!')

    def test_healing_heals(self):
        self.setUp()
        n = self.test_soldier
        n.take_damage(50)
        n.take_healing(20)
        self.assertEqual(n.health, 170)

    def test_equip_weapon(self):
        self.setUp()
        npc = self.test_soldier
        npc.equip_weapon(self.default_weapon)
        self.assertEqual(npc.weapon, self.default_weapon)

    def test_learn_spell(self):
        self.setUp()
        npc = self.test_soldier
        npc.learn_spell(self.default_spell)
        self.assertEqual(npc.spell, self.default_spell)

    def test_equip_weapon_invalid_instance_raises_type_error(self):
        self.setUp()
        with self.assertRaises(TypeError):
            self.test_soldier.equip_weapon('asd')

    def test_learn_spell_invalid_instance_raises_type_error(self):
        self.setUp()
        with self.assertRaises(TypeError):
            self.test_soldier.learn_spell('asd')

    def test_take_mana_should_not_get_over_max_mana(self):
        self.setUp()
        npc = self.test_soldier
        npc.take_mana(20)
        npc.take_mana(30)
        self.assertEqual(npc.get_mana(), 100)

    def test_take_mana_should_raise_type_error_invalid_input(self):
        self.setUp()
        npc = self.test_soldier
        with self.assertRaises(TypeError):
            npc.take_mana('as')

    def test_take_mana_should_raise_value_error_negative_value(self):
        self.setUp()
        n = self.test_soldier
        with self.assertRaises(ValueError):
            n.take_mana(-20)

    def test_get_damage_source_weapon_and_spell(self):
        self.setUp()
        n = self.test_soldier
        n.equip_weapon(self.default_weapon)
        n.learn_spell(Spell(name='asd', damage=20, mana_cost=30, cast_range=2))
        self.assertEqual(n.get_damage_source(), 'spell')

    def test_get_damage_source_weapon_and_spell_wepaon_higher_damage(self):
        self.setUp()
        n = self.test_soldier
        n.equip_weapon(Weapon(name='asd', damage=50))
        n.learn_spell(self.default_spell)
        self.assertEqual(n.get_damage_source(), 'weapon')

    def test_get_damage_source_weapon_only(self):
        self.setUp()
        n = self.test_soldier
        n.equip_weapon(self.default_weapon)
        self.assertEqual(n.get_damage_source(), 'weapon')

    def test_get_damage_source_spell_only(self):
        self.setUp()
        n = self.test_soldier
        n.learn_spell(self.default_spell)
        self.assertEqual(n.get_damage_source(), 'spell')

    def test_get_damage_source_no_weapon_spell(self):
        self.setUp()
        n = self.test_soldier
        self.assertEqual(n.get_damage_source(), None)
Example #57
0
 def update(self, deltaTime):
     Unit.update(self, deltaTime)
Example #58
0
 def setUp(self):
     self.test_soldier = Unit(health=200, mana=100)
     self.default_weapon = Weapon()
     self.default_spell = Spell()
Example #59
0
 def add_unit(self, name, x, y):
     self.units.append(Unit(name, x, y))
Example #60
0
 def __init__(self, val=0, name="Scalar"):
     self.value = val
     self.unit = Unit()
     self.name = name