Python random colors flickering on object -
the following function defines rectangles, x/y location, width , height, , color. color randomly chosen every time.
def things(thingx, thingy, thingw, thingh, color): rand_color = (random.randrange(0,255),random.randrange(0,255),random.randrange(0,255)) pygame.draw.rect(gamedisplay, rand_color, [thingx, thingy, thingw, thingh])
the current code causing program flicker through every different color. if change rand_color variation of choosing between black , white, rectangle flickers between black , white. what's happening here?
as said in comment, function generates different color each time it's called , flickering problem result of calling often. fix making rand_color
global , define value outside function before it's ever called.
however think idea in john rodger's answer of using class one, implement differently , try take advantage of object-oriented programming instead of reinventing whole wheel. below runnable example of mean. every time run it, generate randomly colored rectangle represent thing
object, , color not change or flicker display's updated.
import pygame, sys pygame.locals import * import random fps = 30 # frames per second black = (0, 0, 0) white = (255, 255, 255) class thing(pygame.rect): def __init__(self, *args, **kwargs): super(thing, self).__init__(*args, **kwargs) # init rect base class # define additional attributes self.color = tuple(random.randrange(0, 256) _ in range(3)) self.x_speed, self.y_speed = 5, 5 # how fast moves def draw(self, surface, width=0): pygame.draw.rect(surface, self.color, self, width) def main(): pygame.init() fpsclock = pygame.time.clock() pygame.key.set_repeat(250) # enable keyboard repeat held down keys gamedisplay = pygame.display.set_mode((500,400), 0,32) gamedisplay.fill(white) thingx,thingy, thingw,thingh = 200,150, 100,50 thing = thing(thingx, thingy, thingw, thingh) # create instance while true: # display update loop gamedisplay.fill(white) event in pygame.event.get(): if event.type == quit: pygame.quit() sys.exit() elif event.type == keydown: if event.key == k_down: thing.y += thing.y_speed elif event.key == k_up: thing.y -= thing.y_speed elif event.key == k_right: thing.x += thing.x_speed elif event.key == k_left: thing.x -= thing.x_speed thing.draw(gamedisplay) # display @ current position pygame.display.update() fpsclock.tick(fps) main()
Comments
Post a Comment