利用pygame開發一款遊戲:「跳跳兔」(九)

利用pygame開發一款遊戲:「跳跳兔」(九)

前言

在上一節中,咱們對「跳跳兔」進行了簡單的優化,而後爲遊戲中不一樣的狀態添加不一樣的音樂。python

這一節,爲遊戲添加道具與敵人,觸碰到道具,玩家能夠急速飛躍,觸碰到敵人,玩家將會死亡,遊戲結束git

添加道具

先整理一下添加道具其總體思路。github

  • 1.加載道具圖片
  • 2.加載觸發道具時的音效
  • 3.讓道具隨機出現到平臺上
  • 4.碰撞檢測 - 觸碰到道具後會有的效果

想要的效果,道具隨機出如今不一樣的平臺上,玩家觸碰到,會飛速向上飛躍。dom

一步步來實現。ide

首先構建一個新的類來表示這個道具。優化

# sprites.py

class Pow(pg.sprite.Sprite):
    def __init__(self, game, plat):
        self.groups = game.all_sprites, game.powerups
        pg.sprite.Sprite.__init__(self, self.groups)
        self.game = game # 整個遊戲對象
        self.plat = plat # 平臺對象
        self.type = random.choice(['boost'])
        # 加載道具圖片
        self.image = self.game.spritesheet.get_image(820, 1805, 71, 70)
        self.image.set_colorkey(BLACK)
        self.rect = self.image.get_rect()
        # 道具出如今平臺中間的上方
        self.rect.centerx = self.plat.rect.centerx
        self.rect.bottom = self.plat.rect.top - 5
複製代碼

代碼關鍵部分有相應的註釋,再也不詳細分析。spa

而後在平臺實例化時,隨機實例化道具對象。code

class Platform(pg.sprite.Sprite):
    def __init__(self, game, x, y):
        #... 省略無關代碼
        
        # 隨機在平臺上初始化道具
        if random.randrange(100) < POW_SPAWN_PCT:
            Pow(self.game, self)
複製代碼

這樣,道具實例化就完成了。orm

接着添加音效。cdn

def load_data(self): # 加載數據
        # ... 省略無關代碼
        
        # 加載音樂
        self.snd_dir = os.path.join(self.dir, 'snd')
        # 跳躍時音效
        self.jump_sound = pg.mixer.Sound(os.path.join(self.snd_dir, 'Jump33.wav'))
        # 使用道具時音效
        self.boost_sound = pg.mixer.Sound(os.path.join(self.snd_dir, 'Boost16.wav'))
複製代碼

至此,只剩道具碰撞檢測邏輯未完成了。來搞一搞

# main.py/Game

    def update(self):
        # ... 省略無關代碼
        # 碰撞檢測 - 玩家碰撞到急速飛躍道具
        pow_hits = pg.sprite.spritecollide(self.player, self.powerups, True)
        for pow in pow_hits:
            # 道具類型 - 不一樣道具能夠實現不一樣的效果
            if pow.type == 'boost':
                self.boost_sound.play() # 播放相應的音效
                self.player.vel.y = -BOOST_POWER # 快遞移動的距離
                self.player.jumping = False # 此時不爲跳躍狀態
複製代碼

此時若是直接運行,會發現,玩家移動時,道具也會同步移動,緣由是這部分代碼。

# main.py/Game

    def update(self):
        # 調用全部元素的update()方法
        self.all_sprites.update()
        
        # ... 省略無關代碼
        
        # 玩家到達遊戲框 1/4 處時(注意,遊戲框,頭部爲0,底部爲遊戲框長度,到到遊戲框的1/4處,表示已經到達了頂部一部分了)
        if self.player.rect.top <= HEIGHT / 4:
            # 玩家位置移動(往下移動)
            self.player.pos.y += abs(self.player.vel.y)
            # 平臺在遊戲框外時,將其註銷,避免資源浪費
            for plat in self.platforms:
                # 平臺移動位置(往下移動,移動的距離與玩家相同,這樣玩家才能依舊站立在本來的平臺上)
                plat.rect.y += abs(self.player.vel.y)
                if plat.rect.top >= HEIGHT: 
                    plat.kill()
                    # 分數增長 - 平臺銷燬,分數相加
                    self.score += 10
複製代碼

此時爲了不道具同步移動,在Pow類中建立update()方法,實現以下邏輯。

# 道具對象
class Pow(pg.sprite.Sprite):
    def __init__(self, game, plat):
        # ... 省略無關代碼

    def update(self):
        # 更新時,避免道具一同移動
        self.rect.bottom = self.plat.rect.top - 5
        # 若是道具對應的平臺已經被消除,那麼道具也要被消除
        if not self.game.platforms.has(self.plat):
            self.kill() # 消除道具
複製代碼

最終效果以下。

添加敵人

在實現前,依舊先整理一下實現的總體邏輯。

  • 1.構建敵人類
  • 2.敵人移動效果
  • 3.敵人隨機出現效果
  • 4.敵人碰撞檢測
  • 5.敵人不與跳跳兔同步移動

首先來構建敵人類,代碼以下。

# sprites.py

class Mob(pg.sprite.Sprite):
    def __init__(self, game):
        self.groups = game.all_sprites, game.mobs
        pg.sprite.Sprite.__init__(self, self.groups)
        self.game = game
        # 加載不一樣狀態的圖片
        self.image_up = self.game.spritesheet.get_image(566, 510, 122, 139)
        self.image_up.set_colorkey(BLACK)
        self.image_down = self.game.spritesheet.get_image(568, 1534, 122, 135)
        self.image_down.set_colorkey(BLACK)
        self.image = self.image_up # 默認爲向上的圖片
        self.rect = self.image.get_rect()
        # x軸中心位置隨機選擇
        self.rect.centerx = random.choice([-100, WIDTH + 100])
        # 隨機x軸速度
        self.vx = random.randrange(1, 4)
        if self.rect.centerx > WIDTH:
            self.vx *= -1
        # 隨機敵人y軸位置
        self.rect.y = random.randrange(HEIGHT / 2)
        self.vy = 0 # y軸速度默認爲0
        self.dy = 0.5
複製代碼

__init__()方法中,爲敵人添加了不一樣狀態的兩種圖片並隨機敵人初始centerx、x軸速度與y軸位置。

接着實現敵人移動效果。

# sprites.py

class Mob(pg.sprite.Sprite):

    def __init__(self, game):
        # ... 省略
        
    def update(self):
        self.rect.x += self.vx # x軸位置移動
        self.vy += self.dy
        # 實現上下抖動移動的效果
        if self.vy > 3 or self.vy < -3: 
            self.dy *= -1
        center = self.rect.center
        # 上下移動方向不一樣,使用不一樣的圖片
        if self.dy < 0:
            self.image = self.image_up
        else:
            self.image = self.image_down
        self.rect = self.image.get_rect()
        self.rect.center = center
        # y軸具體的移動
        self.rect.y += self.vy
        # 超過屏幕範圍,刪除敵人
        if self.rect.left > WIDTH + 100 or self.rect.right < -100:
            self.kill()
複製代碼

看註釋就可明白代碼的含義,再也不詳細分析。

接着實現產生敵人與碰撞檢測相關邏輯,代碼以下。

# main.py/Game

    def new(self):
        self.score = 0
        # ... 省略無關代碼
        self.powerups = pg.sprite.Group() # 急速飛躍道具
        self.mobs = pg.sprite.Group() # 敵人對象
        # ... 省略無關代碼
        self.mob_timer = 0

    def update(self):
        self.all_sprites.update()
        # 產生敵人
        now = pg.time.get_ticks()
        # 經過時間間隔來判斷是否要產生敵人
        if now - self.mob_timer > 5000 + random.choice([-1000, -500, 0, 500, 1000]):
            self.mob_timer = now
            Mob(self)
        # 碰撞檢測 - 若是碰撞到了敵人,遊戲結束
        mob_hits = pg.sprite.spritecollide(self.player, self.mobs, False)
        if mob_hits:
            self.playing = False
複製代碼

經過時間間隔的形式隨機產生敵人,至於碰撞檢測...同樣的邏輯。

最後,爲了不敵人元素跟隨跳跳兔一同移動,須要添加以下邏輯。

def update(self):
        # 玩家到達遊戲框 1/4 處時(注意,遊戲框,頭部爲0,底部爲遊戲框長度,到到遊戲框的1/4處,表示已經到達了頂部一部分了)
        if self.player.rect.top <= HEIGHT / 4:
            # 玩家位置移動(往下移動)
            self.player.pos.y += abs(self.player.vel.y)
            # 平臺在遊戲框外時,將其註銷,避免資源浪費
            for plat in self.platforms:
                # 平臺移動位置(往下移動,移動的距離與玩家相同,這樣玩家才能依舊站立在本來的平臺上)
                plat.rect.y += abs(self.player.vel.y)
                if plat.rect.top >= HEIGHT: 
                    plat.kill()
                    # 分數增長 - 平臺銷燬,分數相加
                    self.score += 10
            # 敵人位置同步往下移動
            for mob in self.mobs:
                mob.rect.y += max(abs(self.player.vel.y), 2)
複製代碼

最終效果以下。

在本節中,咱們對「跳跳兔」作了道具與敵人的添加,增長了「跳跳兔遊戲的趣味性」。

由於考慮到篇幅,文中沒有給出完整的代碼,但爲了方便你們理解,我將相應的代碼上傳到了github,圖片資源與音樂資源也在github上。

github.com/ayuLiao/jum…

若是文章對你有幫助或你以爲有點意思,點擊「在看」支持做者一波。

相關文章
相關標籤/搜索