前言
大家都看过彩带飘落吧?这个在比较喜庆的场合是很常见的:
还有“跑马灯”效果,听起来很陌生,其实很常见,下面的就是:
好了,相信大家都有了初步的认识。当然,如果有做前端或者搞设计的同学,上面的效果应该不难实现,那如果想通过Python呢?有没有包可以调用呢?
答案是有的——pygame
这个包适合用来开发游戏,今天就不打算给大家详细介绍了,还是想给大伙儿放松放松,以后有机会再多写写它。
不多说,直接甩出代码:
import pygame from random import randint, choice screen_length = 700 screen_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()
好了,来看看效果:
还不错吧,有没有感觉好玩呢?
当然,如果需要,代码直接拿去用,根据自己的想法去改就行!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。