如何使用pygame创建一个闪烁或发光按钮

时间:2013-12-05 06:54:30

标签: python python-2.7 pygame python-3.3

我是pygame的新手,我想知道如何制作一个矩形对象,该对象在有或没有mousebutton事件时闪烁或发光。 提前谢谢!

1 个答案:

答案 0 :(得分:0)

我鞭打了这个:

from pygame.locals import *
import pygame
import os
import sys


pygame.init()

CAPTION = "TEST"

class Game():
    def __init__(self):
        #window setup
        pygame.display.set_caption(CAPTION)
        os.environ["SDL_VIDEO_CENTERED"] = "True"
        self.fps = 60.0

        self.clock = pygame.time.Clock()
        self.last_tick = pygame.time.get_ticks()
        self.screen_res = [200, 200]

        self.screen = pygame.display.set_mode(self.screen_res,pygame.HWSURFACE)

        self.rect = pygame.Surface((100, 100))
        self.rect.fill((250, 0,0))

        self.alpha = 1
        self.a_change = True
        #Tweak this to change speed
        self.blink_spd = 0.1

        #start loop
        self.clock.tick(self.fps)
        while 1:
            self.Loop()

    def Loop(self):
        # main game loop
        self.eventLoop()

        self.last_tick = pygame.time.get_ticks()

        self.screen.fill((0,0,0))
        #Check if alpha is going up
        if self.a_change:
            self.alpha += self.blink_spd
            if self.alpha >= 175:#if all the way up go down
                self.a_change = False
        #Check if alpha is going down        
        elif self.a_change == False:
            self.alpha += -self.blink_spd
            if self.alpha <= 30: #if all the way down go up
                self.a_change = True

        self.rect.set_alpha(self.alpha)
        self.screen.blit(self.rect,(50,50))

        pygame.display.update()


    def eventLoop(self):
        # the main event loop, detects keypresses
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

Game()

使用pygame.Surface.set_alpha()更改透明度,您可以调整数字以获得不同的速度等等

你可以用图像替换Surface,因为图像也是表面

希望这有帮助!祝你好运:)