コード例 #1
0
    def __init__(self, master: tk.Tk):
        self._master = master
        self._master.geometry(const.APP_GEOMETRY)
        self.mview = Bomb.BombView(self._master)
        self.model = Bomb.BombModel(const.DEFAULT_TIME_LIMIT, self.on_window_close)
        self.model.attach_modules(ModuleManager.get_module_list(self.model, self.mview))
        self.mview.attach_module_list(self.model.modules)
        self.eview = Bomb.EdgeworkView(self._master, self.model)
        self.model.attach_edgework_view(self.eview)

        self.mview.pack(side=tk.LEFT, expand=True, fill=tk.BOTH, padx=20)
        self.eview.pack(side=tk.LEFT, fill=tk.BOTH, padx=10)

        self.model.start_game()
コード例 #2
0
 def dropBomb(self, level):
     '''Creates an instance of the bomb class at the PC's position
     -level, contains matrix to identify location of stationary objects
     '''
     xDiff = abs(self.xres -
                 (const.SCREEN_OFFSET_X_LEFT + self.x * const.TILE_SIZE))
     yDiff = abs(self.yres -
                 (const.SCREEN_OFFSET_Y_TOP + self.y * const.TILE_SIZE))
     if self.kind == const.BOSS:
         isBoss = True
         offsetX = 1
         offsetY = 2
     else:
         isBoss = False
         offsetX = 0
         offsetY = 0
     if xDiff < 10 and yDiff < 10 and self.activeBombs < self.bombCount and level.layout[
             self.y][self.x] == None:
         newBomb = Bomb.Bomb(self.x + offsetX, self.y + offsetY,
                             self.bombRange, isBoss)
         self.changeActiveBombCount(1)
         if isBoss:
             self.readyDropBomb = False
             self.startTicksBomb = pygame.time.get_ticks()
         return newBomb
     else:
         return None
コード例 #3
0
    def broadcastReceive(self,data):
        if (data['code']==200):
            if (self.player.file_player=="player1"):
                enemy_x=data['player2X']
                enemy_y = data['player2Y']
                self.player2.x=enemy_x
                self.player2.y=enemy_y
                self.player2.file_player="player2"

            if (self.player.file_player=="player2"):
                enemy_x=data['player1X']
                enemy_y = data['player1Y']
                self.player2.x=enemy_x
                self.player2.y=enemy_y
                self.player2.file_player = "player1"
        if (data['code']==201):
            print ("BOMMMM",data)
            bomb = Bomb.Bomb(self)
            self.peta_game[data['x']][data['y']] = '!'
            self.screen.blit(self.bomb, [data['y'] * 50, data['x'] * 50])
            bomb.taruh(data['x'], data['y'])
            bomb.start()
        if (data['code']==300):
            self.isWin=True
            self.STATE=State.State.GAME_OVER
コード例 #4
0
 def __init__(self, dimentions):
     self.dimentions = dimentions  # Gotten from Driver.
     self.map_array = []  # Creates empty cell array.
     self.TNTMan = TNTMan.TNTMan()  # Creates playable character.
     self.Bomb = Bomb.Bomb(None)
     self.B_unbreakable_list = []
     self.B_breakable_list = []
     self.pos_map_array_bomb = None
コード例 #5
0
    def add_bomb(self, player):
        """
        Function adds bomb to bombs list.

        :param player: Player which left the bomb.
        :return:
        """
        self.bombs.append(
            Bomb.Bomb(player.x, player.y, time.time(), player.ind))
コード例 #6
0
 def deploy_bomb(self, key):
     if key == 32:
         if self.is_there_any_bomb() is False:
             # self.TNTMan.deploy_bomb()
             tntman_pos = self.get_position_tntman()
             for index in range(len(self.map_array)):
                 if self.map_array[index].position == tntman_pos:
                     self.map_array[index].content = Bomb.Bomb(tntman_pos)
                     self.pos_map_array_bomb = index
                     return True
                     break
コード例 #7
0
ファイル: Player.py プロジェクト: juanignava/Datos2.Project2
 def leave_bomb(self):
     """
     Method that allows the player to leave a bomb where he is
     """
     pos_i = self.get_x()
     pos_j = self.get_y()
     bomb_radius = self.explosion_radius
     if self.has_cross_bomb:
         bomb_radius = max(Matrix.COLUMNS, Matrix.ROWS)
         self.has_cross_bomb = False
     self.matrix[pos_i][pos_j] = Bomb.Bomb((pos_i, pos_j), self.matrix,
                                           bomb_radius, self)
     self.new_bomb = False
コード例 #8
0
 def explode(self):
     """ creates a dense bomb that
         explodes immediately
     """
     bomb = Bomb.Bomb(self.surface, BOMB_SMALL)
     bomb.initVars()
     bomb.setCenter(self.rect.center)
     bomb.setUpdateGroup(self.group)
     bomb.setDensity(25)
     bomb.setSmoke(1)
     bomb.setAmt(5)
     self.group.add(bomb)
     bomb.speed = 0
コード例 #9
0
 def move_bot(self):
     """
     Function handles bot move.
     :return:
     """
     for bot in self.bots:
         old_x = bot.x
         old_y = bot.y
         bot.move()
         if bot.is_bomb_left():
             self.bombs.append(Bomb.Bomb(old_x, old_y, time.time(), 1))
             self.board[bot.last_x][bot.last_y] = "XX"
         else:
             self.board[old_x][old_y] = "  "
         self.board[bot.x][bot.y] = "BB"
         bot.remember_player_pos([self.player])
         bot.remember_board(self.board)
         bot.remember_bombs(self.bombs)
コード例 #10
0
ファイル: Player.py プロジェクト: juanignava/Datos2.Project2
 def kick_bomb(self, position):
     """
     Auxiliary method for the Shoe power up, changes
     the position of the "kicked" bomb
     """
     pos_i = position[0]
     pos_j = position[1]
     self.matrix[pos_i][pos_j] = Matrix.Blank((pos_i, pos_j))
     new_position_found = False
     # Searches until it founds a Black position to add the bomb
     while not new_position_found:
         pos_i = random.randint(0, Matrix.ROWS - 1)
         pos_j = random.randint(0, Matrix.COLUMNS - 1)
         if isinstance(self.matrix[pos_i][pos_j], Matrix.Blank):
             new_position_found = True
     self.matrix[pos_i][pos_j] = Bomb.Bomb((pos_i, pos_j), self.matrix,
                                           self.explosion_radius, self)
     self.has_shoe = False
コード例 #11
0
ファイル: plane.py プロジェクト: dy5225/Plane
    def display(self):
        '''显示飞机'''
        self.window.blit(self.image, (self.x, self.y))

        # 显示子弹
        # 当子弹超过屏幕,将子弹回收
        for bullet in list(self.bullets):
            if bullet.y < -bullet.img_bullet_height:
                self.bullets.remove(bullet)

            #当子弹和敌人相撞的时候,收回子弹和敌人
            rect_buller = pygame.Rect(bullet.x, bullet.y,
                                      bullet.img_bullet_width,
                                      bullet.img_bullet_height)
            for enemy in utility.enemys:
                rect_enemy = pygame.Rect(enemy.x, enemy.y, enemy.img_ep_wideh,
                                         enemy.img_ep_height)
                collide = pygame.Rect.colliderect(rect_buller, rect_enemy)
                if collide:
                    if bullet in self.bullets:
                        self.bullets.remove(bullet)

                    #爆炸效果
                    x = enemy.x + enemy.img_ep_wideh / 2
                    y = enemy.y + enemy.img_ep_height / 2

                    self.bombs.append(Bomb.Bomb(x, y, self.window))

                    #敌机被炸,回收敌机
                    enemy.beiza()

                    #得分

                    utility.score += 10

            bullet.display()
            bullet.move()

        # 显示爆炸物
        for bomb in list(self.bombs):
            if bomb.isDestroy:
                self.bombs.remove(bomb)
            bomb.display()
コード例 #12
0
    elif dir == 'd':
        if bomberman.moveright():
            pass
    #os.system('clear')
    #b.pr()
    #        print("Lives:"+str(bomberman.lives)+"    "+ "Score:" + str(bomberman.score))

    elif dir == 'w':
        if bomberman.moveup():
            pass
    #os.system('clear')
    #b.pr()
    #        print("Lives:"+str(bomberman.lives)+"    "+ "Score:" + str(bomberman.score))

    elif dir == 'b':
        bomb = Bomb(bomberman.getx(), bomberman.gety())
        bombcount = bomb.bombcount
    elif dir == 'q':
        break
    lcount = 0
    while lcount < level:
        i = 0
        lcount = lcount + 1
        while True:
            if (i >= len(enemy)):
                break
            if enemy[i].isblocked():
                i += 1
            #print("i is "+str(i))
            else:
                r = random.randint(1, 4)
コード例 #13
0
def main():
    menu = True
    pygame.init()
    deathcounter = 0
    textcounter = 0
    fpsClock = pygame.time.Clock()
    message = ""
    windowSurfaceObj = pygame.display.set_mode((1280, 720), DOUBLEBUF)
    pygame.display.set_caption("William Wallace Castle Defender X-Treme 2140")
    soundObjectExplosion = pygame.mixer.Sound('explosion.wav')
    soundDecoy = pygame.mixer.Sound('decoy.wav')
    soundPwp = pygame.mixer.Sound('powerup.wav')
    soundShld = pygame.mixer.Sound('zap2.wav')
    desertBackground = pygame.image.load(
        os.path.join(os.curdir, 'desert-background.jpg')).convert_alpha()
    SurfaceObjLife = pygame.image.load("life.png")
    level = pygame.image.load(os.path.join(os.curdir,
                                           'LEVEL.png')).convert_alpha()
    player = Player()
    ArrowList = []
    missileList = []
    ShieldList = []
    BombList = []
    PowerUpList = []
    #EXPLOSION
    exploList = []

    #Enemy variables
    maxEnemies = 50
    enemyList = []

    #Castle HP
    HP = 100
    points = 0
    if menu == True:
        Menu(menu, windowSurfaceObj, fpsClock, desertBackground)
    pygame.key.set_repeat(1, 50)
    playing = True
    gravityLimit = False

    soundObjectExplosion = pygame.mixer.Sound("explosion.wav")
    soundObjectArrow = pygame.mixer.Sound("arrow.wav")
    pygame.mixer.music.load("BackgroundMusic.mp3")
    pygame.mixer.music.play(-1)

    gravityLimit = False
    #Main Loop
    LifeUp = 1
    while playing:
        windowSurfaceObj.blit(desertBackground, (0, 0))
        windowSurfaceObj.blit(level, (0, 0))
        mousex = player.x
        mousey = player.y

        #DRAW EXLPLOSIONS
        count = len(exploList) - 1
        while (count >= 0):
            windowSurfaceObj.blit(
                exploList[count].images[exploList[count].image],
                exploList[count].rect)
            if (exploList[count].updateEnemyPos()):
                exploList.pop(count)
            count = count - 1
        if (textcounter > 0):
            #print message
            textMessage = fontObj.render(str(message), False,
                                         pygame.Color(0, 0, 0))
            windowSurfaceObj.blit(
                textMessage,
                ((1280 - textMessage.get_rect().width) / 2 * 1, 670))
            textcounter -= 1
        if (deathcounter > 0):
            if (player.Lives <= 0):
                player.fall()
                player.updatePlayerSprite(21, 1)
            else:
                player.updatePlayerSprite(20, 1)
            deathcounter -= 1
            windowSurfaceObj.blit(player.images[player.image], player.rect)
            pygame.display.flip()
            fpsClock.tick(30)

        else:
            if (player.Lives <= 0):
                retry = gameOver(points, windowSurfaceObj, fpsClock,
                                 desertBackground)
                playing = False
            #Enemy code
            enemyGenerator(enemyList, maxEnemies, points)
            count = len(enemyList) - 1
            while (count >= 0):
                windowSurfaceObj.blit(
                    enemyList[count].images[enemyList[count].image],
                    enemyList[count].rect)

                enx = enemyList[count].x
                eny = enemyList[count].y
                chance = 1
                if enemyList[count].boss:
                    chance = 5
                if random.randint(
                        0, 100) < chance:  #1% chance that an enemy shoots
                    if enemyList[count].right:
                        speed = -enemyList[count].speed
                    else:
                        speed = enemyList[count].speed
                    tmp = random.randint(0, 100)
                    if player.DecoyCounter > 0:
                        playerX = player.DecoyX
                        playerY = player.DecoyY
                    else:
                        playerX = player.x
                        playerY = player.y
                    if enemyList[count].boss:
                        for i in range(0, 30):
                            m = Missile(enx + random.randint(-180, 180),
                                        eny + random.randint(-180, 180),
                                        player.x + random.randint(-180, 180),
                                        player.y + random.randint(-180, 180),
                                        speed)
                            missileList.append(m)
                    elif tmp < 30:
                        m = Missile(enx, eny, playerX, playerY + 20, speed)
                        missileList.append(m)
                        m = Missile(enx, eny, playerX, playerY, speed)
                        missileList.append(m)
                        m = Missile(enx, eny, playerX, playerY - 20, speed)
                        missileList.append(m)
                    elif tmp < 50:
                        m = Missile(enx, eny, playerX, playerY + 20, speed)
                        missileList.append(m)
                        m = Missile(enx, eny, playerX, playerY, speed)
                        missileList.append(m)
                        m = Missile(enx, eny, playerX, playerY - 20, speed)
                        missileList.append(m)
                        m = Missile(enx, eny, playerX, playerY + 40, speed)
                        missileList.append(m)
                        m = Missile(enx, eny, playerX, playerY - 40, speed)
                        missileList.append(m)
                    else:
                        missileList.append(
                            Missile(enx, eny, playerX, playerY, speed))
                if enemyList[count].updateEnemyPos(enemyList, count):
                    HP = HP - 2
                    if HP < 0:
                        HP = 0
                    exploList.append(Explo(enx, eny, False))
                    soundObjectExplosion.play()
                    if HP == 0:
                        retry = gameOver(points, windowSurfaceObj, fpsClock,
                                         desertBackground)
                        playing = False

                    exploList.append(Explo(enx, eny, False))
                count = count - 1

            skipFall = False
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                elif event.type == MOUSEMOTION:
                    mousex, mousey = event.pos
                    player.updateVector(mousex, mousey)
                elif event.type == MOUSEBUTTONDOWN:
                    myx, myy = event.pos
                    if (myx < player.x):
                        player.updatePlayerSprite(18, 1)
                    else:
                        player.updatePlayerSprite(19, 1)
                elif event.type == MOUSEBUTTONUP:
                    if event.button in (1, 2, 3):
                        mousex, mousey = event.pos
                        #if player.Arrows - 1 >= 0:
                        if 1:
                            arrow = Arrow(player.x, player.y + 24, mousex,
                                          mousey, player.gunmode)
                            ArrowList.append(arrow)
                            if player.MultiShot2:
                                arrow = Arrow(player.x, player.y + 24, mousex,
                                              mousey + 20, player.gunmode)
                                ArrowList.append(arrow)
                                arrow = Arrow(player.x, player.y + 24, mousex,
                                              mousey - 20, player.gunmode)
                                ArrowList.append(arrow)
                                arrow = Arrow(player.x, player.y + 24, mousex,
                                              mousey + 40, player.gunmode)
                                ArrowList.append(arrow)
                                arrow = Arrow(player.x, player.y + 24, mousex,
                                              mousey - 40, player.gunmode)
                                ArrowList.append(arrow)
                            elif player.MultiShot:
                                arrow = Arrow(player.x, player.y + 24, mousex,
                                              mousey + 30, player.gunmode)
                                ArrowList.append(arrow)
                                arrow = Arrow(player.x, player.y + 24, mousex,
                                              mousey - 30, player.gunmode)
                                ArrowList.append(arrow)
                            soundObjectArrow.play()
                            #player.Arrows -= 1

                        #left, middle, right button
                    elif event.button in (4, 5):
                        blah = "blah"
                        #scroll up or down
                elif event.type == KEYDOWN:
                    x = 0
                    y = 0
                    if event.key == K_SPACE:
                        if player.Repel > 0:
                            soundShld.play()
                            ShieldList.append(Shield(player.x, player.y))
                            player.Repel -= 1

                            #rep = pygame.image.load("pexpl1.png")
                            #windowSurfaceObj.blit(rep,rep.get_rect())
                            for i in range(0, len(missileList)):
                                missXp = missileList[i].x
                                missYp = missileList[i].y

                                diffX = missileList[i].x - player.x
                                diffY = missileList[i].y - player.y

                                if diffX != 0 and diffY != 0:
                                    missileList[i].vector = Vector(
                                        (diffX /
                                         sqrt(diffX * diffX + diffY * diffY)),
                                        (diffY /
                                         sqrt(diffX * diffX + diffY * diffY)))
                                else:
                                    if diffX == 0:
                                        if diffY < 0:
                                            missileList[i].vector = Vector(
                                                0, -1)
                                        elif diffY > 0:
                                            missileList[i].vector = Vector(
                                                0, 1)
                                    elif diffY == 0:
                                        if diffX < 0:
                                            missileList[i].vector = Vector(
                                                -1, 0)
                                        elif diffX > 0:
                                            missileList[i].vector = Vector(
                                                1, 0)
                                    else:
                                        missileList[i].vector = Vector(1, 0)
                                missileList[i].vel = 15
                    if event.key == K_LSHIFT:
                        if player.DecoyNum > 0:
                            soundDecoy.play()
                            player.Decoy(player.x, player.y)
                            player.DecoyNum -= 1

                    if event.key == K_LEFT or event.key == K_a:
                        x = -10
                    if event.key == K_RIGHT or event.key == K_d:
                        x = 10
                    if event.key == K_UP or event.key == K_w:
                        y = -.5
                    keystate = pygame.key.get_pressed()
                    if keystate[pygame.locals.K_UP] or keystate[
                            pygame.locals.K_w]:
                        y = -10
                    if keystate[pygame.locals.K_RIGHT] or keystate[
                            pygame.locals.K_d]:
                        x = 10
                    if keystate[pygame.locals.K_LEFT] or keystate[
                            pygame.locals.K_a]:
                        x = -10
                    #player.updatePlayerPos(x,0)
                    if y != 0:
                        if player.Gravity - 1 >= 0 and gravityLimit:
                            player.jet()
                            skipFall = True
                            player.Gravity -= 1
                        else:
                            if player.Gravity >= 20:
                                gravityLimit = True
                            else:
                                gravityLimit = False
                    if event.key == K_ESCAPE:
                        pygame.event.post(pygame.event.Event(QUIT))
                #else:
            x = 0
            y = 0
            keystate = pygame.key.get_pressed()
            if keystate[pygame.locals.K_UP] or keystate[pygame.locals.K_w]:
                y = -10
            if keystate[pygame.locals.K_RIGHT] or keystate[pygame.locals.K_d]:
                x = 10
            if keystate[pygame.locals.K_LEFT] or keystate[pygame.locals.K_a]:
                x = -10
            if (x != 0 or y != 0):
                player.updatePlayerPos(x, 0)
            if y != 0:
                if player.Gravity - 1 >= 0 and gravityLimit:
                    player.jet()
                    skipFall = True
                    player.Gravity -= 1
                else:
                    if player.Gravity >= 20:
                        gravityLimit = True
                    else:
                        gravityLimit = False

            #player.updateVector(mousex,mousey)
            #Castle health bar
            pygame.draw.rect(windowSurfaceObj, pygame.Color(255, 0, 0),
                             (540, 260, 200, 20))
            pygame.draw.rect(windowSurfaceObj, pygame.Color(0, 255, 0),
                             (540, 260, HP * 2, 20))
            #Display Points
            fontObj = pygame.font.Font('freesansbold.ttf', 32)
            pointsSurfaceObj = fontObj.render("Points: " + str(points), False,
                                              pygame.Color(255, 255, 255))
            windowSurfaceObj.blit(pointsSurfaceObj,
                                  (windowSurfaceObj.get_rect().width -
                                   pointsSurfaceObj.get_rect().width - 25, 25))
            #Display Lives
            fontObj = pygame.font.Font('freesansbold.ttf', 32)
            livesSurfaceObj = fontObj.render("Lives:", False,
                                             pygame.Color(255, 255, 255))
            windowSurfaceObj.blit(livesSurfaceObj, (300, 25))
            for i in range(0, player.Lives):
                windowSurfaceObj.blit(
                    SurfaceObjLife,
                    (300 + livesSurfaceObj.get_rect().width +
                     (i * (SurfaceObjLife.get_rect().width + 25)),
                     25 - SurfaceObjLife.get_rect().height / 4))
            #Display Arrows and gravity
            decoysSurfaceObj = fontObj.render(
                "Decoys: " + str(player.DecoyNum), False,
                pygame.Color(255, 255, 255))
            #arrowsSurfaceObj = fontObj.render("Arrows: " + str(player.Arrows)+"/"+str(player.ArrowsMax), False, pygame.Color(255,255,255))
            #gravitySurfaceObj = fontObj.render("Anti-Gravity: ", False, pygame.Color(255,255,255))
            windowSurfaceObj.blit(decoysSurfaceObj, (40, 15))
            repelSurfaceObj = fontObj.render("Repels: " + str(player.Repel),
                                             False,
                                             pygame.Color(255, 255, 255))
            windowSurfaceObj.blit(repelSurfaceObj, (40, 70))

            pygame.draw.rect(windowSurfaceObj, pygame.Color(255, 255, 0),
                             (20, 120, 200, 20))
            pygame.draw.rect(windowSurfaceObj, pygame.Color(255, 0, 0),
                             (20, 120, 40, 20))
            pygame.draw.rect(windowSurfaceObj, pygame.Color(0, 255, 0),
                             (20, 120, player.Gravity * 2, 20))
            #windowSurfaceObj.blit(arrowsSurfaceObj, (25, 25))
            #windowSurfaceObj.blit(gravitySurfaceObj, (25, arrowsSurfaceObj.get_rect().height + 50))
            #player.updatePos()
            if not skipFall:
                player.fall()
            #Arrow Code
            end = len(ArrowList)
            i = end - 1
            while i >= 0:
                chk = ArrowList[i].updateArrowPos()
                if not chk:
                    ArrowList.pop(i)
                    i = i - 1
                else:
                    end = len(enemyList) - 1
                    count = end
                    chk = True
                    while count >= 0:
                        if ArrowList[i].rect.colliderect(
                                enemyList[count].rect):
                            if (not player.gunmode):
                                ArrowList.pop(i)
                                i = i - 1
                            enx = enemyList[count].x
                            eny = enemyList[count].y
                            if (enemyList[count].Hit(enemyList, count, 5)):
                                exploList.append(Explo(enx, eny, False))
                                x = random.randint(0, 100)
                                if x <= 25:
                                    tmp = PowerUp(enx, eny)
                                    PowerUpList.append(tmp)
                                elif x > 95:
                                    b = Bomb(enx, eny)
                                    BombList.append(b)
                                soundObjectExplosion.play()
                            points = points + 5
                            if points / LifeUp >= 100:
                                LifeUp += 1
                                player.Lives += 1
                            chk = False
                        count -= 1
                        if i < 0:
                            count = -1
                    if chk:
                        ArrowObj = ArrowList[i].ArrowObj
                        windowSurfaceObj.blit(ArrowObj, ArrowList[i].rect)
                i = i - 1

            #Bomb Code
            i = len(BombList) - 1
            while i >= 0:
                if BombList[i].rect.colliderect(player.rect):
                    killAllEnemies(enemyList, exploList, soundObjectExplosion)
                    #deathcounter=45
                    points = points + 30
                    if points / LifeUp >= 100:
                        LifeUp += 1
                        player.Lives += 1
                    for i in range(0, 60):
                        x = random.randint(0, 1280)
                        y = random.randint(0, 720)
                        z = random.randint(0, 1)
                        exploList.append(Explo(x, y, z))
                    BombList = []
                    missileList = []
                    arrowList = []
                    i = -1
                else:
                    windowSurfaceObj.blit(BombList[i].image, BombList[i].rect)
                i = i - 1

            #Missile Code
            end = len(missileList)
            i = end - 1

            while i >= 0:
                chk = missileList[i].updateMissilePos()
                if not chk:
                    missileList.pop(i)
                    i = i - 1
                else:
                    if missileList[i].rect.colliderect(player.rect):
                        exploList.append(
                            Explo(missileList[i].x, missileList[i].y, True))
                        soundObjectExplosion.play()
                        missileList.pop(i)
                        player.Lives -= 1
                        #i = i - 1
                        if player.Lives <= 0 and playing == True:
                            killAllEnemies(enemyList, exploList,
                                           soundObjectExplosion)
                            deathcounter = 70
                        else:
                            i = -1
                            player.ArrowsMax = 20
                            player.ArrowsReplRate = 0.05
                            missileList = []
                            arrowList = []
                            #TODO
                            killAllEnemies(enemyList, exploList,
                                           soundObjectExplosion)
                            deathcounter = 45
                            player.RapidFire = False
                            player.MultiShot = False
                            player.MultiShot2 = False
                            player.gunmode = False
                        chk = False
                    if i < 0:
                        count = -1
                if chk:
                    missileObj = missileList[i].missileObj
                    windowSurfaceObj.blit(missileObj, missileList[i].rect)
                i = i - 1

            i = len(PowerUpList) - 1
            while i >= 0:
                PowerUpList[i].updateBoxSprite()
                if player.rect.colliderect(PowerUpList[i].rect):
                    soundPwp.play()
                    if PowerUpList[i].type == 0:
                        player.Repel += 1
                        message = "Repel!"
                        textcounter = 120
                    elif PowerUpList[i].type == 1:
                        if player.MultiShot:
                            player.MultiShot2 = True
                        player.MultiShot = True
                        message = "Multi Shot!"
                        textcounter = 120
                    elif PowerUpList[i].type == 2:
                        player.DecoyNum += 1
                        message = "Decoy!"
                        textcounter = 120
                    elif PowerUpList[i].type == 3:
                        if HP + 10 >= 100:
                            HP = 100
                        else:
                            HP += 10
                        message = "Castle HP restored!"
                        textcounter = 120
                    elif PowerUpList[i].type == 4:
                        player.gunmode = True
                        message = "Piercing bullets!"
                        textcounter = 120
                        soundObjectArrow = pygame.mixer.Sound("gun.wav")
                    PowerUpList.pop(i)
                else:
                    windowSurfaceObj.blit(
                        PowerUpList[i].images[PowerUpList[i].image],
                        PowerUpList[i].rect)
                i = i - 1
            #check enemy detection with player
            i = len(enemyList) - 1
            while i >= 0:
                if player.rect.colliderect(enemyList[i].rect):
                    player.Lives -= 1
                    exploList.append(
                        Explo(enemyList[i].x, enemyList[i].y, True))
                    soundObjectExplosion.play()
                    exploList.append(
                        Explo(enemyList[i].x, enemyList[i].y, True))
                    enemyList.pop(i)
                    if player.Lives <= 0 and playing == True:
                        killAllEnemies(enemyList, exploList,
                                       soundObjectExplosion)
                        deathcounter = 70
                    else:
                        player.ArrowsMax = 20
                        player.ArrowsReplRate = 0.05
                        killAllEnemies(enemyList, exploList,
                                       soundObjectExplosion)
                        deathcounter = 45
                        missileList = []
                        arrowsList = []
                        player.RapidFire = False
                        player.MultiShot = False
                        player.MultiShot2 = False
                        player.gunmode = False
                    i = len(enemyList)
                i = i - 1

            windowSurfaceObj.blit(player.images[player.image], player.rect)
            player.DecoyCounter -= 5
            if player.DecoyCounter > 0:
                windowSurfaceObj.blit(player.images[21],
                                      (player.DecoyX, player.DecoyY))
            #DRAW SHIELD
            count = len(ShieldList) - 1
            while (count >= 0):
                windowSurfaceObj.blit(
                    ShieldList[count].images[ShieldList[count].image],
                    ShieldList[count].rect)
                ShieldList[count].x = player.x
                ShieldList[count].y = player.y

                if (ShieldList[count].move(0, 0)):
                    ShieldList.pop(count)
                count = count - 1

            #pygame.display.update()
            pygame.display.flip()
            fpsClock.tick(30)
            #if player.Arrows + 1 <= player.ArrowsMax:
            #    player.ArrowsRepl += player.ArrowsReplRate
            #   if player.ArrowsRepl >= 1.0:
            #       player.Arrows += 1
            #      player.ArrowsRepl = 0.0
            if player.Gravity + 1 <= 100:
                player.GravityRepl += .5
                if player.GravityRepl >= 1.0:
                    player.Gravity += 1
                    player.GravityRepl = 0.0

    if retry:
        pygame.mixer.music.stop
        main()
    else:
        pygame.quit()
コード例 #14
0
        start = time.time()
        screen.blit(bg, (0, 0))

        if not game_over:

            # 判断玩家飞机个地方飞机相撞
            playRect = pygame.Rect(player.x, player.y, player.img_width,
                                   player.img_height)
            for enemy in utility.enemys:
                enemyRect = pygame.Rect(enemy.x, enemy.y, enemy.img_ep_wideh,
                                        enemy.img_ep_height)
                ico = pygame.Rect.colliderect(playRect, enemyRect)
                if ico:
                    x = player.x - player.img_width / 2
                    y = player.y - player.img_height / 2
                    player.bombs.append(Bomb.Bomb(x, y, screen))

                    # 游戏结束
                    game_over = True
                    break
        if not game_over:
            # 显示玩家飞机
            player.display()
        if not game_over:
            # 显示敌方飞机
            for enemyPlane in utility.enemys:
                enemyPlane.display()
                enemyPlane.move()

            keys = pygame.key.get_pressed()
            if keys[K_LEFT]:
コード例 #15
0
def SpawnBomb(car_pos, screen):
    car_bomb.append(Bomb.BombSprite("bomb.png", car_pos))
コード例 #16
0
    def parseRoomXML(self, xml):
        self.w, self.h = map(int, [xml.get('width'), xml.get('height')])
        for obj in xml:  # Iterate through room objects
            attr = obj.attrib
            x, y = int(attr["x"]), int(attr["y"])

            if obj.tag == "spawn":

                typ = int(obj[0].get('type'))
                var = int(obj[0].get('variant'))
                subtype = int(obj[0].get('subtype'))

                # Spawn the correct item for the type
                if typ in [1500, -1, -1, 1496, -1]:
                    self.poops.append(
                        Poop([1500, -1, -1, 1496, -1].index(typ), (x, y),
                             self.textures["poops"], self.sounds["pop"]))
                elif typ == 1000:
                    self.rocks.append(
                        Rock(randint(0, 2), (x, y), False,
                             self.sounds["rockBreak"], self.textures["rocks"]))
                elif typ == 33:
                    self.fires.append(
                        Fire(0, (x, y),
                             [self.sounds["fireBurn"], self.sounds["steam"]],
                             self.textures["fires"]))
                elif typ == 5 and var == 10:
                    self.other.append(
                        Heart(
                            [1, 3, 6].index(subtype), (x, y),
                            [self.sounds["heartIntake"], self.sounds["holy"]],
                            self.textures["pickupHearts"]))
                elif typ == 5 and var == 20:
                    self.other.append(
                        Coin(subtype - 1, (x, y), [
                            self.sounds["coinDrop"], self.sounds["coinPickup"]
                        ], self.textures["coins"]))
                elif typ == 5 and var == 30:
                    self.other.append(
                        Key(0, (x, y),
                            [self.sounds["keyDrop"], self.sounds["keyPickup"]],
                            self.textures["keys"]))
                elif typ == 5 and var == 40:
                    self.other.append(
                        Bomb(self,
                             0, (x, y), [self.sounds["explosion"]],
                             self.textures["bombs"],
                             explode=False))
                elif typ == 13:
                    self.enemies.append(
                        Fly((x, y), [self.sounds["deathBurst"]],
                            self.textures["enemies"]["fly"]))
                elif typ == 14:
                    self.enemies.append(
                        Pooter((x, y), [self.sounds["deathBurst"]],
                               self.textures["enemies"]["pooter"]))
                elif typ == 26:
                    self.enemies.append(
                        Maw((x, y), [self.sounds["deathBurst"]],
                            self.textures["enemies"]["maw"]))
                elif typ == 27:
                    self.enemies.append(
                        Host((x, y), self.sounds, self.textures))
                elif typ == 30:
                    self.enemies.append(
                        Boil((x, y), self.sounds, self.textures))
コード例 #17
0
    def update(self):
        self.initSprite()
        self.gm = GameMap.GameMap()
        self.peta_game = self.gm.createMap("./assets/peta/map.txt")
        self.client.start()

        while(self.STATE==State.State.RUNNING):
            self.clock.tick(15)
            self.screen.fill(0)
            location=self.packageclient.location(self.player.x,self.player.y,self.player.file_player,self.room)
            self.client.sendall(location)

            self.up=pygame.key.get_pressed()[pygame.K_w]
            self.down = pygame.key.get_pressed()[pygame.K_s]
            self.left = pygame.key.get_pressed()[pygame.K_a]
            self.right = pygame.key.get_pressed()[pygame.K_d]
            self.space = pygame.key.get_pressed()[pygame.K_SPACE]

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

            if (self.space):
                self.peta_game[self.player.x][self.player.y]='!'
                bombData=self.packageclient.createPackageBomb(self.player.x,self.player.y,self.room)
                self.client.sendall(bombData)
                bomb=Bomb.Bomb(self)
                bomb.taruh(self.player.x,self.player.y)
                bomb.start()

            if (self.up):
                if (self.player.x-1>=0 and self.peta_game[self.player.x-1][self.player.y]=='0' ):
                    self.player.x=self.player.x-1
            if (self.down):
                if (self.player.x+1<11 and self.peta_game[self.player.x+1][self.player.y]=='0' ):
                    self.player.x = self.player.x + 1
            if (self.left):
                if (self.player.y-1>=0 and self.peta_game[self.player.x][self.player.y-1]=='0' ):
                    self.player.y = self.player.y - 1
            if (self.right):
                if (self.player.y+1<16 and self.peta_game[self.player.x][self.player.y+1]=='0' ):
                    self.player.y = self.player.y + 1

            for i in range(len(self.peta_game)):
                for j in range(len(self.peta_game[i])):

                    if i==self.player.x and j==self.player.y:
                        if (self.player.file_player=="player1"):
                            self.screen.blit(self.p1, [j * 50, i * 50])
                        elif (self.player.file_player == "player2"):
                            self.screen.blit(self.p2, [j * 50, i * 50])

                    elif i == self.player2.x and j == self.player2.y:
                        if (self.player2.file_player == "player1"):
                            self.screen.blit(self.p1, [j * 50, i * 50])
                        elif (self.player2.file_player == "player2"):
                            self.screen.blit(self.p2, [j * 50, i * 50])

                    elif self.peta_game[i][j] == '0':
                        self.screen.blit(self.grass, [j*50, i*50])
                    elif self.peta_game[i][j] == '1':
                        self.screen.blit(self.wall,[j*50,i*50])
                    elif self.peta_game[i][j] == '2':
                        self.screen.blit(self.box,[j*50,i*50])
                    elif self.peta_game[i][j] == '!':
                        self.screen.blit(self.bomb,[j*50,i*50])
                    elif self.peta_game[i][j] == '@' :
                        self.screen.blit(self.explosion,[j*50,i*50])


            pygame.display.flip()

        if (self.isWin==False):
            self.gameOver()
        else :
            self.gameWin()
コード例 #18
0
ファイル: Game.py プロジェクト: seenbeen/CS3244-Project
	def run(self, screen, sounds, textures, fonts, joystick=None):
		# Run the main loop
		animatingRooms = self.animatingRooms
		currentRoom = self.currentRoom

		# Setup controls and create character
		cn = self.controls
		self.isaac = isaac = Character(self.characterType, (WIDTH//2, (HEIGHT//4)*3), [[cn[3], cn[1], cn[2], cn[0]], [cn[7], cn[5], cn[6], cn[4]]], textures, sounds, fonts)

		# Setup special stats
		if self.characterType == 0:
			isaac.pill = Pill((0,0), textures["pills"])
		elif self.characterType == 2:
			isaac.speed = 3
			isaac.damage = 1
			del isaac.hearts[-1]

		self.sounds = sounds
		self.textures = textures
		self.setup()

		floor = self.floor
		floorIndex = self.floorIndex
		clock = time.Clock()

		# Create minimap
		self.minimap = Surface((textures["map"]["background"].get_width(), textures["map"]["background"].get_height())).convert_alpha()
		self.updateMinimap(self.currentRoom)
		self.minimap.set_clip(Rect(4, 4, 100, 86))
		mWidth = self.minimap.get_width()
		mHeight = self.minimap.get_height()
		
		# Define possible moves
		self.posMoves = [[1, 0], [0, 1], [-1, 0], [0, -1]]
		posMoves = self.posMoves

		# Set the game (so we can modify stuff from the character class)
		self.isaac.game = self

		self.updateFloor()

		running = True
		while running:

			currTime = cTime()
			#k = key.get_pressed() # Current down keys

			for e in event.get():
				if e.type == QUIT:
					quit() 
				elif e.type == KEYDOWN and e.key == 27:
					# Pause the game
					running = pause(screen, self.seed, textures, fonts, [self.isaac.speed, self.isaac.shotSpeed, self.isaac.damage, self.isaac.luck, self.isaac.shotRate, self.isaac.range])

				elif e.type == KEYDOWN:
					# Update key value
					isaac.moving(e.key, True, False)
	
					if e.key == self.controls[-1]:
						# Bomb key pressed
						if isaac.pickups[1].use(1):
							self.floor[self.currentRoom].other.append(Bomb(self.floor[self.currentRoom], 0, ((isaac.x-GRIDX)/GRATIO, (isaac.y-GRIDY)/GRATIO), [sounds["explosion"]], textures["bombs"], explode=True))

					elif e.key == self.controls[-2]:
						# Pill key pressed
						isaac.usePill()

				elif e.type == KEYUP:
					# Update key value
					isaac.moving(e.key, False, False)

			# Draw animating rooms (The ones that are shifting in and out of frame)
			if len(animatingRooms) > 0:
				for r in animatingRooms[:]:
					r.render(screen, isaac, currTime)
					if not r.animating:
						animatingRooms.remove(r)
			else:
				screen.fill((0,0,0))

				# Render the room
				move = self.floor[self.currentRoom].render(screen, isaac, currTime)

				if move[0] != 0 or move[1] != 0:
					old = tuple(self.currentRoom[:])

					self.currentRoom = (move[0]+self.currentRoom[0], move[1]+self.currentRoom[1])
					try:
						# Animate the room
						self.floor[self.currentRoom].animateIn(move)
						self.floor[old].animateOut(move)

						# Animate the room
						animatingRooms.append(self.floor[self.currentRoom])
						animatingRooms.append(self.floor[old])

						# Animate isaac with the room
						isaac.x += 650*(-move[0])
						isaac.y += 348*(move[1])


						# Remove tears from an animating room
						isaac.clearTears()

						# Check if you enter a boss room
						if self.floor[self.currentRoom].variant == 2 and not self.floor[self.currentRoom].entered:
							sounds["bossIntro"].play()

							# Give the correct boss index
							bossIntro(screen, self.characterType, [Gurdy, Duke].index(type(self.floor[self.currentRoom].enemies[0])), self.floorIndex)

						self.floor[self.currentRoom].entered = True

						for m in posMoves:
							mx, my = m
							x, y = self.currentRoom
							newPos = (mx+x, my+y)

							try:
								self.floor[newPos].seen = True
							except:
								pass

						self.updateMinimap(self.currentRoom)

					except:
						# That room doesnt exist
						self.currentRoom = old

			if self.floor[self.currentRoom].variant == 2:
				# Its a boss room
				try:
					# Draw the boss bar
					bossbar(screen, self.floor[self.currentRoom].enemies[0].health/100)
				except:
					pass

				if not self.won and self.floorIndex == 6 and len(self.floor[self.currentRoom].enemies) == 0:
					self.banners.append(Banner("You won", self.textures))
					self.won = True


			# DRAW MAP
			screen.blit(self.minimap, (MAPX-mWidth//2, MAPY-mHeight//2))

			# Blit all banners
			for banner in self.banners:
				if banner.render(screen):
					self.banners.remove(banner)

			if joystick != None:
				joystick.update()

			if isaac.dead:
				running = False

			display.flip()
			clock.tick(60)
コード例 #19
0
ファイル: Player.py プロジェクト: Mylos97/Platformer_v2
    def key_input(self):
        self.vel = [0, 0]
        keystate = pygame.key.get_pressed()

        if keystate[pygame.K_LEFT] or keystate[pygame.K_a]:
            self.accel[0] -= self.accel_speed

            if self.accel[0] <= -self.top_speed:
                self.accel[0] = -self.top_speed

            self.vel[0] = self.accel[0]

        else:
            if self.accel[0] < 0:
                self.accel[0] += self.accel_speed * 2

                if self.accel[0] >= 0:
                    self.accel[0] = 0
                self.vel[0] = self.accel[0]

        if keystate[pygame.K_RIGHT] or keystate[pygame.K_d]:
            self.accel[0] += self.accel_speed

            if self.accel[0] >= self.top_speed:
                self.accel[0] = self.top_speed

            self.vel[0] = self.accel[0]

        else:
            if self.accel[0] > 0:
                self.accel[0] -= self.accel_speed * 2

                if self.accel[0] <= 0:
                    self.accel[0] = 0

                self.vel[0] = self.accel[0]

        if keystate[pygame.K_UP] or keystate[pygame.K_w]:
            self.accel[1] -= self.accel_speed

            if self.accel[1] <= -self.top_speed:
                self.accel[1] = -self.top_speed

            self.vel[1] = self.accel[1]

        else:
            if self.accel[1] < 0:
                self.accel[1] += self.accel_speed * 2

                if self.accel[1] >= 0:
                    self.accel[1] = 0
                self.vel[1] = self.accel[1]

        if keystate[pygame.K_DOWN] or keystate[pygame.K_s]:
            self.accel[1] += self.accel_speed

            if self.accel[1] >= self.top_speed:
                self.accel[1] = self.top_speed

            self.vel[1] = self.accel[1]

        else:
            if self.accel[1] > 0:
                self.accel[1] -= self.accel_speed * 2

                if self.accel[1] <= 0:
                    self.accel[1] = 0

                self.vel[1] = self.accel[1]

        if keystate[pygame.K_SPACE] and self.bomb_timer > 10:
            x_y = [self.rect.x, self.rect.y]
            self.bomb_timer = 0
            Mediator.ALL_GAMEOBJECTS.append(Bomb(x_y.copy()))

        if keystate[pygame.K_ESCAPE]:
            sys.exit()
コード例 #20
0
     bomber.moveRight()
     bomber.MakeBomber()
 elif mv == 'a':
     bomber.RemoveBomber()
     bomber.moveLeft()
     bomber.MakeBomber()
 elif mv == 's':
     bomber.RemoveBomber()
     bomber.moveDown()
     bomber.MakeBomber()
 elif mv == 'w':
     bomber.RemoveBomber()
     bomber.moveUp()
     bomber.MakeBomber()
 elif mv == 'b':
     boom = Bomb.Bomb(bomber, time.time())
     '''
         This condition can be used to set interval between two bombs and
         thus number of bombs that could be present simutaneously on the
         board, to do so just check for len of Global.bombs array against
         required number of restricted bomb numbers.
     '''
     if boom.GetTime() - Global.lbombtime >= 1.5:
         Global.bombs.append(boom)
         Global.lbombtime = boom.GetTime()
         boom.MakeBomb()
     '''
     if not len(Global.bombs):
         Global.bombs.append(boom)
         Global.lbombtime = boom.GetTime()
         boom.MakeBomb()
コード例 #21
0
    def Action(self, screen, pressed_Key, seconds, bomb_map, all_blocks):
        #check if player is invincible
        if self.invincible_turn > 0:
            #flashing affect
            if (self.show == 1):
                self.show = 0
            else:
                self.show = 1
            self.invincible_turn -= 1

        #count down for the time that hurt_face will display
        if (self.hurt_turn > 0):
            self.hurt_turn -= 1
            screen.blit(self.hurt_face, (665, 665))

        #check if player is currently being knock
        if self.knock > 0:
            #decrease the turn
            self.knock -= 1
            distance = self.knockspeed * seconds

            #check knock direction
            if self.knockDirection == 1:
                if self.rect.x - distance > 0:
                    self.rect.x -= distance
                else:
                    self.rect.x = 0
            elif self.knockDirection == 3:
                if self.rect.x + distance < self.background_x:
                    self.rect.x += distance
                else:
                    self.rect.x = self.image_x
            elif self.knockDirection == 2:
                if self.rect.y - distance > 0:
                    self.rect.y -= distance
                else:
                    self.rect.y = 0
            elif self.knockDirection == 4:
                if self.rect.y + distance < self.background_y:
                    self.rect.y += distance
                else:
                    self.rect.y = self.background_y
            screen.blit(self.images[self.image_index],
                        (self.rect.x, self.rect.y))
            return

        self.time += seconds
        self.bomb_since_last += seconds
        switch = False

        if self.slowed:
            self.slow_time -= seconds

        if self.slow_time < 0:
            self.slow_time = 0
            self.speed = self.initial_speed
            self.slowed = False

        if self.inversed:
            self.inverse_time -= seconds

        if self.inverse_time < 0:
            self.inverse_time = 0
            self.speed *= (-1)
            self.initial_speed *= (-1)
            self.inversed = False

        if self.rushing:
            self.rush_time -= seconds

        if self.rush_time < 0:
            self.rush_time = 0
            self.speed = self.initial_speed
            self.rushing = False

        #check if it is time to change the image index
        if self.time >= 0.2:
            switch = True
            self.time = 0

        distance = seconds * self.speed

        if pressed_Key[K_SPACE] and self.bomb_since_last >= 0.2:
            self.bomb_since_last = 0

            # Becareful with this line, need to check index out of bound exception
            new_bomb = Bomb(self.bomb_name, int(self.rect.x + 23),
                            int(self.rect.y + 23), self.bomb_damage)

            bomb_map.AddBomb(new_bomb)
            #print (self.rect.x)
            #print (",")
            #print (self.rect.y)

        # 1 = left, 2 = up, 3 = right, 4 = down
        #collide = pygame.sprite.spritecollideany(self, all_blocks, False);
        if pressed_Key[K_LEFT]:
            self.rect.x -= distance
            if self.rect.x < 0:
                self.rect.x = 0
            if self.rect.x > self.background_x:
                self.rect.x = self.background_x

        #only change the image when switch is true
            if switch == True or self.image_index < 8 or self.image_index > 11:
                self.image_index = ChangeNextIndex(self.image_index, 1)
        elif pressed_Key[K_RIGHT]:
            self.rect.x += distance
            if self.rect.x < 0:
                self.rect.x = 0
            if self.rect.x > self.background_x:
                self.rect.x = self.background_x
            if switch == True or self.image_index < 12:
                self.image_index = ChangeNextIndex(self.image_index, 3)
        elif pressed_Key[K_UP]:
            self.rect.y -= distance
            if self.rect.y < 0:
                self.rect.y = 0
            if self.rect.y > self.background_y:
                self.rect.y = self.background_y
            if switch == True or self.image_index > 3:
                self.image_index = ChangeNextIndex(self.image_index, 2)
        elif pressed_Key[K_DOWN]:
            self.rect.y += distance
            if self.rect.y < 0:
                self.rect.y = 0
            if self.rect.y > self.background_y:
                self.rect.y = self.background_y
            if switch == True or self.image_index < 4 or self.image_index > 7:
                self.image_index = ChangeNextIndex(self.image_index, 4)
        else:
            self.image_index = (self.image_index / 4) * 4

        if self.invincible_turn <= 0 or self.show == 1:
            screen.blit(self.hp_image, (self.rect.x, self.rect.y - 13))
            screen.blit(self.images[self.image_index],
                        (self.rect.x - 5, self.rect.y))
コード例 #22
0
ファイル: Level.py プロジェクト: rntakor/bomberman
    def destroyWalls(self, x, y, blastRange):
        '''Used when a bomb explodes to put blast graphics in all four directions
            returns powerups and blasts so they can be drawn onscreen by the caller 
        - x, x location where blast starts
        - y, y location where blast starts
        - blastRange, used to limit how far the blasts extend in each direction
        '''
        checkNumeric(x)
        if x != 0:
            checkPositive(x)

        checkNumeric(y)
        if y != 0:
            checkPositive(y)

        checkNumeric(blastRange)
        checkPositive(blastRange)

        walls = []
        powerups = []
        hitWallUp = False
        hitWallDown = False
        hitWallLeft = False
        hitWallRight = False

        blasts = []
        blasts.append(Bomb.Blast(x, y, const.CENTER_FLAME, True))
        for i in range(1, blastRange + 1):
            if y - i > 0 and not hitWallUp:
                if isinstance(self.layout[y - i][x], Wall.Wall):
                    walls.append(self.layout[y - i][x])
                    hitWallUp = True
                    if self.layout[y - i][x].breakable:
                        blasts.append(
                            Bomb.Blast(x, y - i, const.UP_FLAME, True))
                if not hitWallUp:
                    if i < blastRange:
                        blasts.append(
                            Bomb.Blast(x, y - i, const.UP_FLAME, False))
                    else:
                        blasts.append(
                            Bomb.Blast(x, y - i, const.UP_FLAME, True))

            if y + i < self.levelHeight and not hitWallDown:
                if isinstance(self.layout[y + i][x], Wall.Wall):
                    walls.append(self.layout[y + i][x])
                    hitWallDown = True
                    if self.layout[y + i][x].breakable:
                        blasts.append(
                            Bomb.Blast(x, y + i, const.DOWN_FLAME, True))
                if not hitWallDown:
                    if i < blastRange:
                        blasts.append(
                            Bomb.Blast(x, y + i, const.DOWN_FLAME, False))
                    else:
                        blasts.append(
                            Bomb.Blast(x, y + i, const.DOWN_FLAME, True))

            if x - i > 0 and not hitWallLeft:
                if isinstance(self.layout[y][x - i], Wall.Wall):
                    walls.append(self.layout[y][x - i])
                    hitWallLeft = True
                    if self.layout[y][x - i].breakable:
                        blasts.append(
                            Bomb.Blast(x - i, y, const.LEFT_FLAME, True))
                if not hitWallLeft:
                    if i < blastRange:
                        blasts.append(
                            Bomb.Blast(x - i, y, const.LEFT_FLAME, False))
                    else:
                        blasts.append(
                            Bomb.Blast(x - i, y, const.LEFT_FLAME, True))

            if x + i < self.levelWidth and not hitWallRight:
                if isinstance(self.layout[y][x + i], Wall.Wall):
                    walls.append(self.layout[y][x + i])
                    hitWallRight = True
                    if self.layout[y][x + i].breakable:
                        blasts.append(
                            Bomb.Blast(x + i, y, const.RIGHT_FLAME, True))
                if not hitWallRight:
                    if i < blastRange:
                        blasts.append(
                            Bomb.Blast(x + i, y, const.RIGHT_FLAME, False))
                    else:
                        blasts.append(
                            Bomb.Blast(x + i, y, const.RIGHT_FLAME, True))
        for theWall in walls:
            result = theWall.destroy(self)
            if result:
                powerups.append(result)
        return powerups, blasts
コード例 #23
0
    def render(self, surface, character, currTime):

        if len(self.enemies) > 0:
            for door in self.doors:
                door.close()

        else:
            for door in self.doors:
                door.open()

            if self.hadEnemies and len(self.other) == 0 and randint(
                    0, 5) == 0 and not self.spawnedItem:
                typ = randint(0, 2)
                self.spawnedItem = True

                # Random spawn
                if typ == 0:
                    self.other.append(
                        Coin(0, (6, 2), [
                            self.sounds["coinDrop"], self.sounds["coinPickup"]
                        ], self.textures["coins"]))
                elif typ == 1:
                    self.other.append(
                        Bomb(self,
                             1, (6, 2), [self.sounds["explosion"]],
                             self.textures["bombs"],
                             explode=False))
                elif typ == 2:
                    self.other.append(
                        Key(0, (6, 2),
                            [self.sounds["keyDrop"], self.sounds["keyPickup"]],
                            self.textures["keys"]))

            # Create trapdoor in empty boss room
            if self.variant == 2 and self.floor < 6 and not Trapdoor in list(
                    map(type, self.other)):
                self.other.append(Trapdoor(self.textures["trapdoor"]))

        if not self.animating:
            # Render stationary room

            surface.blit(self.backdrop, (38, -16))

            for door in self.doors:
                door.render(surface)

            for rock in self.rocks:
                rock.render(surface)

            for poop in self.poops:
                poop.render(surface)

            for fire in self.fires:
                fire.render(surface, currTime)

            objects = self.rocks + self.poops + self.fires

            for other in self.other[::-1]:
                if not other.render(surface, currTime, objects + self.enemies):
                    self.other.remove(other)

            everything = objects + self.other

            # Character x and y
            cx, cy = int((character.x - GRIDX) / GRATIO), int(
                (character.y - GRIDY) / GRATIO)

            if cx != self.lcx or cy != self.lcy:
                self.lcx, self.lcy = cx, cy
                for enemy in self.enemies:
                    enemy.pathFind((cx, cy), self.nodes, self.paths)

            for enemy in self.enemies[:]:
                if not enemy.render(surface, currTime, character, self.nodes,
                                    self.paths, self.levelBounds, objects):
                    self.enemies.remove(enemy)

            move = character.render(surface, currTime, self.levelBounds,
                                    everything, self.doors)

            return move
        else:
            # Render moving room

            moveDistance = 40  # How far the canvas should move
            self.ax += [0, 1, 0, -1][self.aDirection] * moveDistance
            self.ay += [-1, 0, 1, 0][self.aDirection] * moveDistance

            if abs(self.sx - self.ax) >= WIDTH or abs(self.sy -
                                                      self.ay) >= HEIGHT:
                self.animating = False
                self.ax, self.ay = 0, 0
                self.sx, self.sy = 0, 0
            else:
                surface.blit(self.backdrop, (38 + self.ax, -16 + self.ay))

                for door in self.doors:
                    door.render(surface, ox=self.ax, oy=self.ay)

                for rock in self.rocks:
                    rock.render(surface, ox=self.ax, oy=self.ay)

                for poop in self.poops:
                    poop.render(surface, ox=self.ax, oy=self.ay)

                for fire in self.fires:
                    fire.render(surface, currTime, ox=self.ax, oy=self.ay)

                objects = self.rocks + self.poops + self.fires

                for other in self.other[::-1]:
                    if not other.render(
                            surface, currTime, objects, ox=self.ax,
                            oy=self.ay):
                        self.other.remove(other)

            return [0, 0]
コード例 #24
0
 def put_bomb(self):
     b = Bomb()
     tup = self.get_position()
     tp = b.create_bomb(tup[0], tup[1])
     return tp
コード例 #25
0
ファイル: KTaNE.py プロジェクト: protzermotzer/KTaNE-Python
def lose():
    spacer(100)
    input('you\'re lose game over sorry')
    quit()


# START =====================================================================================

module_rand = input(
    'Would you like one of each module or random types? [(O)ne of each / (R)andom types]\n> '
)

if module_rand == 'R':
    module_amount = input('How many modules would you like? \n> ')
    bomb = Bomb.Bomb(int(module_amount), is_random=True)
else:
    bomb = Bomb.Bomb(0, is_random=False)

spacer(100)
divider_length = 60

start_time = datetime.now()
in_module = False
module_num = ''
while 1:
    if not in_module:
        show_all_modules()
        try:
            module_num = int(input('> '))
コード例 #26
0
ファイル: Bomberman.py プロジェクト: Yahnit/Bomberman
 def placeBomb(self,x,y,screen,char):
     bomb=Bomb(x,y)
     bomb.insertBomb(x,y,screen,char)
     return bomb
コード例 #27
0
    def run_logic(self):
        if not self.game_over and not self.end:
            # Move all the sprites
            self.all_sprites_list.update()

            # For each bonus alien if alien.x > screen.width + 10 remove alien
            for bonus_alien in self.alien_list:
                if bonus_alien.rect.x > SCREEN_WIDTH + 10:
                    self.alien_list.remove(bonus_alien)
                    self.all_sprites_list.remove(bonus_alien)

            # Have the aliens drop bombs
            for alien in self.alien_list:
                rand = random.randrange(200)
                if (rand < 2):
                    if (alien.bombing == False and alien.bombs > 0):
                        bomb = Bomb()
                        alien.bombing = True
                        alien.bombs -= 1
                        bomb.rect.x = alien.rect.x + 18
                        bomb.rect.y = alien.rect.y
                        # Add the bomb to the lists
                        self.all_sprites_list.add(bomb)
                        self.bomb_list.add(bomb)

            # Calculate mechanics for each bullet
            for bullet in self.bullet_list:

                # See if it hit an alien or wall
                alien_hit_list = pygame.sprite.spritecollide(
                    bullet, self.alien_list, False)  # Changed to False
                wall_hit_list = pygame.sprite.spritecollide(
                    bullet, self.wall_list, True)

                # For each alien hit, remove the bullet and add to the score
                for alien in alien_hit_list:
                    alien.hitpoints -= 1
                    if alien.hitpoints <= alien.start_hitpoints / 2:
                        alien.not_damaged = False
                    if alien.hitpoints < 1:
                        if alien.bonus_points > 0:
                            Game.score += alien.bonus_points
                        else:
                            Game.score += alien.start_hitpoints * 10

                        # Every 1000 points player gets a new life
                        if Game.score > 0 and Game.score % 100 == 0:
                            Game.lives += 1
                            self.life.play()
                        alien_hit_list.remove(alien)
                        self.alien_list.remove(alien)
                        self.all_sprites_list.remove(alien)
                        self.ping.play()
                        print(Game.score)
                    self.explosion.play()
                    explode = Explosion()
                    explode.rect.x = alien.rect.x
                    explode.rect.y = alien.rect.y
                    self.all_sprites_list.add(explode)
                    self.explosion_list.add(explode)
                    self.bullet_list.remove(bullet)
                    self.all_sprites_list.remove(bullet)

                # Kill bullet object if it flies up off the screen
                if bullet.rect.y < -10:
                    self.bullet_list.remove(bullet)
                    self.all_sprites_list.remove(bullet)

                # Remove wall pieces if they have been hit
                for wall in wall_hit_list:
                    self.explosion.play()
                    self.bullet_list.remove(bullet)
                    self.all_sprites_list.remove(bullet)

            # Remove explosion objects after they have exploded
            for exp in self.explosion_list:
                if exp.finished:
                    self.explosion_list.remove(exp)
                    self.all_sprites_list.remove(exp)

            # Update game for each bomb dropped
            for bomb in self.bomb_list:
                wall_hit_list = pygame.sprite.spritecollide(
                    bomb, self.wall_list, True)
                bomb_hit_list = pygame.sprite.spritecollide(
                    self.player, self.bomb_list, False)

                # Play explosion sound and remove bombs that hit the wall
                for wall in wall_hit_list:
                    self.explosion.play()
                    self.bomb_list.remove(bomb)
                    self.all_sprites_list.remove(bomb)

                # Play hit sound and rove bomb that have hit player
                # Reduce player lives and end game if they have no lives
                for b in bomb_hit_list:
                    self.bomb_list.remove(b)
                    self.all_sprites_list.remove(b)
                    self.hit.play()
                    Game.lives -= 1
                    print("Lives = " + str(Game.lives))
                    if Game.lives == 0:
                        self.end = True

                # Remove alien bombs from game that have droped below screen
                if bomb.rect.y > SCREEN_HEIGHT:
                    self.bomb_list.remove(bomb)
                    self.all_sprites_list.remove(bomb)

            # See if the self.player alien has collided with anything.
            aliens_hit_list = pygame.sprite.spritecollide(
                self.player, self.alien_list, False)

            # Check the list of collisions.
            for alien in aliens_hit_list:
                alien.change_y *= -1
                alien.change_x *= -1
                print("Collided with Alien")

            # If alien hits wall play explsion, remove wall piece
            for wall in self.wall_list:
                alien_hit_list = pygame.sprite.spritecollide(
                    wall, self.alien_list, True)
                for alien in alien_hit_list:
                    self.explosion.play()
                    self.wall_list.remove(wall)
                    self.all_sprites_list.remove(wall)
                    print("Alien Hit Wall")

            # Check to see if the game is over
            if len(self.alien_list) == 0:
                self.game_over = True
                Game.level_number += 1
コード例 #28
0
                    game_map[row][column] = 0

def get_key():
    while 1:
        event = pygame.event.poll()
        if event.type == pygame.KEYDOWN:
            return event.key
        else:
            pass
size=[600,800]
screen=pygame.display.set_mode(size)
pygame.display.set_caption("Centipede")

player=Player(300,700)
fire=Fire()
bomb=Bomb()
fireGroup=pygame.sprite.Group()
fireGroup.add(fire)
clock=pygame.time.Clock()
going=True
#Drawing background
background=pygame.Surface(size)
background.fill(bg)
screen.blit(background,(0,0))

allsprites=pygame.sprite.Group()
allsprites.add(player)
allsprites.add(fireGroup)
allsprites.add(bomb)

expos=pygame.sprite.Group()
コード例 #29
0
 def drop_bomb(self):
     if time.time() >= self.timers["bomb"] + self.cooldowns["bomb"]:
         new_bomb = Bomb.Bomb(self.cord_x, self.cord_y)
         self.bombs.append(new_bomb)
         self.timers["bomb"] = time.time()
コード例 #30
0
ファイル: TestFile.py プロジェクト: dsourile/GitProject
def main():
    if INTRO == 1:
        audio = vlc.MediaPlayer("Resources/Deathless.mp3")
        audio.play()
        image, box, letter = startScreen()
        time.sleep(1.25)
        image.undraw()
        box.undraw()
        letter.undraw()
        update()

    houses = []

    if INTRO == 1:
        for i in range(7):
            #house = House(random.randrange(15, 984), random.randrange(15, 634))
            house = House(200 + i*40, 400)
            house.drawHouse(win)
            houses.append(house)
            update()
            time.sleep(0.1)

        time.sleep(3)

        for i in range(7):
            house = House(random.randrange(15, 984), random.randrange(15, 634))
            house.drawHouse(win)
            houses.append(house)
            update()
            time.sleep(0.1)

    else:
        for i in range(100):
            house = House(random.randrange(15, 984), random.randrange(15, 634))
            house.drawHouse(win)
            houses.append(house)

    while True:                                 ##Animation loop
        for i in houses:
            dx = random.randrange(-20,21,5)
            dy = random.randrange(-20,21,5)
            i.house.move(dx, dy)
            northernWallDetection(i)
            southernWallDetection(i)
            easternWallDetection(i)
            westernWallDetection(i)
            i.centerX += dx
            i.centerY += dy

        update()
        time.sleep(0.01)
        click = win.checkMouse()
        #click = Point(500, 325)
        if click != None:
            break



    bomb = Bomb(click)
    bomb.drawBomb(win)
    update()
    bombAudio = vlc.MediaPlayer("Resources/Explosion.mp3")
    bombAudio.play()

    for i in houses:
        i.isItHit(bomb, click)

    update()

    gameOverExit(houses)

    showScore(bomb)

    audio.stop()

    win.getMouse()
    win.close()