示例#1
0
class RamboStateStanding(State):
    name = "standing"

    def __init__(self, brain):
        super().__init__(brain)
        self.canAttackTimer = Timer()


    def on_enter(self):
        self.canAttackTimer.setTimer(2.0)

        meGroupId = self.brain.owner.world.component_for_entity(
                self.brain.owner.entity, system.groupid.GroupId)
        messaging.add(
            type=MessageType.EntityStanding,
            groupId=meGroupId.getId(),
            data=None
        )

    def process(self, dt):
        self.canAttackTimer.advance(dt)
        self.tryAttack()


    def tryAttack(self):
        if self.canAttackTimer.timeIsUp():
            self.brain.pop()
            self.brain.push("attacking")
示例#2
0
class SceneLogo(SceneBase):
    def __init__(self, viewport, world):
        super().__init__(world=world, viewport=viewport)

        # teh logo
        coordinates = Coordinates(2, 5)
        textureLogo = PhenomenaTexture(phenomenaType=PhenomenaType.intro)
        self.renderableLogo = Renderable(
            texture=textureLogo,
            viewport=self.viewport,
            coordinates=coordinates,
            active=True,
        )

        self.anyKeyFinishesScene = True

        self.timer = Timer(3)
        self.sceneFinished = False
        self.name = "Scene0 - Logo"

    def enter(self):
        self.addRenderable(self.renderableLogo)

    def sceneIsFinished(self):
        if self.timer.timeIsUp():
            return True
        else:
            return False

    def advance(self, dt):
        self.timer.advance(dt)
示例#3
0
    def __init__(self,
                 initialHealth=100,
                 stunTime=0.75,
                 stunCount=3,
                 stunTimeFrame=3,
                 knockdownChance=0.0,
                 knockbackChance=0.0):
        self.health = initialHealth
        self.initialHealth = initialHealth

        self.knockdownChance = knockdownChance
        self.knockbackChance = knockbackChance

        self.maxStunCount = stunCount
        self.stunTimeFrame = stunTimeFrame
        self.stunTime = stunTime
        self.isStunned = False
        self.stunTimer = Timer(0.0)
        self.stunTimer.setActive(False)
        self.stunnedQueue = collections.deque(maxlen=5)

        # after message GameRestart, all Renderables are deleted - but not until
        # the next advance(). Upon restarting the map, if the user presses a key,
        # checkHeal() in AttackableProcessor would emit yet another stray
        # GameOver message. This is the fix.
        self.isActive = True
示例#4
0
 def __init__(self, brain):
     State.__init__(self, brain)
     meEnemy = self.brain.owner.world.component_for_entity(
         self.brain.owner.entity, system.gamelogic.enemy.Enemy)
     self.lastInputTimer = Timer(meEnemy.enemyInfo.wanderStepDelay, instant=True)
     self.destCoord = Coordinates()
     self.destIsPoint = False
示例#5
0
    def __init__(self):
        self.name = 'Player'
        self.points = 0
        self.isPlayer = True
        self.isAttacking = False
        self.isAlive = True

        self.attackTimer = Timer(0.0)
示例#6
0
    def __init__(self, type, width=0, height=0, name=''):
        self.type = type
        self.width: int = width
        self.height: int = height
        self.active: bool = True
        self.name = name

        # color related
        self.overwriteColorTimer = Timer(0.25, active=False)
        self.overwriteColor = None
示例#7
0
 def __init__(self, viewport, sceneManager):
     super().__init__()
     self.viewport = viewport
     self.sceneManager = sceneManager
     self.xCenter = Config.columns / 2 - 5
     self.state = State.start
     self.screenMoveTimer = Timer(0.1)
     self.lastKnownPlayerPos = None
     self.gameoverTimer = Timer(3.0,
                                active=False)  # show gameover for this long
示例#8
0
class Player():
    def __init__(self):
        self.name = 'Player'
        self.points = 0
        self.isPlayer = True
        self.isAttacking = False
        self.isAlive = True

        self.attackTimer = Timer(0.0)

    def advance(self, deltaTime: float):
        self.attackTimer.advance(deltaTime)

        if self.attackTimer.timeIsUp():
            self.isAttacking = False
            self.attackTimer.setActive(False)

    def setAttacking(self, attackTime: float):
        self.isAttacking = True

        self.attackTimer.setTimer(attackTime)
        self.attackTimer.start()

    def setAlive(self, alive):
        self.isAlive = alive

    def __repr__(self):
        return "Player"
示例#9
0
class Defense():
    def __init__(self):
        self.coordinates = None
        self.timer = Timer(1.0)
        self.isActive = False

    def advance(self, dt):
        self.timer.advance(dt)

        if self.timer.timeIsUp():
            self.isActive = False
示例#10
0
    def __init__(self, viewport, world):
        super().__init__(world=world, viewport=viewport)

        self.textureEmiter = TextureEmiter(viewport=viewport, world=world)
        renderableCache.init(viewport=viewport)

        textureCopter = PhenomenaTexture(
            phenomenaType=PhenomenaType.roflcopter,
            name="Scene1 chopper")
        self.copterSpawn = Coordinates(13, -1 * textureCopter.height)
        renderableCopter = Renderable(
            texture=textureCopter,
            viewport=self.viewport,
            coordinates=self.copterSpawn,
            active=True,
        )

        texturePlayer = CharacterTexture(
            characterAnimationType=CharacterAnimationType.standing,
            characterTextureType=CharacterTextureType.player,
            name='Scene1 Player')
        coordinates = Coordinates(24, 13)
        renderablePlayer = Renderable(
            texture=texturePlayer,
            viewport=self.viewport,
            coordinates=coordinates,
            active=True,
        )

        textureEnemy = CharacterTexture(
            characterAnimationType=CharacterAnimationType.standing,
            characterTextureType=CharacterTextureType.player,
            name='Scene1 Enemy')
        coordinates = Coordinates(Config.columns, 13)
        renderableEnemy = Renderable(
            texture=textureEnemy,
            viewport=self.viewport,
            coordinates=coordinates,
            active=True,
        )

        self.renderableCopter = renderableCopter
        self.renderablePlayer = renderablePlayer
        self.renderableEnemy = renderableEnemy

        self.myTimer = Timer(0.5)
        self.state = IntroSceneState.wait1
        self.name = "Scene1 - Intro Animation"
        self.anyKeyFinishesScene = True

        self.init()
示例#11
0
    def __init__(self, brain):
        State.__init__(self, brain)
        meEnemy = self.brain.owner.world.component_for_entity(
            self.brain.owner.entity, system.gamelogic.enemy.Enemy)

        # basically move speed
        self.lastInputTimer = Timer(meEnemy.enemyInfo.chaseStepDelay,
                                    instant=True)

        # try attacking when timer is finished
        self.canAttackTimer = Timer()

        # we need to know player location, or we could just handle on every new
        # PlayerLocation message
        self.lastKnownPlayerPosition = None
示例#12
0
class Texture(object):
    def __init__(self, type, width=0, height=0, name=''):
        self.type = type
        self.width: int = width
        self.height: int = height
        self.active: bool = True
        self.name = name

        # color related
        self.overwriteColorTimer = Timer(0.25, active=False)
        self.overwriteColor = None

    def init(self):
        pass

    def draw(self, viewport):
        pass

    def advance(self, deltaTime: float):
        # reset overwrite color
        if self.overwriteColorTimer.timeIsUp():
            self.overwriteColor = None
            self.overwriteColorTimer.stop()
        self.overwriteColorTimer.advance(deltaTime)

    def setOverwriteColorFor(self, time: float, color: Color):
        if self.overwriteColorTimer.isActive():
            logger.debug("{} Color already active on new set color".format(
                self.name))

        self.overwriteColor = color
        self.overwriteColorTimer.setTimer(time)
        self.overwriteColorTimer.reset()

    def advanceStep(self):
        pass

    def setActive(self, active: bool):
        self.active = active

    def isActive(self) -> bool:
        return self.active

    def setName(self, name: str):
        self.name = name

    def __repr__(self):
        return self.name
 async def on_voice_state_update(self, member: discord.Member,
                                 before: discord.VoiceState,
                                 after: discord.VoiceState):
     voice_client: discord.voice_client = member.guild.voice_client
     if voice_client and voice_client.channel.members.__len__() == 1:
         Timer(TIMEOUT_VALUE,
               self.voice_client_disconnect_check,
               parameter=member.guild)
示例#14
0
class DragonStateChase(StateChase):
    def __init__(self, brain):
        super().__init__(brain)
        self.canSkillTimer = Timer()

    def on_enter(self):
        super().on_enter()
        self.canSkillTimer.setTimer(3.0)

    def process(self, dt):
        super().process(dt)
        self.canSkillTimer.advance(dt)

    def trySkill(self):
        if self.canSkillTimer.timeIsUp():
            meRenderable = self.brain.owner.world.component_for_entity(
                self.brain.owner.entity, system.graphics.renderable.Renderable)
            locCenter = meRenderable.getLocationCenter()
            messaging.add(type=MessageType.EmitParticleEffect,
                          data={
                              'location': locCenter,
                              'effectType': ParticleEffectType.dragonExplosion,
                              'damage': 50,
                              'byPlayer': False,
                              'direction': Direction.none,
                          })
            self.canSkillTimer.reset()
示例#15
0
    def __init__(self, viewport, world):
        super().__init__(world=world, viewport=viewport)

        # teh logo
        coordinates = Coordinates(2, 5)
        textureLogo = PhenomenaTexture(phenomenaType=PhenomenaType.intro)
        self.renderableLogo = Renderable(
            texture=textureLogo,
            viewport=self.viewport,
            coordinates=coordinates,
            active=True,
        )

        self.anyKeyFinishesScene = True

        self.timer = Timer(3)
        self.sceneFinished = False
        self.name = "Scene0 - Logo"
示例#16
0
    def __init__(
        self,
        char: str,
        colorArr,
        timeArr,
        movementX: int = 0,
        movementY: int = 0,
    ):
        self.width = 1
        self.height = 1
        self.char = char
        self.movementX = movementX
        self.movementY = movementY
        self.timeArr = timeArr
        self.colorArr = colorArr

        self.idx = 0
        self.timer = Timer(self.timeArr[0])
示例#17
0
class DamageStat(object):
    def __init__(self):
        self.damage = 100
        self.dmgTimer = Timer(1.0)


    def addDamage(self, damage):
        self.damage += damage


    def process(self, dt):
        self.dmgTimer.advance(dt)
        if self.dmgTimer.timeIsUp():
            self.dmg -= 10
            self.dmgTimer.reset()


    def getDamageStat(self):
        return self.damage
示例#18
0
    def __init__(self, parentChar, parentRenderable):
        self.parentChar = parentChar
        self.parentRenderable = parentRenderable

        self.cooldownTimer: Timer = Timer(Config.playerAttacksCd, instant=True)

        self.weaponType: WeaponType = WeaponType.hitWhip
        self.selectedWeaponKey: str = '1'

        # coordinates are based on left side orientation of renderable
        self.weaponBaseLocation = Coordinates(0, -1)
示例#19
0
 def get_death_animation(self):
     death_frames = []
     for file in os.listdir('assets/images/ship/dead'):
         if file.startswith('ship_death_') and file.endswith('.png'):
             death_frames.append(
                 pygame.transform.scale(
                     pygame.image.load('assets/images/ship/dead/' + file),
                     (84, 84)))
     return Timer(death_frames,
                  self.death_delay / len(death_frames),
                  loop_once=True)
示例#20
0
class TextureMinimal(object):
    def __init__(
        self,
        char: str,
        colorArr,
        timeArr,
        movementX: int = 0,
        movementY: int = 0,
    ):
        self.width = 1
        self.height = 1
        self.char = char
        self.movementX = movementX
        self.movementY = movementY
        self.timeArr = timeArr
        self.colorArr = colorArr

        self.idx = 0
        self.timer = Timer(self.timeArr[0])

    def advance(self, dt):
        self.timer.advance(dt)
示例#21
0
def load_file(path):
    t1 = Timer("Load text")
    dictionary, corpus = prepare_dict(path)
    t1.ends()
    t3 = Timer("LDA")
    #ldamodel = models.ldamodel.LdaModel(corpus, num_topics=NUM_TOPICS, id2word=dictionary, passes=PASSES)
    ldamodel = models.LdaMulticore(corpus, num_topics=NUM_TOPICS, id2word=dictionary, passes=PASSES, workers=2)
    t3.ends()
    country_dir = os.path.join(path, 'lda_results', country)
    if not os.path.isdir(country_dir):
        os.mkdir(country_dir)
    version_dir = os.path.join(country_dir, version)
    if not os.path.isdir(version_dir):
        os.mkdir(version_dir)
    ldamodel.save(os.path.join(path, 'lda_results', country, version, 'lda_model'))
    dictionary.save(os.path.join(path, 'lda_results', country, version, 'dictionary'))
示例#22
0
 def __init__(
     self,
     viewport =None,
     x :int =0,
     y :int =0,
     life :int =0,
     angle :float =0,
     speed :int =1,
     fadeout :bool =True,
     charType :int =0,
     byStep :bool =False,
     active :bool =False,
     damage :int =0,
     damageEveryStep :bool =False,
     byPlayer :bool =True,
 ):
     self.viewport = viewport
     self.movementTimer = Timer()
     self.init(
         x=x, y=y, life=life, angle=angle, speed=speed, fadeout=fadeout,
         byStep=byStep, charType=charType, active=active,
         damage=damage,
         damageEveryStep=damageEveryStep,
         byPlayer=byPlayer)
示例#23
0
def main() -> None:
    timer = Timer('Model training')

    model_trainer, images = set_up_components('base_model_location')

    model_trainer.train_and_save_all_models(images)
    model_trainer.charts.finalize()

    print('class 1: ' + images.class_labels[0] + ', class 2: ' +
          images.class_labels[1])
    timer.stop()
    timer.print_results()
示例#24
0
def main():
    # Start execution and parse arguments
    timer = Timer('Classifying a test set')
    image_folders, list_of_models, color_mode, image_size = process_input_arguments()

    # Import images
    images = LabeledImages(SEED)
    images.load_testing_images(image_folders, image_size, color_mode)
    print('Images imported.')

    combined_results = pd.DataFrame()

    combined_results['filename'] = images.test_img_names
    combined_results['actual_class'] = images.test_labels
    all_predictions = pd.DataFrame()

    for model_path in list_of_models:
        classify_images_with_a_model(images.class_labels, all_predictions, images, model_path)

    all_predictions['voted_probability'] = all_predictions.mean(axis=1)
    # calculate_confusion_matrix(combined_results)
    combined_results = combined_results.join(all_predictions)
    combined_results['tp'] = combined_results.eval('actual_class == 1 and voted_probability >= 0.5')
    combined_results['fn'] = combined_results.eval('actual_class == 1 and voted_probability < 0.5')
    combined_results['fp'] = combined_results.eval('actual_class == 0 and voted_probability >= 0.5')
    combined_results['tn'] = combined_results.eval('actual_class == 0 and voted_probability < 0.5')
    combined_results['voted_label'] = combined_results.eval('voted_probability >= 0.5')

    combined_results['tp'] = combined_results['tp'].map(lambda v: 1 if v else 0)
    combined_results['fn'] = combined_results['fn'].map(lambda v: 1 if v else 0)
    combined_results['fp'] = combined_results['fp'].map(lambda v: 1 if v else 0)
    combined_results['tn'] = combined_results['tn'].map(lambda v: 1 if v else 0)
    combined_results['voted_label'] = combined_results['voted_label'].map(lambda v: 1 if v else 0)

    combined_results.columns = ['filename', 'actual_class'] + list_of_models + \
                               ['voted_probability', 'tp', 'fn', 'fp', 'tn', 'voted_label']

    if not os.path.exists('predictions'):
        os.makedirs('predictions')
    write_dataframe_to_csv('predictions', 'model_vote_predict', combined_results)

    # Finish execution
    timer.stop()
    timer.print_results()
示例#25
0
class StateAttack(State):
    name = "attack"

    def __init__(self, brain):
        State.__init__(self, brain)
        self.attackTimer = Timer(instant=True)


    def on_enter(self):
        meEnemy = self.brain.owner.world.component_for_entity(
            self.brain.owner.entity, system.gamelogic.enemy.Enemy)
        meGroupId = self.brain.owner.world.component_for_entity(
            self.brain.owner.entity, system.groupid.GroupId)

        self.attackTimer.setTimer(meEnemy.enemyInfo.attackTime)
        self.setTimer(meEnemy.enemyInfo.attackStateTime)

        messaging.add(
            type=MessageType.EntityAttack,
            groupId=meGroupId.getId(),
            data=None
        )


    def process(self, dt):
        self.attackTimer.advance(dt)

        if self.attackTimer.timeIsUp():
            logger.info(self.name + " I'm attacking, via offensiveattack!")
            self.attackTimer.reset()
            offensiveAttack = self.brain.owner.world.component_for_entity(
                self.brain.owner.entity, OffensiveAttack)
            offensiveAttack.attack()

        if self.timeIsUp():
            # too long attacking. lets switch to chasing
            logger.info("{}: Too long attacking, switch to chasing".format(self.owner))
            self.brain.pop()
            self.brain.push("chase")
示例#26
0
    def __init__(self, esperData, viewport):
        self.esperData = esperData
        self.viewport = viewport

        self.skillStatus = [
            'q', 'w', 'e', 'r', 'f', 'g'
        ]

        self.keyAssignment = {
            'q': fileOffenseLoader.skillManager.getSkillData(SkillType.cleave),
            'w': fileOffenseLoader.skillManager.getSkillData(SkillType.laser),
            'e': fileOffenseLoader.skillManager.getSkillData(SkillType.block),
            'r': fileOffenseLoader.skillManager.getSkillData(SkillType.explosion),
            'f': fileOffenseLoader.skillManager.getSkillData(SkillType.heal),
            'g': fileOffenseLoader.skillManager.getSkillData(SkillType.port),
        }

        self.cooldownTimers = {}
        for key in self.keyAssignment:
            self.cooldownTimers[key] = Timer(
                self.keyAssignment[key].cooldown, instant=True)

        self.data = {
            SkillType.port: {
                'distance': 20,
            }
        }

        self.dispatch = {
            SkillType.explosion: self.skillExplosion,
            SkillType.laser: self.skillLaser,
            SkillType.cleave: self.skillCleave,
            SkillType.heal: self.skillHeal,
            SkillType.port: self.skillPort,
            SkillType.block: self.skillBlock,
        }
示例#27
0
class GameController(object):
    '''
    This class represents a skeleton from which game controls
    can inherit. It contains all the shared functionality of
    all game controls.
    '''

    def __init__(self, time):
        '''
        Ctor - Initialises game controller.
        '''
        self._timer = Timer(time)

    def set_up_game(self):
        '''
        Sets up the game to be played by this controller.
        '''
        self._game = Game()

    def get_game(self):
        '''
        Returns the game currently being played.
        '''
        return self._game

    def get_time_remaining(self):
        '''
        Returns the timer being used on this game controller.
        '''
        return self._timer.get_time_remaining()

    def play_next_turn(self):
        '''
        Plays a single turn of the game.
        '''
        self._game.next_turn()
示例#28
0
def main() -> None:
    timer = Timer('Model training')

    cnn_arguments = CNNArguments()
    new_images = LabeledImages(SEED)
    new_images.load_images_from_folders(cnn_arguments.training_image_folder,
                                        cnn_arguments.image_size,
                                        cnn_arguments.color_mode,
                                        shuffle=True,
                                        n_folds=cnn_arguments.n_folds)

    architecture = SmithsonianModel(SEED, cnn_arguments.lr,
                                    cnn_arguments.image_size,
                                    cnn_arguments.color_mode)
    trainer = ModelTrainer(cnn_arguments.n_epochs, cnn_arguments.batch_size,
                           cnn_arguments.n_folds, architecture, SEED)
    trainer.train_and_save_all_models(new_images)
    trainer.charts.finalize()

    print('class 1: ' + new_images.class_labels[0] + ', class 2: ' +
          new_images.class_labels[1])
    timer.stop()
    timer.print_results()
示例#29
0
class StateChase(State):
    name = "chase"

    def __init__(self, brain):
        State.__init__(self, brain)
        meEnemy = self.brain.owner.world.component_for_entity(
            self.brain.owner.entity, system.gamelogic.enemy.Enemy)

        # basically move speed
        self.lastInputTimer = Timer(meEnemy.enemyInfo.chaseStepDelay,
                                    instant=True)

        # try attacking when timer is finished
        self.canAttackTimer = Timer()

        # we need to know player location, or we could just handle on every new
        # PlayerLocation message
        self.lastKnownPlayerPosition = None

    def on_enter(self):
        meEnemy = self.brain.owner.world.component_for_entity(
            self.brain.owner.entity, system.gamelogic.enemy.Enemy)

        stateTimeRnd = random.randrange(-100 * meEnemy.enemyInfo.chaseTimeRnd,
                                        100 * meEnemy.enemyInfo.chaseTimeRnd)
        self.setTimer(meEnemy.enemyInfo.chaseTime + (stateTimeRnd / 100))

        self.canAttackTimer.setTimer(meEnemy.enemyInfo.enemyCanAttackPeriod)
        self.canAttackTimer.reset()

        if not Config.allowEnemyAttacking:
            self.canAttackTimer.setActive(False)

    def tryAttacking(self):
        if self.canAttackTimer.timeIsUp():
            logger.debug("{}: Check if i can attack player".format(self.name))
            if self.canAttackPlayer():
                if (EntityFinder.numEnemiesInState(self.brain.owner.world,
                                                   'attack') <
                        Config.maxEnemiesInStateAttacking):
                    self.brain.pop()
                    self.brain.push("attackwindup")

            self.canAttackTimer.reset()

    def tryMoving(self):
        # only move if we can not hit him (even on cooldown)
        # this is quiet... taxing. and not really necessary?
        # if not self.canAttackPlayer():

        if True:
            # movement speed, and direction
            if self.lastInputTimer.timeIsUp():
                self.getInputChase()
                self.lastInputTimer.reset()

    def trySkill(self):
        # stickfigure has no skills
        pass

    def process(self, dt):
        meAttackable = self.brain.owner.world.component_for_entity(
            self.brain.owner.entity, system.gamelogic.attackable.Attackable)

        if meAttackable.isStunned:
            return

        self.lastInputTimer.advance(dt)
        self.canAttackTimer.advance(dt)

        # update player position if new location
        self.checkForNewPlayerPosition()

        self.tryAttacking()
        # note that if we want to attack, as identified a few lines above,
        # we will be in state attackWindup, and not reach here
        self.trySkill()
        self.tryMoving()

        # switch to wander if exhausted
        if self.timeIsUp():
            logger.debug("{}: Too long chasing, switching to wander".format(
                self.owner))
            self.brain.pop()
            self.brain.push("wander")

    def checkForNewPlayerPosition(self):
        # check if there are any new player position messages
        for message in messaging.getByType(MessageType.PlayerLocation):
            self.lastKnownPlayerPosition = message.data

    def canAttackPlayer(self):
        if self.lastKnownPlayerPosition is None:
            # we may not yet have received a location.
            # find it directly via player entity
            # this is every time we go into chase state
            playerEntity = EntityFinder.findPlayer(self.brain.owner.world)
            # player not spawned
            if playerEntity is not None:
                playerRenderable = self.brain.owner.world.component_for_entity(
                    playerEntity, system.graphics.renderable.Renderable)
                self.lastKnownPlayerPosition = playerRenderable.getLocationAndSize(
                )

        canAttack = AiHelper.canAttackPlayer(self.brain.owner,
                                             self.lastKnownPlayerPosition)

        return canAttack

    def getInputChase(self):
        meGroupId = self.brain.owner.world.component_for_entity(
            self.brain.owner.entity, system.groupid.GroupId)
        meRenderable = self.brain.owner.world.component_for_entity(
            self.brain.owner.entity, system.graphics.renderable.Renderable)

        if not Config.allowEnemyMovement:
            return

        moveX, moveY, dontChangeDirection = AiHelper.getAttackVectorToPlayer(
            self.owner, meRenderable)

        # only move if we really move a character
        if moveX != 0 or moveY != 0:
            directMessaging.add(
                groupId=meGroupId.getId(),
                type=DirectMessageType.moveEnemy,
                data={
                    'x': moveX,
                    'y': moveY,
                    'dontChangeDirection': dontChangeDirection,
                    'updateTexture': True,
                    'force': False,
                },
            )
示例#30
0
 def __init__(self, brain):
     State.__init__(self, brain)
     self.attackMoveTimer = Timer()  # Timer(0.5, instant=False) # windup and cooldown
示例#31
0
class StateAttack(State):
    name = "attack"

    def __init__(self, brain):
        State.__init__(self, brain)
        self.attackMoveTimer = Timer()  # Timer(0.5, instant=False) # windup and cooldown


    def on_enter(self):
        meEnemy = self.brain.owner.world.component_for_entity(
            self.brain.owner.entity, system.gamelogic.enemy.Enemy)
        meGroupId = self.brain.owner.world.component_for_entity(
            self.brain.owner.entity, system.groupid.GroupId)

        messaging.add(
            type=MessageType.EntityAttack,
            groupId=meGroupId.getId(),
            data=None
        )

        # self.attackTimer.setTimer(meEnemy.enemyInfo.attackTime)
        # self.setTimer(meEnemy.enemyInfo.attackTime)
        self.stepsTodo = 30
        self.attackMoveTimer.init()
        self.attackMoveTimer.setTimer(0.1)
        self.setTimer(3.0)

        # even though we attack multiple times (each step)
        # only send EntityAttack once (change animation)
        messaging.add(
            type=MessageType.EntityAttack,
            groupId=meGroupId.getId(),
            data={}
        )


    def process(self, dt):
        self.attackMoveTimer.advance(dt)

        # check if we got stunned
        meAttackable = self.brain.owner.world.component_for_entity(
            self.brain.owner.entity, system.gamelogic.attackable.Attackable)
        if meAttackable.isStunned:
            self.brain.pop()
            self.brain.push("chase")

        # check if we should do one attack step
        if self.attackMoveTimer.timeIsUp():
            logger.info("{}: I'm attacking, step {}".format(self.owner, self.stepsTodo))

            if self.stepsTodo > 0:
                self.attackMoveTimer.reset()
                self.stepsTodo -= 1

                meRenderable = self.brain.owner.world.component_for_entity(
                    self.brain.owner.entity, Renderable)
                meGroupId = self.brain.owner.world.component_for_entity(
                    self.brain.owner.entity, system.groupid.GroupId)

                if self.stepsTodo % 2 == 0:
                    offensiveAttack = self.brain.owner.world.component_for_entity(
                        self.brain.owner.entity, OffensiveAttack)
                    offensiveAttack.attack()

                if meRenderable.direction is Direction.left:
                    x = -1
                else:
                    x = 1
                directMessaging.add(
                    groupId = meGroupId.getId(),
                    type = DirectMessageType.moveEnemy,
                    data = {
                        'x': x,
                        'y': 0,
                        'dontChangeDirection': False,
                        'updateTexture': False,
                        'force': True
                    },
                )
            else:
                self.attackMoveTimer.stop()

        if self.timeIsUp():
            # too long attacking. lets switch to chasing
            logger.info("{}: Too long attacking, switch to chasing".format(
                self.owner))
            self.brain.pop()
            self.brain.push("chase")
示例#32
0
 def __init__(self, time):
     '''
     Ctor - Initialises game controller.
     '''
     self._timer = Timer(time)