コード例 #1
0
    def create_monsters(self):
        monster_count = 3 + roll_dice(3) - 1
        # determining monster levels(by predefined chances), creating monsters
        for _ in range(monster_count):
            self.monsters.append(Monster(generate_monster_level(self.level)))
        # and for the boss
        self.boss = Boss(generate_monster_level(self.level))
        # let's add the boss to the monsters list, just for simplicity
        self.monsters.append(self.boss)

        # finding random floors for placing the monsters
        placed_floors = []
        # this process includes the boss too, hence monster_count+1
        while len(placed_floors) < monster_count + 1:
            # 63 is the number of empty floors on the map
            rolled_dice = roll_dice(63)
            if rolled_dice == 1:
                continue
            if rolled_dice not in placed_floors:
                # placing the monster at floor
                x, y = self.map.get_nth_floor(rolled_dice)
                self.monsters[len(placed_floors) - 1].place(x, y)
                placed_floors.append(rolled_dice)

        # giving the key to the next area, to one of the 3 monsters
        key_holder = roll_dice(monster_count) - 1
        self.monsters[key_holder].give_the_key()
コード例 #2
0
    def __init__(self, name):
        Scheduler._instance = self
        self._name = string.lower(name)
        self._boss = Boss()
        self.protocolDict = { 'CAF'      : 'rfio' , \
                              'LSF'      : 'rfio' , \
                              'PBS'      : 'rfio' , \
                              'CONDOR_G' : 'srm-lcg' , \
                              'GLITE'    : 'srm-lcg' , \
                              'GLIDEIN'  : 'srm-lcg' , \
                              'CONDOR'   : 'srm-lcg',  \
                              'REMOTEGLIDEIN'  : 'srm-lcg',  \
                              'SGE'      : 'srm-lcg', \
                              'ARC'      : 'srm-lcg', \
                              'PBSV2'    : 'srm-lcg', \
                              'SLURM'    : 'srm-lcg',
                            }

        self.protocolOpt = { 'rfio' : '', \
                             'xrootd' : '', \
                             'srmv2' : '' ,  \
                             'srm-lcg' : '-b -D srmv2'
                            }

        return
コード例 #3
0
ファイル: scenary.py プロジェクト: sandee97/Jetpack-Joyride
    def prior(self):
        for x in range(8, 21):
            for y in range(7, 37):
                self.__scene[x][y] = self.__blue + Dragon[x -
                                                          8][y -
                                                             7] + self.__reset
        self.__scene[11][29] = self.__red + 'M' + self.__reset
        self.__scene[11][30] = self.__red + 'A' + self.__reset
        self.__scene[11][31] = self.__red + 'N' + self.__reset
        self.__scene[11][32] = self.__red + 'D' + self.__reset
        self.__scene[11][33] = self.__red + 'O' + self.__reset
        for i in range(9, 15):
            for j in range(100, 115):
                self.__scene[i][j] = magnet[i - 9][j - 100]
        for i in range(9, 15):
            for j in range(500, 515):
                self.__scene[i][j] = magnet[i - 9][j - 500]
        for i in range(9, 15):
            for j in range(1000, 1015):
                self.__scene[i][j] = magnet[i - 9][j - 1000]

        self.__vertical = createVbars()
        self._horizontal = createHbars()
        self._typical = createTbars()
        self.__clouds = createClouds()
        self.__coins = createCoins()
        for clo in self.__clouds:
            self.__scene = clo.create(self.__scene)
        self.__Enemies = creation_of_enemies()
        self.boo = Boss(1440, 20)
        self.boos.append(self.boo)
コード例 #4
0
ファイル: Scheduler.py プロジェクト: belforte/CRAB2
    def __init__(self, name):
        Scheduler._instance = self
        self._name = string.lower(name)
        self._boss = Boss()
        self.protocolDict = { 'CAF'      : 'rfio' , \
                              'LSF'      : 'rfio' , \
                              'PBS'      : 'rfio' , \
                              'CONDOR_G' : 'srm-lcg' , \
                              'GLITE'    : 'srm-lcg' , \
                              'GLIDEIN'  : 'srm-lcg' , \
                              'CONDOR'   : 'srm-lcg',  \
                              'REMOTEGLIDEIN'  : 'srm-lcg',  \
                              'SGE'      : 'srm-lcg', \
                              'ARC'      : 'srm-lcg', \
                              'PBSV2'    : 'srm-lcg', \
                              'SLURM'    : 'srm-lcg',
                            }

        self.protocolOpt = { 'rfio' : '', \
                             'xrootd' : '', \
                             'srmv2' : '' ,  \
                             'srm-lcg' : '-b -D srmv2'
                            }

        return
コード例 #5
0
ファイル: MoneyPenny.py プロジェクト: GK230/JamesBond
 def enter(self):
     print("You are James Bond.")
     print("You enter MoneyPenny's office.")
     print("You flirt with him for a while, then M interupts.")
     print("She wants to see you immediately.")
     response = input("Do you respond instantly?")
     if response == "yes":
         Boss.enter()
     elif response == "no":
         print(
             "M, angrily wants to know why you are keeping the nation waiting"
         )
         Boss.enter()
     else:
         print("That is not an appropriate response.")
         MoneyPenny.enter(self)
コード例 #6
0
def enter():
    global kirby, sky, coin1, coin2, coin3, coin4, monster, monster1, monster2, current_time, boss, item
    kirby = Kirby()
    sky = Sky()
    coin1 = Coin1()
    coin2 = Coin2()
    coin3 = Coin3()
    coin4 = Coin4()
    item = Item()
    boss = Boss()
    monster = [Monster() for i in range(3) ]
    monster1 = [Monster1(i) for i in range(2)]
    monster2 = Monster2()
    game_framework.reset_time()
コード例 #7
0
    def generateWave(self):
        waveEnemies = [Goblin(), Beast(), Boss()]

        #only spawn enemies if wave spawn counter is greater than 0, keeps track of how many enemies we need to generate
        if self.waveSpawnCounter > 0:
            randEnemy = choice(waveEnemies, 1, p=[.5, .3, .2])
            # append enemy object into our list of enemies
            self.enemies.append(randEnemy[0])
            #decrement the count
            self.waveSpawnCounter -= 1

        # if there are no more enemies to be spawned
        if self.waveSpawnCounter == 0:
            #make sure that there are no enemies in the list, meaning that round is over
            if len(self.enemies) == 0:
                self.wave += 1
                self.waveSpawnCounter = self.wave * 5
                #set pause back to true
                self.pause = True
                #change the image
                self.playPauseButton.changeImage()
コード例 #8
0
def update():
    global dragons, boss, record, fire_timer, fireball

    if fire_timer >= 800 - eru.stage_level * 100:
        fireball = FireBall()
        game_world.add_object(fireball, 1)
        fire_timer = 0

    else:
        fire_timer += 1

    if len(dragons) <= 0 and eru.stage_level < 4:
        dragons = [Dragon(i, eru.stage_level) for i in range(5)]
        game_world.add_objects(dragons, 1)

    if eru.stage_level == 4 and boss is None:
        boss = Boss()
        game_world.add_object(boss, 1)

    if eru.remain_hp <= 0:
        record = eru.distance
        eru.death_sound.play(1)
        game_framework.change_state(ranking_state)

    if boss is not None and boss.hp <= 0:
        boss.ending_timer += 1

        if boss.ending_timer == 1:
            boss.win_sound.play(1)

    if boss is not None and boss.ending_timer >= 500:
        boss = None
        record = eru.distance
        game_framework.change_state(ranking_state)

    for game_object in game_world.all_objects():
        game_object.update()
コード例 #9
0
ファイル: MoneyPenny.py プロジェクト: GK230/JamesBond
from Boss import Boss


class MoneyPenny(object):
    def enter(self):
        print("You are James Bond.")
        print("You enter MoneyPenny's office.")
        print("You flirt with him for a while, then M interupts.")
        print("She wants to see you immediately.")
        response = input("Do you respond instantly?")
        if response == "yes":
            Boss.enter()
        elif response == "no":
            print(
                "M, angrily wants to know why you are keeping the nation waiting"
            )
            Boss.enter()
        else:
            print("That is not an appropriate response.")
            MoneyPenny.enter(self)


Boss = Boss()
play = MoneyPenny()
play.enter()
コード例 #10
0
    def on_update(self, delta_time):
        if not self.off:
            self.time = self.time + 1
            self.gui.votes_count = int(CONST.MAX_VOTES - (self.time / 60 * 2))

            # Create supporter
            if self.time % (self.spawn_interval * 30) == 0:
                r = random.random()
                if r < CONST.REDNECK_PROBABILITY:
                    s = Redneck(1)
                else:
                    s = ProTrump(1)
                self.supporters.append(s)
            if self.gui.votes_count <= 60 and not self.boss:
                self.supporters.append(Boss(1))
                self.boss = True

            # Distribute events
            self.distribute_events()

            self.player.update()
            self.tweet.update()

            for s in self.supporters:
                s.boost_speed = max(
                    1, self.tweet.activated * CONST.TWEET_SPEED_BOOST)
            self.boost_speed = max(
                1, self.tweet.activated * CONST.TWEET_SPEED_BOOST)

            for b in self.bullets:
                b.update()
            for s in self.supporters:
                if s.type == "Redneck":
                    s.update(self.player.sprite.center_x,
                             self.player.sprite.center_y)
                else:
                    s.update()

            # Fire a bullet
            bullet = self.player.fire(self.mouse_x, self.mouse_y)
            if bullet != None:
                self.bullets.append(bullet)

            if self.coequipier is not None:
                nearest = None
                dist = 1e9
                for s in self.supporters:
                    d = math.sqrt(
                        (s.sprite.center_x - CONST.SCREEN_WIDTH / 2)**2 +
                        (s.sprite.center_y - CONST.SCREEN_HEIGHT / 2)**2)
                    if d < dist and d < self.coequipier.range:
                        dist = d
                        nearest = s
                if nearest is not None:
                    bullet = self.coequipier.fire(nearest.sprite.center_x,
                                                  nearest.sprite.center_y)
                    if bullet != None:
                        self.bullets.append(bullet)

            for b in self.bullets:
                b.update()
                for s in self.supporters:
                    if arcade.check_for_collision(
                            b.sprite, s.sprite) and b.last_touch != s:
                        s.hit_points -= b.damage
                        if s.hit_points <= 0:
                            self.gui.dollars_count += s.cashprize
                        b.last_touch = s
                        b.hit_points -= 1
                        break
            self.bullets = [b for b in self.bullets if b.hit_points > 0]
            self.supporters = [s for s in self.supporters if s.hit_points > 0]

            # Remove bullets
            self.bullets = [
                b for b in self.bullets
                if b.sprite.right > 0 and b.sprite.left <
                (CONST.SCREEN_WIDTH - 1) and b.sprite.bottom > 0
                and b.sprite.top < (CONST.SCREEN_HEIGHT - 1)
            ]

            # Collisions player <-> supporters
            stunned = False
            for s in self.supporters:
                if arcade.check_for_collision(self.player.sprite, s.sprite):
                    if s.type == "Redneck":
                        s.hit_points -= CONST.REDNECK_HP_DECREASE
                        s.is_on_player = True
                    self.player.stun = True
                    stunned = True
            if not stunned:
                self.player.stun = False
            self.supporters = [s for s in self.supporters if s.hit_points > 0]

            # Collisions capitol <-> supporters
            for s in self.supporters:
                if arcade.check_for_collision(self.capitol.sprite, s.sprite):
                    self.capitol.hit(s.damage)
                    s.hit_points = 0
            self.supporters = [s for s in self.supporters if s.hit_points > 0]

            # Collisions capitol <-> bullets
            for b in self.bullets:
                if arcade.check_for_collision(
                        self.capitol.sprite,
                        b.sprite) and b.sender != "Coequipier":
                    b.hit_points = 0
            self.bullets = [b for b in self.bullets if b.hit_points > 0]

            self.check_sound()
            """ ENDING CONDITIONS """
            if self.capitol.hit_point <= 0:
                self.win_state = 0
                self.end_game()
            """ WIN CONDITIONS """
            if self.gui.votes_count <= 0:
                self.win_state = 1
                self.end_game()

            if self.music.get_stream_position(self.current_player) == 0.0:
                #    self.advance_song()
                self.play_song()
コード例 #11
0
class Scheduler:

    _instance = None

    def getInstance():
        if not Scheduler._instance:
            raise CrabException('Scheduler has no instance.')
        return Scheduler._instance

    getInstance = staticmethod(getInstance)

    def __init__(self, name):
        Scheduler._instance = self
        self._name = string.lower(name)
        self._boss = Boss()
        self.protocolDict = { 'CAF'      : 'rfio' , \
                              'LSF'      : 'rfio' , \
                              'PBS'      : 'rfio' , \
                              'CONDOR_G' : 'srm-lcg' , \
                              'GLITE'    : 'srm-lcg' , \
                              'GLIDEIN'  : 'srm-lcg' , \
                              'CONDOR'   : 'srm-lcg',  \
                              'REMOTEGLIDEIN'  : 'srm-lcg',  \
                              'SGE'      : 'srm-lcg', \
                              'ARC'      : 'srm-lcg', \
                              'PBSV2'    : 'srm-lcg', \
                              'SLURM'    : 'srm-lcg',
                            }

        self.protocolOpt = { 'rfio' : '', \
                             'xrootd' : '', \
                             'srmv2' : '' ,  \
                             'srm-lcg' : '-b -D srmv2'
                            }

        return

    def name(self):
        return self._name

    def realSchedParams(self, cfg_params):
        """
        """
        return {}

    def configure(self, cfg_params):
        self._boss.configure(cfg_params)
        self.CRAB_useServer = cfg_params.get('CRAB.use_server', 0)
        self.CRAB_serverName = cfg_params.get('CRAB.server_name', None)
        seWhiteList = cfg_params.get('GRID.se_white_list', [])
        seBlackList = cfg_params.get('GRID.se_black_list', [])
        self.dontCheckMyProxy = int(
            cfg_params.get("GRID.dont_check_myproxy", 0))
        self.EDG_requirements = cfg_params.get('GRID.requirements', None)
        self.EDG_addJdlParam = cfg_params.get('GRID.additional_jdl_parameters',
                                              None)
        if (self.EDG_addJdlParam):
            self.EDG_addJdlParam = string.split(self.EDG_addJdlParam, ';')

        self.pset = cfg_params.get('CMSSW.pset', None)
        self.blackWhiteListParser = SEBlackWhiteListParser(
            seWhiteList, seBlackList, common.logger())

        self.return_data = int(cfg_params.get('USER.return_data', 0))
        self.copy_data = int(cfg_params.get('USER.copy_data', 0))
        self.publish_data = cfg_params.get("USER.publish_data", 0)
        self.local_stage = int(cfg_params.get('USER.local_stage_out', 0))
        self.check_RemoteDir = int(
            cfg_params.get('USER.check_user_remote_dir', 1))

        if int(self.copy_data) == 1:
            self.SE = cfg_params.get('USER.storage_element', None)
            if not self.SE:
                msg = "Error. The [USER] section does not have 'storage_element'"
                common.logger.info(msg)
                raise CrabException(msg)

        if (int(self.return_data) == 0 and int(self.copy_data) == 0):
            msg = 'Error: return_data = 0 and copy_data = 0 ==> your exe output will be lost\n'
            msg = msg + 'Please modify return_data and copy_data value in your crab.cfg file\n'
            raise CrabException(msg)

        if (int(self.return_data) == 1 and int(self.copy_data) == 1):
            msg = 'Error: return_data and copy_data cannot be set both to 1\n'
            msg = msg + 'Please modify return_data or copy_data value in your crab.cfg file\n'
            raise CrabException(msg)

        if (int(self.copy_data) == 0 and int(self.local_stage) == 1):
            msg = 'Error: copy_data = 0 and local_stage_out = 1.\n'
            msg += 'To enable local stage out the copy_data value has to be = 1\n'
            msg = msg + 'Please modify copy_data value in your crab.cfg file\n'
            raise CrabException(msg)

        if (int(self.copy_data) == 0 and int(self.publish_data) == 1):
            msg = 'Error: publish_data = 1 must be used with copy_data = 1\n'
            msg = msg + 'Please modify copy_data value in your crab.cfg file\n'
            common.logger.info(msg)
            raise CrabException(msg)

        if (int(self.publish_data) == 1 and self._name == 'lsf'):
            msg = 'Error: data publication is not allowed with lsf scheduler, but only with grid scheduler or caf\n'
            common.logger.info(msg)
            raise CrabException(msg)

        self.debug_wrapper = int(cfg_params.get('USER.debug_wrapper', 0))
        self.debugWrap = ''
        if self.debug_wrapper == 1: self.debugWrap = '--debug'
        self.loc_stage_out = ''
        if (int(self.local_stage) == 1):
            self.debugWrap = '--debug'
            self.loc_stage_out = '--local_stage'

        # Time padding for minimal job duration.
        self.minimal_job_duration = 10

        self.proxyValid = 0
        self.dontCheckProxy = int(cfg_params.get("GRID.dont_check_proxy", 0))
        self.proxyServer = 'myproxy.cern.ch'
        self.group = cfg_params.get("GRID.group", None)
        self.role = cfg_params.get("GRID.role", None)
        self.checkProxy()

        return

    def boss(self):
        return self._boss

    def rb_configure(self, RB):
        """
        Return a requirement to be add to Jdl to select a specific RB/WMS:
        return None if RB=None
        To be re-implemented in concrete scheduler
        """
        return None

    def ce_list(self):
        return '', None, None

    def se_list(self, id, dest):
        return '', None, None

    def sched_fix_parameter(self):
        return

    def sched_parameter(self, i, task):
        """
        Returns parameter scheduler-specific, to use with BOSS .
        """
        return ''

    def wsSetupEnvironment(self):
        """
        Returns part of a job script which does scheduler-specific work.
        """
        return ''

    def wsExitFunc(self):
        """
        Returns part of a job script which does scheduler-specific
        output checks and management.
        """
        return ''

    def checkRemoteDir(self, endpoint, fileList):
        """
        """

        common.logger.info('Checking remote location')
        ## temporary hack for OctX:
        if endpoint.find('${PSETHASH}') > 1:
            try:
                jdir = common.work_space.jobDir()
                ### FEDE bug fix 93573
                psethash = string.strip(
                    runCommand('cd %s; edmConfigHash CMSSW.py|tail -1' % jdir))
                endpoint = string.replace(endpoint, '${PSETHASH}', psethash)
                #####################
            except:
                msg = 'Problems with PSETHASH during remote dir check... \n'
                msg += '\tPlease check stage out configuration parameters.\n'
                raise CrabException(msg)
        try:
            remoteListTmp = self.listRemoteDir(endpoint)
        except Exception, ex:
            msg = 'WARNING: Problems trying remote dir check: \n\t%s' % str(ex)
            msg += '\nWARNING: Stage out of output files may fail'
            common.logger.info(msg)
            remoteListTmp = False
        if remoteListTmp is False:
            return
        if remoteListTmp == []:
            return
        if remoteListTmp:
            listJob = common._db.nJobs('list')
            remoteList = []
            for f_path in remoteListTmp:
                remoteList.append(str(os.path.basename(f_path)))
            metaList = []
            for id in listJob:
                for file in fileList:
                    metaList.append('%s' % numberFile(file, id))
            for remote in remoteList:
                for meta in metaList:
                    metaPrePost = meta.split('.')
                    if remote.startswith(metaPrePost[0]) and remote.endswith(
                            metaPrePost[1]):
                        msg = 'Error: You are asking to stage out on a remote directory \n'
                        msg += '\twhich already contains files with same name.\n'
                        msg += '\tThe endpoint is ' + endpoint + '\n'
                        msg += '\tPlease change directory or remove the actual content following this HowTo:\n'
                        msg += '\thttps://twiki.cern.ch/twiki/bin/view/CMS/CheckUserRemoteDir\n'
                        msg += '\n\tIt will be not possible to submit these jobs!\n'
                        raise CrabException(msg)
        else:
            msg = 'Remote directory is empty or not existis\n'
            common.logger.debug(msg)

        return
コード例 #12
0
ファイル: scenary.py プロジェクト: sandee97/Jetpack-Joyride
class Scenary(Player, Enemy):
    def __init__(self):
        self.Up = False
        self.Right = False
        self.left = False
        self.__maxx = 990
        self.__minx = 3
        self.__miny = 1
        self.__maxy = 46
        self.__land = ['|' for x in range(0, 1500)]
        self.__scene = [[] for x in range(0, 50)]
        self.__Boundary = ['X' for x in range(0, 1500)]
        self.__space = [' ' for x in range(0, 1500)]
        self.__black = '\u001b[30;1m'
        self.__red = '\u001b[31;1m'
        self.__green = '\u001b[32;1m'
        self.__yellow = '\u001b[33;1m'
        self.__blue = '\u001b[34;1m'
        self.__magenta = '\u001b[35;1m'
        self.__cyan = '\u001b[36;1m'
        self.__white = '\u001b[37;1m'
        self._maxWidth = 1500
        self.player = Player()
        self.__reset = '\u001b[0m'
        self.__counter = 0
        self.__gravity = False
        self.bullets = False
        self.fired = False
        self.__clouds = []
        self.__coins = []
        self.__Enemies = []
        self.__vertical = []
        self.__horizontal = []
        self.__typical = []
        self.score = 0
        self.shh = False
        self.speedBoost = False
        self.boo = 2
        self.DragonBull = []
        self.boos = []
        self.bullcounter = 0
        self.__bosslifes = 40
        self.time = 400
        self.__timing = time.time()

        for i in range(0, 50):
            if i == 0 or i == 47 or i == 49:
                self.__scene[i] = self.__Boundary[:]
            elif i == 48:
                self.__scene[i] = self.__land[:]
            else:
                self.__scene[i] = self.__space[:]

    def checkCollisions(self):
        if (self.player.posx >= 100 and self.player.posx <= 115
                and self.player.posycap - 5 > 9) or (
                    self.player.posx >= 500 and self.player.posx <= 515
                    and self.player.posycap - 5 > 9) or (
                        self.player.posx >= 1000 and self.player.posx <= 1015
                        and self.player.posycap - 5 > 9):
            self.Up = True
        if (self.player.posx >= 80 and self.player.posx <= 100) or (
                self.player.posx >= 480
                and self.player.posx <= 500) or (self.player.posx >= 980
                                                 and self.player.posx <= 1000):
            self.Right = True
        elif (self.player.posx >= 115 and self.player.posx <= 135) or (
                self.player.posx >= 515
                and self.player.posx <= 535) or (self.player.posx >= 1015
                                                 and self.player.posx <= 1035):
            self.left = True
        '''Bullet collision with enemy'''
        for ene in self.__Enemies:
            for bull in self.player.Bull:
                if ((bull.x >= ene.x and bull.x <= ene.x + 3) or
                    (bull.x + 1 >= ene.x and bull.x <= ene.x + 3)) and (
                        bull.y <= ene.y and bull.y >= ene.y - 3):
                    if ene.lives == 0:
                        if ene in self.__Enemies:
                            self.__Enemies.remove(ene)
                        self.score = self.score + 50
                    else:
                        ene.lives -= 1
                        self.player.Bull.remove(bull)
        '''Player collision with the enemy'''
        for ene in self.__Enemies:
            if (ene.x == self.player.posx + 2 or ene.x == self.player.posx + 1
                    or ene.x == self.player.posx
                    or ene.x + 1 == self.player.posx) and (
                        ene.y == self.player.posycap
                        or ene.y == self.player.posyhead
                        or ene.y == self.player.posybody1
                        or ene.y == self.player.posybody1
                        or ene.y == self.player.posylegs):
                if self.player._lifes > 0 and self.player.sheild == False:
                    self.player.update_lifes()
                    self.__counter = 0
                    self.time = 400
                elif self.player._lifes == 0:
                    self.player.lost_to_boss(self.score)
        '''Player collision with the coin'''
        for co in self.__coins:
            if (self.player.posx <= co.x and co.x <= self.player.posx + 3
                ) and (co.y <= self.player.posylegs
                       and co.y >= self.player.posycap):
                self.__coins.remove(co)
                self.score = self.score + 10
        '''Player collision with the vetical beams'''
        for bea in self.__vertical:
            if (bea.x >= self.player.posx
                    and bea.x <= self.player.posx + 3) and (
                        (bea.y >= self.player.posylegs
                         and bea.y - 4 <= self.player.posylegs) or
                        (bea.y >= self.player.posycap
                         and bea.y - 4 <= self.player.posycap)):
                if self.player._lifes > 0 and self.player.sheild == False:
                    self.player.update_lifes()
                    self.__counter = 0
                    self.time = 400
                elif self.player._lifes == 0:
                    self.player.lost_to_boss(self.score)
        '''Player collision with the horizontal beam'''
        for bea in self._horizontal:
            if (bea.x <= self.player.posx and bea.x + 8 >= self.player.posx
                ) and (bea.y >= self.player.posycap
                       and bea.y <= self.player.posylegs):
                if self.player._lifes > 0 and self.player.sheild == False:
                    self.player.update_lifes()
                    self.__counter = 0
                    self.time = 400
                elif self.player._lifes == 0:
                    self.player.lost_to_boss(self.score)
        '''Player collision with the typical beam'''
        for bea in self._typical:
            if (bea.x <= self.player.posx + 2 and bea.x >= self.player.posx
                    and bea.y >= self.player.posycap
                    and bea.y <= self.player.posylegs) or (
                        (bea.x + 1) <= self.player.posx + 2 and
                        (bea.x + 1) >= self.player.posx and
                        (bea.y - 1) >= self.player.posycap and
                        (bea.y - 1) <= self.player.posylegs) or (
                            (bea.x + 2) <= self.player.posx + 2 and
                            (bea.x + 2) >= self.player.posx and
                            (bea.y - 2) >= self.player.posycap and
                            (bea.y - 2) <= self.player.posylegs) or (
                                (bea.x + 3) <= self.player.posx + 2 and
                                (bea.x + 3) >= self.player.posx and
                                (bea.y - 3) >= self.player.posycap and
                                (bea.y - 3) <= self.player.posylegs) or (
                                    (bea.x + 4) <= self.player.posx + 2 and
                                    (bea.x + 4) >= self.player.posx and
                                    (bea.y - 4) >= self.player.posycap and
                                    (bea.y - 4) <= self.player.posylegs):
                if self.player._lifes > 0 and self.player.sheild == False:
                    self.player.update_lifes()
                    self.__counter = 0
                    self.time = 400
                elif self.player._lifes == 0:
                    self.player.lost_to_boss(self.score)
        '''Bullets colliding with the vertical beams'''
        for bea in self.__vertical:
            for bul in self.player.Bull:
                if bul.y <= bea.y and bul.y >= bea.y - 4 and bul.x >= bea.x:
                    self.__vertical.remove(bea)
                    self.player.Bull.remove(bul)
                    self.score += 5
        '''Bullets colliding with the horizontal beams'''
        for bea in self._horizontal:
            for bul in self.player.Bull:
                if bul.y == bea.y and bul.x >= bea.x and bul.x <= bea.x + 8:
                    self._horizontal.remove(bea)
                    self.player.Bull.remove(bul)
                    self.score += 5
        '''Bullet collision with typical beams'''
        for bea in self._typical:
            for bul in self.player.Bull:
                if ((bul.x == bea.x or bul.x + 1 == bea.x or bul.x + 2 == bea.x
                     or bul.x - 1 == bea.x) and (bul.y == bea.y)) or (
                         (bul.x == bea.x + 1 or bul.x + 1 == bea.x + 1
                          or bul.x + 2 == bea.x + 1 or bul.x - 1 == bea.x + 1)
                         and (bul.y == bea.y + 1)) or (
                             (bul.x == bea.x + 2 or bul.x + 1 == bea.x + 2 or
                              bul.x + 2 == bea.x + 2 or bul.x - 1 == bea.x + 2)
                             and (bul.y == bea.y + 2)) or (
                                 (bul.x == bea.x + 3 or bul.x + 1 == bea.x + 3
                                  or bul.x + 2 == bea.x + 3
                                  or bul.x - 1 == bea.x + 3) and
                                 (bul.y == bea.y + 3)) or (
                                     (bul.x == bea.x + 4 or bul.x + 1
                                      == bea.x + 4 or bul.x + 2 == bea.x + 4
                                      or bul.x - 1 == bea.x + 4) and
                                     (bul.y == bea.y + 4)):
                    self._typical.remove(bea)
                    self.player.Bull.remove(bul)
                    self.score += 5
        '''Collision with boss enemy bullet'''
        for dragbul in self.DragonBull:
            if dragbul.bullposx <= self.player.posx + 2 and dragbul.bullposx + 11 >= self.player.posx and (
                (self.player.posycap <= dragbul.bullposy
                 and self.player.posylegs >= dragbul.bullposy) or
                (self.player.posycap >= dragbul.bullposy
                 and self.player.posylegs >= dragbul.bullposy
                 and dragbul.bullposy + 5 >= self.player.posycap) or
                (self.player.posycap >= dragbul.bullposy
                 and self.player.posylegs <= dragbul.bullposy + 5)):
                if self.player._lifes > 0 and self.player.sheild == False:
                    self.player._lifes = 0
                    self.player.lost_to_boss(self.score)
        '''Dragon bullet removing'''
        for dragbul in self.DragonBull:
            if dragbul.bullposx <= 1299:
                self.DragonBull.remove(dragbul)
        '''Dragon killing'''
        for bull in self.player.Bull:
            if bull.x >= self.boo.x and bull.x <= self.boo.x + 38 and bull.y >= self.boo.y and bull.y <= self.boo.y + 14:
                self.__bosslifes -= 1
                self.player.Bull.remove(bull)
                self.score += 5

        if self.__bosslifes == 0:
            self.player.terminateboss(self.score)

    def update_lifes(self):
        self.__counter = 0
        self.player.posx = self.player.start
        self.player._lifes -= 1

    def prior(self):
        for x in range(8, 21):
            for y in range(7, 37):
                self.__scene[x][y] = self.__blue + Dragon[x -
                                                          8][y -
                                                             7] + self.__reset
        self.__scene[11][29] = self.__red + 'M' + self.__reset
        self.__scene[11][30] = self.__red + 'A' + self.__reset
        self.__scene[11][31] = self.__red + 'N' + self.__reset
        self.__scene[11][32] = self.__red + 'D' + self.__reset
        self.__scene[11][33] = self.__red + 'O' + self.__reset
        for i in range(9, 15):
            for j in range(100, 115):
                self.__scene[i][j] = magnet[i - 9][j - 100]
        for i in range(9, 15):
            for j in range(500, 515):
                self.__scene[i][j] = magnet[i - 9][j - 500]
        for i in range(9, 15):
            for j in range(1000, 1015):
                self.__scene[i][j] = magnet[i - 9][j - 1000]

        self.__vertical = createVbars()
        self._horizontal = createHbars()
        self._typical = createTbars()
        self.__clouds = createClouds()
        self.__coins = createCoins()
        for clo in self.__clouds:
            self.__scene = clo.create(self.__scene)
        self.__Enemies = creation_of_enemies()
        self.boo = Boss(1440, 20)
        self.boos.append(self.boo)

    def background(self):
        print(self.__green)
        print("lifes Remaining", self.player._lifes, "   ", end=" ")
        print(self.__reset)
        if self.shh:
            self.player.sheild = True
        tmp_grid = self.player.create(self.__scene, self.__counter)
        for co in self.__coins:
            tmp_grid = co.create(tmp_grid)
        for bars in self.__vertical:
            tmp_grid = bars.create(tmp_grid)
        for bars in self._horizontal:
            tmp_grid = bars.create(tmp_grid)
        for bars in self._typical:
            tmp_grid = bars.create(tmp_grid)
        if self.bullets:
            tmp_grid = self.player.updateBullet(tmp_grid)
        for ene in self.__Enemies:
            ene.update_Enemies()
        for ene in self.__Enemies:
            tmp_grid = ene.PlaceEnemyvertical(tmp_grid)
        if self.__counter > 1299:
            for boo in self.boos:
                tmp_grid = self.boo.create(tmp_grid)
            self.boo.updatePosition(self.player.posybody1)
            if self.bullcounter % 20 == 0:
                drabu = DragonBullets(self.boo.x - 8, self.boo.y + 3)
                self.DragonBull.append(drabu)
            for drabuu in self.DragonBull:
                tmp_grid = drabuu.create(tmp_grid)
            self.bullcounter += 1
            if self.bullcounter == 100:
                self.bullcounter = 0
            for drabul in self.DragonBull:
                drabul.updateBullets()
        printScenary(tmp_grid, self.__green, self.__reset, self.__counter)
        if self.speedBoost and self.__counter <= 1296:
            self.__counter += 3
            self.speedBoost = False
        if self.__counter <= 1299:
            self.__counter += 1

    def check(self):
        if self.Right:
            self.player.moveright(self.__counter)
            self.Right = False
        if self.Up:
            self.player.moveup()
            self.Up = False
            self.__gravity = True
        if self.__gravity:
            self.__gravity = self.player.Gravity()
        if self.fired:
            self.player.createbullts()
            self.fired = False
        if self.left:
            self.player.moveleft(self.__counter)
            self.left = False
コード例 #13
0
ファイル: gui.py プロジェクト: yuvrajwaraich/GameJam2021
def bossLevel():
    global currLevel
    currLevel += 1

    up, down, right, left = False, False, False, False

    if randint(0, 1):
        bossX = SCREEN_WIDTH // 4 - 32
    else:
        bossX = SCREEN_WIDTH - SCREEN_WIDTH // 4 - 32
    bossY = SCREEN_HEIGHT // 2 - 32
    boss = Boss(bossX, bossY)

    level_disp = pygame.Rect(900, 0, 100, 42)
    myfont = pygame.font.SysFont('Comic Sans MS', 20)

    running = True
    currentTime = pygame.time.get_ticks()
    moveTime = pygame.time.get_ticks()
    while running:
        screen.blit(background, (0, 0))
        screen.blit(main_char.image, (main_char.x, main_char.y))
        main_char.displayHealth(screen)

        text = myfont.render("Level: " + str(currLevel), True, WHITE)
        fontSize = myfont.size("Level: " + str(currLevel))
        disp_coords = (level_disp.center[0] - fontSize[0] // 2,
                       level_disp.center[1] - fontSize[1] // 2 + 20)
        screen.blit(text, disp_coords)

        global highestScore
        highestScore = max(highestScore, currLevel)
        highScore = myfont.render("Highest Level: " + str(highestScore), True,
                                  WHITE)
        hs_fontSize = myfont.size("Highest Level: " + str(highestScore))
        hs_disp_coords = (level_disp.center[0] - hs_fontSize[0] // 2 - 42,
                          level_disp.center[1] - hs_fontSize[1] // 2 - 5)
        screen.blit(highScore, hs_disp_coords)

        screen.blit(boss.image, (boss.x, boss.y))
        boss.displayHealth(screen)

        toDel = set()

        if pygame.time.get_ticks() - currentTime > 500:
            for bullet in boss.shoot(main_char.x + 32, main_char.y + 32):
                bullets.add(bullet)
            currentTime = pygame.time.get_ticks()

        if pygame.time.get_ticks() - moveTime > 3000:
            boss.move(main_char.x, main_char.y)
            moveTime = pygame.time.get_ticks()

        boss.changeDir(main_char.x, main_char.y)

        for bullet in bullets:
            if (bullet.x < 0 or bullet.x > SCREEN_WIDTH or bullet.y < 0
                    or bullet.y > SCREEN_HEIGHT):
                toDel.add(bullet)
            elif (bullet.character.charType == 'boss'
                  and bullet.collide(main_char)):
                if main_char.alive:
                    main_char.lowerHealth(boss.bulletDamage)
                toDel.add(bullet)
            else:
                bullet.draw()

            if (bullet.character.charType == 'hero' and bullet.collide(boss)):
                toDel.add(bullet)
                boss.lowerHealth(main_char.bulletDmg)

        for bullet in toDel:
            bullets.remove(bullet)

        if right:
            main_char.move(movementSpeed, 0)
        if left:
            main_char.move(-1 * movementSpeed, 0)
        if up:
            main_char.move(0, -1 * movementSpeed)
        if down:
            main_char.move(0, movementSpeed)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()

            if event.type == pygame.KEYDOWN:
                if event.key in [pygame.K_ESCAPE, pygame.K_p]:
                    up, down, right, left = False, False, False, False
                    if not options():
                        return "no more play"
                if event.key in [pygame.K_RIGHT, pygame.K_d]:
                    right = True
                if event.key in [pygame.K_LEFT, pygame.K_a]:
                    left = True
                if event.key in [pygame.K_UP, pygame.K_w]:
                    up = True
                if event.key in [pygame.K_DOWN, pygame.K_s]:
                    down = True

            if event.type == pygame.KEYUP:
                if event.key in [pygame.K_RIGHT, pygame.K_d]:
                    right = False
                if event.key in [pygame.K_LEFT, pygame.K_a]:
                    left = False
                if event.key in [pygame.K_UP, pygame.K_w]:
                    up = False
                if event.key in [pygame.K_DOWN, pygame.K_s]:
                    down = False

            if event.type == pygame.MOUSEBUTTONUP:
                mouseX, mouseY = pygame.mouse.get_pos()
                bullets.add(main_char.shoot(mouseX, mouseY))

        clock.tick(60)
        pygame.display.update()

        if not boss.alive:
            return 'continue'

        if not main_char.alive:
            return 'dead'
コード例 #14
0
pygame.init()

# настройка экрана и группы всех спрайтов
size = width, height = 700, 700
screen = pygame.display.set_mode(size)
all_sprites = pygame.sprite.Group()
bg = Background('background.jpg', [0, 0])

# спрайт игрока
wizard = Player(load_image("sorlowalk.png", (128, 128, 128, 255)),
                load_image("sorlowalkback.png", (128, 128, 128, 255)),
                load_image("sorlostand.png", (128, 128, 128, 255)),
                load_image("sorlofire.png", (128, 128, 128, 255)), 4, 1, 0,
                300, all_sprites)
# спрайт противника
enemi = Boss(load_image("enemi.png", -1), 400, 250, all_sprites)

# заставка
start_screen(screen)

# музыка
pygame.mixer.init()
pygame.mixer.music.load(os.path.join('data', 'danzhi.wav'))
pygame.mixer.music.set_volume(0.5)
pygame.mixer.music.play(-1)
wiz_fire = pygame.mixer.Sound(os.path.join('data', 'wiz_fire.wav'))
enemi_fire = pygame.mixer.Sound(os.path.join('data', 'enemi_fire.wav'))

# определение счетчиков, групп спрайтов и вспомогательных переменных
running = True
clock = pygame.time.Clock()
コード例 #15
0
    def drawRoom(self, room):
        room_x = int(room.x * ROOM_WIDTH)
        room_y = int(room.y * ROOM_HEIGHT)

        for x in range(0, 3):
            for y in range(0, 3):
                template = ROOM_TEMPLATES[2]

                neighbor_rooms = {}
                for direction in DIRS:
                    neighbor = self.rooms.get((room.x + direction[0], room.y + direction[1]))
                    if neighbor is not None:
                        neighbor_rooms[direction] = neighbor
                        
                left = neighbor_rooms.get((-1, 0)) is not None
                bottom = neighbor_rooms.get((0, -1)) is not None
                top = neighbor_rooms.get((0, 1)) is not None
                right = neighbor_rooms.get((1, 0)) is not None

                if y == 0:
                    if x == 1:
                        if bottom:
                            template = getRandTemplate(BOTTOM_OPEN)
                        else:
                            template = getRandTemplate(BOTTOM)
                    elif x == 0:
                        template = getRandTemplate(BOTTOM_LEFT)
                    elif x == 2:
                        template = getRandTemplate(BOTTOM_RIGHT)
                elif y == 1:
                    if x == 0:
                        if left:
                            template = EMPTY
                        else:
                            template = MIDDLE_LEFT[0]
                    elif x == 1:
                        template = MIDDLE_CENTER[0]
                    elif x == 2:
                        if right:
                            template = EMPTY
                        else:
                            template = MIDDLE_RIGHT[0]
                elif y == 2:
                    if x == 1:
                        if top:
                            template = getRandTemplate(TOP_OPEN)
                        else:
                            template = TOP[0]
                    elif x == 0:
                        template = TOP_LEFT[0]
                    elif x == 2:
                        template = TOP_RIGHT[0]

                drawTemplate(
                    self.level,
                    room_x + x * TEMPLATE_WIDTH,
                    room_y + y * TEMPLATE_HEIGHT,
                    template)

        difficulty = self.level.difficulty
        
        while difficulty > 0:
            if room.type == START_ROOM:
                break
            if room.type == BOSS_ROOM:
                entity_x = (room_x + ROOM_WIDTH / 2) * TILE_SIZE
                entity_y = (room_y + ROOM_HEIGHT / 2) * TILE_SIZE
                boss = Boss(entity_x, entity_y, self.level.difficulty)
                self.level.add_entity_to_list(boss, self.level.entities)
                difficulty -= 5
            else:
                enemy_type = random.randint(0, 2)
                
                entity_x = random.randrange(room_x + 1, room_x + ROOM_WIDTH - 1)
                entity_y = random.randrange(room_y + 1, room_y + ROOM_HEIGHT - 1)
                tries = 0
                while self.level.get_tile(entity_x, entity_y) or tries < 5:
                    entity_x = random.randrange(room_x + 1, room_x + ROOM_WIDTH - 1)
                    entity_y = random.randrange(room_y + 1, room_y + ROOM_HEIGHT - 1)
                    tries += 1
                entity_x *= TILE_SIZE
                entity_y *= TILE_SIZE
                if enemy_type == 0:
                    slem = Slime(Textures.get_texture(3, 2), entity_x, entity_y, self.level.difficulty)
                    self.level.add_entity_to_list(slem, self.level.entities)
                    difficulty -= 1
                elif enemy_type == 1:
                    enemy = Enemy(Textures.get_texture(0, 2), entity_x, entity_y, self.level.difficulty)
                    self.level.add_entity_to_list(enemy, self.level.entities)
                    difficulty -= 1
                else:
                    spiky_ball = SpikyBall(entity_x, entity_y, self.level.difficulty)
                    self.level.add_entity_to_list(spiky_ball, self.level.entities)
                    difficulty -= 1
コード例 #16
0
ファイル: Scheduler.py プロジェクト: ericvaandering/CRAB2
class Scheduler :

    _instance = None

    def getInstance():
        if not Scheduler._instance :
            raise CrabException('Scheduler has no instance.')
        return Scheduler._instance

    getInstance = staticmethod(getInstance)

    def __init__(self, name):
        Scheduler._instance = self
        self._name = string.lower(name)
        self._boss = Boss()
        self.protocolDict = { 'CAF'      : 'rfio' , \
                              'LSF'      : 'rfio' , \
                              'PBS'      : 'rfio' , \
                              'CONDOR_G' : 'srm-lcg' , \
                              'GLITE'    : 'srm-lcg' , \
                              'GLIDEIN'  : 'srm-lcg' , \
                              'CONDOR'   : 'srm-lcg',  \
                              'REMOTEGLIDEIN'  : 'srm-lcg',  \
                              'SGE'      : 'srm-lcg', \
                              'ARC'      : 'srm-lcg'
                            }

        self.protocolOpt = { 'rfio' : '', \
                             'xrootd' : '', \
                             'srmv2' : '' ,  \
                             'srm-lcg' : '-b -D srmv2'
                            }

        return

    def name(self):
        return self._name

    def realSchedParams(self,cfg_params):
        """
        """
        return {}

    def configure(self, cfg_params):
        self._boss.configure(cfg_params)
        self.CRAB_useServer = cfg_params.get('CRAB.use_server',0)
        self.CRAB_serverName = cfg_params.get('CRAB.server_name',None)
        seWhiteList = cfg_params.get('GRID.se_white_list',[])
        seBlackList = cfg_params.get('GRID.se_black_list',[])
        self.dontCheckMyProxy=int(cfg_params.get("GRID.dont_check_myproxy",0))
        self.EDG_requirements = cfg_params.get('GRID.requirements',None)
        self.EDG_addJdlParam = cfg_params.get('GRID.additional_jdl_parameters',None)
        if (self.EDG_addJdlParam):
            self.EDG_addJdlParam = string.split(self.EDG_addJdlParam,';')

        self.pset = cfg_params.get('CMSSW.pset',None)
        self.blackWhiteListParser = SEBlackWhiteListParser(seWhiteList, seBlackList, common.logger())

        self.return_data = int(cfg_params.get('USER.return_data',0))
        self.copy_data = int(cfg_params.get('USER.copy_data',0))
        self.publish_data = cfg_params.get("USER.publish_data",0)
        self.local_stage = int(cfg_params.get('USER.local_stage_out',0))
        self.check_RemoteDir =  int(cfg_params.get('USER.check_user_remote_dir',1))

        if int(self.copy_data) == 1:
            self.SE = cfg_params.get('USER.storage_element',None)
            if not self.SE:
                msg = "Error. The [USER] section does not have 'storage_element'"
                common.logger.info(msg)
                raise CrabException(msg)

        if ( int(self.return_data) == 0 and int(self.copy_data) == 0 ):
            msg = 'Error: return_data = 0 and copy_data = 0 ==> your exe output will be lost\n'
            msg = msg + 'Please modify return_data and copy_data value in your crab.cfg file\n'
            raise CrabException(msg)

        if ( int(self.return_data) == 1 and int(self.copy_data) == 1 ):
            msg = 'Error: return_data and copy_data cannot be set both to 1\n'
            msg = msg + 'Please modify return_data or copy_data value in your crab.cfg file\n'
            raise CrabException(msg)

        if ( int(self.copy_data) == 0 and int(self.local_stage) == 1 ):
            msg = 'Error: copy_data = 0 and local_stage_out = 1.\n'
            msg += 'To enable local stage out the copy_data value has to be = 1\n'
            msg = msg + 'Please modify copy_data value in your crab.cfg file\n'
            raise CrabException(msg)

        if ( int(self.copy_data) == 0 and int(self.publish_data) == 1 ):
            msg = 'Error: publish_data = 1 must be used with copy_data = 1\n'
            msg = msg + 'Please modify copy_data value in your crab.cfg file\n'
            common.logger.info(msg)
            raise CrabException(msg)

        if ( int(self.publish_data) == 1 and self._name == 'lsf'):
            msg = 'Error: data publication is not allowed with lsf scheduler, but only with grid scheduler or caf\n'
            common.logger.info(msg)
            raise CrabException(msg)

        self.debug_wrapper = int(cfg_params.get('USER.debug_wrapper',0))
        self.debugWrap=''
        if self.debug_wrapper==1: self.debugWrap='--debug'
        self.loc_stage_out = ''
        if ( int(self.local_stage) == 1 ):
            self.debugWrap='--debug'
            self.loc_stage_out='--local_stage'

        # Time padding for minimal job duration.
        self.minimal_job_duration = 10

        return

    def boss(self):
        return self._boss

    def rb_configure(self, RB):
        """
        Return a requirement to be add to Jdl to select a specific RB/WMS:
        return None if RB=None
        To be re-implemented in concrete scheduler
        """
        return None

    def ce_list(self):
        return '',None,None

    def se_list(self, id, dest):
        return '',None,None

    def sched_fix_parameter(self):
        return

    def sched_parameter(self,i,task):
        """
        Returns parameter scheduler-specific, to use with BOSS .
        """
        return ''

    def wsSetupEnvironment(self):
        """
        Returns part of a job script which does scheduler-specific work.
        """
        return ''

    def  wsExitFunc(self):
        """
        Returns part of a job script which does scheduler-specific
        output checks and management.
        """
        return ''

    def checkRemoteDir(self, endpoint, fileList):
        """
        """
    
        common.logger.info('Checking remote location')
        ## temporary hack for OctX:
        if endpoint.find('${PSETHASH}')>1:
            try:
                jdir=common.work_space.jobDir()
                ### FEDE bug fix 93573
                psethash= string.strip(runCommand('cd %s; edmConfigHash CMSSW.py|tail -1'%jdir))
                endpoint= string.replace(endpoint,'${PSETHASH}',psethash)
                #####################
            except:
                msg =  'Problems with PSETHASH during remote dir check... \n'
                msg += '\tPlease check stage out configuration parameters.\n'
                raise CrabException(msg)
        try:
            remoteListTmp = self.listRemoteDir(endpoint)
        except Exception, ex:
            msg =  'Problems trying remote dir check: \n\t%s'%str(ex)
            raise CrabException(msg)
        if remoteListTmp is False:
            return
        if remoteListTmp == []:
            return
        if remoteListTmp:
            listJob = common._db.nJobs('list')
            remoteList = []
            for f_path in remoteListTmp:
                remoteList.append(str(os.path.basename(f_path)))
            metaList = []
            for id in listJob:
                for file in fileList :
                    metaList.append('%s'%numberFile(file,id))
            for remote in remoteList:
                for meta in metaList:
                    metaPrePost = meta.split('.')
                    if remote.startswith(metaPrePost[0]) and remote.endswith(metaPrePost[1]):
                        msg  = 'Error: You are asking to stage out on a remote directory \n'
                        msg += '\twhich already contains files with same name.\n'
                        msg += '\tThe endpoint is ' + endpoint + '\n'
                        msg += '\tPlease change directory or remove the actual content following this HowTo:\n'
                        msg += '\thttps://twiki.cern.ch/twiki/bin/view/CMS/CheckUserRemoteDir\n'
                    	msg += '\n\tIt will be not possible to submit these jobs!\n'
                        raise CrabException(msg)
        else:
            msg = 'Remote directory is empty or not existis\n'
            common.logger.debug(msg)
        
        return
コード例 #17
0
ファイル: World.py プロジェクト: SeraphRoy/Bomberman
        #boss_sound.play(-1)
        flag = True
        isArcher = True

    if not flag and isArcher and not isMage:
        m = Mage(random.randint(50, 680), random.randint(50, 680), 50, 150,
                 mage_images, 200, 200)
        enemys.add(m)
        all_enemies.add(m)
        #background_music.fadeout(1500)
        #boss_sound.play(-1)
        flag = True
        isMage = True

    if not flag and isArcher and isMage and not isBoss:
        b = Boss(random.randint(50, 680), random.randint(50, 680), 50, 150,
                 panda_images, 200, 200)
        enemys.add(b)
        all_enemies.add(b)
        background_music.fadeout(1500)
        boss_sound.play(-1)
        flag = True
        isBoss = True

    if not flag and isBoss:
        stage_num += 3
        pickle.dump(stage_num, open("./save/save_stage", "wb"))
        data = p.GetValuableData()
        pickle.dump(data, open("./save/save_player", "wb"))
        GameReinitialization(stage_num)
        boss_sound.fadeout(1500)
        background_music.play(-1)
コード例 #18
0
class Game:
    def __init__(self, map_root):
        self.level = 1
        self.map = Map(map_root, self)
        self.hero = Hero(1)
        # placing the hero at the top-left corner
        self.hero.place()

        self.monsters = []
        self.boss = None
        # this property will hold a reference to the monster that is in the same place as the hero
        self.monster_in_tile = None
        self.create_monsters()

        map_root.bind('<Left>', self.left_key)
        map_root.bind('<Right>', self.right_key)
        map_root.bind('<Up>', self.up_key)
        map_root.bind('<Down>', self.down_key)
        map_root.bind('<space>', self.battle)

        # this holds a character object. comes handy when determining the attacker
        self.last_moved = None
        # keep track of the hero's moves, so we move the monsters after every 2 moves of the hero
        self.hero_moves_counter = 0

    def create_monsters(self):
        monster_count = 3 + roll_dice(3) - 1
        # determining monster levels(by predefined chances), creating monsters
        for _ in range(monster_count):
            self.monsters.append(Monster(generate_monster_level(self.level)))
        # and for the boss
        self.boss = Boss(generate_monster_level(self.level))
        # let's add the boss to the monsters list, just for simplicity
        self.monsters.append(self.boss)

        # finding random floors for placing the monsters
        placed_floors = []
        # this process includes the boss too, hence monster_count+1
        while len(placed_floors) < monster_count + 1:
            # 63 is the number of empty floors on the map
            rolled_dice = roll_dice(63)
            if rolled_dice == 1:
                continue
            if rolled_dice not in placed_floors:
                # placing the monster at floor
                x, y = self.map.get_nth_floor(rolled_dice)
                self.monsters[len(placed_floors) - 1].place(x, y)
                placed_floors.append(rolled_dice)

        # giving the key to the next area, to one of the 3 monsters
        key_holder = roll_dice(monster_count) - 1
        self.monsters[key_holder].give_the_key()

    # Binding keyboard key events to functions
    def left_key(self, event):
        if self.map.pos_is_free(self.hero.x - 1, self.hero.y):
            self.hero.move(x=-1)
            self.last_moved = self.hero
            self.hero_moves_counter += 1
            self.do_game_logic()
        self.hero.img = "hero_left"

    def right_key(self, event):
        if self.map.pos_is_free(self.hero.x + 1, self.hero.y):
            self.hero.move(x=1)
            self.last_moved = self.hero
            self.hero_moves_counter += 1
            self.do_game_logic()
        self.hero.img = "hero_right"

    def up_key(self, event):
        if self.map.pos_is_free(self.hero.x, self.hero.y - 1):
            self.hero.move(y=-1)
            self.last_moved = self.hero
            self.hero_moves_counter += 1
            self.do_game_logic()
        self.hero.img = "hero_up"

    def down_key(self, event):
        if self.map.pos_is_free(self.hero.x, self.hero.y + 1):
            self.hero.move(y=1)
            self.last_moved = self.hero
            self.hero_moves_counter += 1
            self.do_game_logic()
        self.hero.img = "hero_down"

    def check_hero_tile(self):
        any_monster = [monster for monster in self.monsters if monster.get_tile() == self.hero.get_tile()]
        if len(any_monster) == 1:
            self.monster_in_tile = any_monster[0]
        else:
            self.monster_in_tile = None

    def strike(self, attacker: Character, defender: Character):
        sv = attacker.stats.strike_point + (roll_dice() * 2)
        if sv > defender.stats.defend_point:
            defender.lose_health(sv - defender.stats.defend_point)

    def someone_died(self, character):
        if character is self.hero:
            # game over
            messagebox.showinfo("Game Over", "You lost.")
            self.map.master.destroy()
        else:
            self.monsters.remove(character)
            # level up hero
            self.hero.level_up()
            self.check_monsters_status()
        self.check_hero_tile()

    # performs a battle until one dies, then notifies the result to game.someone_died(character)
    def battle(self, event=None):
        if self.monster_in_tile is not None:
            # determining the attacker and the defender; who did the last move? (entered the tile)
            attacker = self.hero if self.last_moved is self.hero else self.monster_in_tile
            defender = self.monster_in_tile if attacker is self.hero else self.hero
            original_attacker = attacker

            who_died = None
            while attacker.is_alive() and defender.is_alive():
                self.strike(attacker, defender)
                if not (attacker.is_alive() and defender.is_alive()):
                    who_died = attacker if not attacker.is_alive() else defender
                    break
                else:
                    # switching the attacker and the defender, the defender strikes next
                    switching_temp = attacker
                    attacker = defender
                    defender = switching_temp
            self.someone_died(who_died)
            self.map.notify_battle(original_attacker, who_died)

    # this method is called after every character moves
    def do_game_logic(self):
        # checking if the hero is on a monster's tile
        self.check_hero_tile()

        # if a monster entered the hero's tile, a battle should be triggered
        if self.monster_in_tile is not None and self.last_moved is not self.hero:
            self.battle()

        # moving monsters after every 2 moves of the hero
        if self.last_moved is self.hero and self.hero_moves_counter == 2:
            self.hero_moves_counter = 0
            self.move_monsters()

    def check_monsters_status(self):
        monsters = self.monsters.copy()
        if self.boss.is_alive():
            # boss never carries the key
            monsters.remove(self.boss)

        hero_has_key = sum(monster.has_the_key for monster in monsters) == 0
        if hero_has_key and not self.boss.is_alive():
            self.enter_next_area()

    def move_monsters(self):
        for monster in self.monsters:
            current_tile = monster.get_tile()
            while True:
                random_direction = roll_dice(4)
                if random_direction == 1 and self.map.pos_is_free(current_tile[0], current_tile[1]-1):
                    monster.move(y=-1)
                    break
                elif random_direction == 2 and self.map.pos_is_free(current_tile[0]+1, current_tile[1]):
                    monster.move(x=+1)
                    break
                elif random_direction == 3 and self.map.pos_is_free(current_tile[0], current_tile[1]+1):
                    monster.move(y=+1)
                    break
                elif random_direction == 4 and self.map.pos_is_free(current_tile[0]-1, current_tile[1]):
                    monster.move(x=-1)
                    break
        self.last_moved = self.monsters
        self.do_game_logic()

    def enter_next_area(self):
        # hero restores some health upon entering next area
        hp_restore_dice = roll_dice(10)
        if hp_restore_dice == 1:
            # restore all hp
            self.hero.gain_health(self.hero.stats.max_health_point)
        elif 2 <= hp_restore_dice <= 5:
            # restore third of hp
            self.hero.gain_health(int(self.hero.stats.max_health_point / 3))
        else:
            # restore 10 percent of hp
            self.hero.gain_health(int(self.hero.stats.max_health_point / 10))

        self.monsters.clear()
        self.level += 1
        self.last_moved = None
        self.hero_moves_counter = 0
        self.monster_in_tile = None

        # creating new monsters
        self.create_monsters()
        self.hero.place(0, 0)

    def start(self):
        # this is the game loop
        # constantly running
        while True:
            self.map.update_screen()
コード例 #19
0
IMG_SIZE = 52
WIDTH = 10 * IMG_SIZE
HEIGHT = (10 * IMG_SIZE) + IMG_SIZE

root = Tk()
root.title('Wanderer Game')
canvas = Canvas(root, width=WIDTH, height=HEIGHT)
canvas.pack()

hero = Hero()
game_map = Map()
skeleton1 = Skeleton(6, 1, True)
skeleton2 = Skeleton(2, 6)
skeleton3 = Skeleton(8, 1)
boss = Boss(9, 1)
enemies = [skeleton1, skeleton2, skeleton3, boss]


def draw_screen():
    canvas.delete("all")
    for i in range(len(game_map.tiles)):
        for j in range(len(game_map.tiles[i])):
            if game_map.tiles[i][j] == 0:
                image = root.floor
            else:
                image = root.wall
            canvas.create_image(j * IMG_SIZE,
                                i * IMG_SIZE,
                                anchor=NW,
                                image=image)
コード例 #20
0
ファイル: myTextRpg.py プロジェクト: Zacros7164/unit1
                        if not theHero.is_alive():  # hero death message
                            print asciiArt.death
                            print dialogue.heroDied % monster.name
                            break

                    if not monster.is_alive():  # Monster death message
                        print dialogue.monsterDied % monster.name
                        print dialogue.power_up
                        theHero.defeated_enemy(monster.power)
                        monster.drop_gold()
                        numMonsters += 1
                        break
                    raw_input("Hit enter to continue ")
                    os.system("clear")
        else:
            monster = Boss()  #generate a boss
            print dialogue.encounterBoss
            while theHero.health > 0 and monster.health > 0:
                print dialogue.battleStats % (theHero.health, theHero.power,
                                              monster.name, monster.health,
                                              monster.power)
                theHero.battle_choice()
                player_choice = raw_input("> ")

                if player_choice == "1":  #fight
                    monster.take_damage(theHero.power)
                    print dialogue.battleStats % (
                        theHero.health, theHero.power, monster.name,
                        monster.health, monster.power)

                elif player_choice == "2":  #dance
コード例 #21
0
            enemies_on_map += 1

        if not demios_count <= 0:
            enemies.append(
                Demios(1000, random.randint(100, 500), 30, 50, 2, 8, 5))
            demios_count -= 1
            enemies_on_map += 1

        if lvl == 5 and clorfos_count != 0:
            enemies.append(
                Clorfos(600, (25 + clorfos_count * 150), 30, 120, 2, 50, 0.5))
            clorfos_count -= 1
            enemies_on_map += 1

        if lvl == 5 and boss_count == 1:
            boss = Boss(700, 250, 30, 200, 2, 100, 2)

            if menu.lvl_difficulty == 1:
                boss.image = boss.boss_easy_image
            elif menu.lvl_difficulty == 2:
                boss.image = boss.boss_normal_image
            else:
                boss.image = boss.boss_normal_image

            enemies.append(boss)
            enemies_on_map += 1
            boss_count = 0

        spawn_rate += 1
    # Spawn speed limit