如何基于Python pygame實現動畫跑馬燈
前言
大家都看過彩帶飄落吧?這個在比較喜慶的場合是很常見的:
還有“跑馬燈”效果,聽起來很陌生,其實很常見,下面的就是:
好了,相信大家都有了初步的認識。當然,如果有做前端或者搞設計的同學,上面的效果應該不難實現,那如果想通過Python呢?有沒有包可以調用呢?
答案是有的——pygame
這個包適合用來開發游戲,今天就不打算給大家詳細介紹了,還是想給大伙兒放松放松,以后有機會再多寫寫它。
不多說,直接甩出代碼:
import pygamefrom random import randint, choicescreen_length = 700screen_width = 500# 模擬彩帶飄落的類,掉落的詞作為彩帶class Word_drop(pygame.sprite.Sprite): # 設置屬性:包括字體、下落速度、彩帶來源、彩帶框的屬性 def __init__(self): pygame.sprite.Sprite.__init__(self) self.font = pygame.font.SysFont(name=’幼圓’, size=10, bold=True, italic=True) self.speed = randint(15, 30) self.word = self.getWord() self.image = self.font.render(self.word, True, (randint(0, 255), randint(0, 255), randint(0, 255))) self.image = pygame.transform.rotate(self.image, randint(87, 93)) self.rect = self.image.get_rect() self.rect.topleft = (randint(0, screen_length), -20) # 獲取掉落的詞 def getWord(self): length = randint(1, 8) word = ’’ for i in range(length): word += choice(’qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM’) return word # 設置彩帶更新的條件 def update(self, *args): self.rect = self.rect.move(0, self.speed) if self.rect.top > screen_length: self.kill()# 實現'跑馬燈'效果的函數def word_translate(jx, ztw1, ztw2, screen_length, text): max_ztw = max(ztw1, ztw2) jx.x -= 5 if jx.x < 0 - max_ztw: jx.x = (screen_length + 10) screen.blit(text, [jx.x, jx.y])if __name__ == ’__main__’: # 初始化工作 pygame.init() pygame.font.init() # 渲染字體,兩行字 a = pygame.font.SysFont(name=’幼圓’, size=50, bold=True, italic=True) word1 = ' 中國' text1 = a.render(word1, True, (255, 0, 0), (0, 0, 0)) word2 = '我超級愛你' text2 = a.render(word2, True, (255, 0, 0), (0, 0, 0)) # '跑馬場'字體框的屬性 _, _, ztw1, zth1 = text1.get_rect() jx1 = pygame.Rect(screen_length, (screen_width / 2 - zth1), ztw1, zth1) _, _, ztw2, zth2 = text2.get_rect() jx2 = pygame.Rect(screen_length, (screen_width / 2), ztw2, zth2) # 其他相關設置 screen = pygame.display.set_mode((screen_length, screen_width)) clock = pygame.time.Clock() wordGroup = pygame.sprite.Group() while True: clock.tick(30) screen.fill((0, 0, 0)) # 設置退出的條件 for event in pygame.event.get(): if event.type == pygame.QUIT:pygame.quit()exit(0) # 彩帶飄落 word_object = Word_drop() wordGroup.add(word_object) wordGroup.update() wordGroup.draw(screen) # '跑馬場' word_translate(jx1, ztw1, ztw2, screen_length, text1) word_translate(jx2, ztw1, ztw2, screen_length, text2) pygame.display.update()
好了,來看看效果:
還不錯吧,有沒有感覺好玩呢?
當然,如果需要,代碼直接拿去用,根據自己的想法去改就行!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: