def change_size(self, new_width): """ Function used to change the size of the palette. Rebuilds image from source and generates new collision Rect :param new_width: new Paddle width in pixels (min. 22px) :return: """ paddleAsset = Assets.paddles[self.paddle_color] new_width = max(new_width, 22) # 22 = (border(8) + colorbar(3))*2 paddle_mid = Surface((38, 15)) # (2*paddle.rect.width, paddle.rect.height)) # paddle_mid.blit(self.image, (0, 0), Rect(11, 0, 38, 15)) paddle_mid.blit(paddleAsset, (0, 0), Rect(11, 0, 38, 15)) paddle_mid = transform.scale(paddle_mid, (new_width-22, self.rect.height)) new_paddle = Surface((new_width, self.rect.height), SRCALPHA) # blank surface # new_paddle.fill(pygame.Color(0, 0, 0, 0), new_paddle.get_rect()) new_paddle.blit(paddle_mid, (11, 0)) new_paddle.blit(paddleAsset, (0, 0), Rect(0, 0, 11, 15)) new_paddle.blit(paddleAsset, (new_width - 11, 0), Rect(paddleAsset.get_rect().width - 11, 0, 11, 15)) paddle_new_x = self.rect.x + self.rect.width/2 - new_paddle.get_rect().width/2 self.rect = Rect(paddle_new_x, self.rect.y, new_paddle.get_rect().width, new_paddle.get_rect().height) self.mask = mask.from_surface(new_paddle) self.image = new_paddle self.attachment_points[1] = (self.rect.width-8, 0) # self.paddle.attachment_points[1] = if self.rect.x <= PLAYFIELD_PADDING[0]: self.rect.x = PLAYFIELD_PADDING[0] + 1 elif self.rect.x + self.rect.width >= LEVEL_WIDTH - PLAYFIELD_PADDING[0]: self.rect.x = LEVEL_WIDTH - PLAYFIELD_PADDING[0] - self.rect.width - 1
class Enemy(Sprite): width = 40 height = 40 y = -40 def __init__(self): self.x = randrange(0,scrWidth-self.width) Sprite.__init__(self) #Self.rect and self.image self.rect = Rect((self.x,self.y),(self.width,self.height)) self.image = Surface(self.rect.size) self.image.fill((0,0,0)) self.image.set_colorkey((0,0,0)) #Draw stuff pygame.draw.ellipse(self.image,red,self.image.get_rect()) pygame.draw.ellipse(self.image,blue2,self.image.get_rect(),15) #Randomly picking trajectory self.down = randrange(1,5) self.side = randrange(-6,6,4) def update(self): "Movement behavior" self.rect.y += self.down self.rect.x += self.side if self.rect.right > scrWidth or self.rect.left < 0: self.side *=-1 if self.rect.top > scrHeight: self.kill()
class Player(Sprite): def __init__(self, bounds): Sprite.__init__(self) self.bounds = bounds self.image = Surface((80, 80)) self.rect = self.image.get_rect() self.image.fill((0,0,0)) self.image.fill(PLAYER_COLOR, self.rect.inflate(-4,-4)) self.x, self.y = bounds.center self.vx = PLAYER_SPEED self.vy = PLAYER_SPEED def update(self, dt): dt = dt / 1000.0 keys = pygame.key.get_pressed() if keys[K_UP]: self.y -= self.vy * dt if keys[K_DOWN]: self.y += self.vy * dt if keys[K_LEFT]: self.x -= self.vx * dt if keys[K_RIGHT]: self.x += self.vx * dt # update player self.rect = self.image.get_rect() self.rect.center = int(self.x), int(self.y) self.rect.clamp_ip(self.bounds)
class Shield(Sprite): color = 255,255,255 transparent = 0,0,0 size = 120,120 kind = "null" def __init__(self, parent, kind): self.parent=parent Sprite.__init__(self) self.kind = kind self.hiss_sfx = load_sfx("hiss") if kind == "baseball": self.color = 0,90,90 elif kind == "cigar": self.color = 255,100,0 elif kind == "health": self.color = 180, 200, 180 self.image = Surface(self.size) self.rect = self.image.get_rect() self.rect.center = self.parent.rect.center self.image.fill(self.transparent) self.image.set_colorkey(self.transparent) pygame.draw.ellipse(self.image, (self.color), self.image.get_rect()) pygame.draw.ellipse(self.image, self.transparent, self.image.get_rect().inflate(-10, -10)) #pygame.draw.ellispe(self.image, (30,255,30), self.rect.center, ((self.rect.width)/2)) def update(self): if not self.parent.alive(): self.kill() self.rect.center = self.parent.rect.center
def __init__(self, parentSurface:Surface, rect:pygame.Rect, filmstrip:Surface, borderColor:tuple): Widget.__init__(self, parentSurface, rect, borderColor, None) self.images = [] self.numImages = int(filmstrip.get_rect().height / filmstrip.get_rect().width) self.currentImage = 0 clipRect = pygame.Rect(0, 0, rect.width, rect.height) for x in range(0, self.numImages): self.images.append(filmstrip.subsurface(clipRect)) clipRect.move_ip(0, rect.height) self.draw()
class Enemy2(Sprite): y = -50 health = 3 width = height = 50 def __init__(self): Sprite.__init__(self) self.x = randrange(0,scrWidth-self.width) self.rect = Rect((self.x,self.y),(self.width,self.height)) self.image = Surface(self.rect.size) self.image.fill((0,0,0)) self.image.set_colorkey((0,0,0)) pygame.draw.ellipse(self.image,yellow,self.image.get_rect()) self.down = 2 self.side = randrange(-1,1,2) self.bombSplode = False def update(self): self.rect.x+=self.side self.rect.y+=self.down if self.rect.right > scrWidth or self.rect.left < 0: self.side *=-1 if self.rect.top > scrHeight: self.kill if self.health<3: pygame.draw.ellipse(self.image,bOrange,self.image.get_rect(),15) if self.health<2: pygame.draw.ellipse(self.image,(0,0,0),self.image.get_rect(),15) if self.bombSplode: count = 3 while count >0: pygame.draw.ellipse(self.image,(bORange),self.image.get_rect(),15) self.kill check = randrange(0,100) if check<3: eBulletGroup.add(bulletEnemy(self)) def damage(self): self.health-=1 if self.health == 0: check = randrange(0,100) pygame.draw.ellipse(self.image,bOrange,self.image.get_rect(),15) self.kill() if check <=10: bombGroup.add(Bomb(self))
class Player (Sprite): size = 20,20 color = 255,255,0 shottimer = 0 def __init__(self, loc, bounds): Sprite.__init__(self) # required for sprites self.image = Surface(self.size) self.rect = self.image.get_rect() self.rect.center = loc self.bounds = bounds # passes the bounds to the object so it can be saved. self.image.fill(self.color) self.bullets = Group() def update(self): if self.shottimer > 0: self.shottimer -= 1 self.rect.center = pygame.mouse.get_pos() self.rect.clamp_ip(self.bounds) #makes sure it doesn't go outside the provided rectangle def shoot(self): if not self.alive(): #return just stops everything in hte function return if self.shottimer == 0: bullet = Bullet(self.bounds) self.bullets.add(bullet) #adds the new bullet to the Bullets list bullet.rect.midbottom = self.rect.midtop self.shottimer = 10
def draw(surface:pygame.Surface, color:tuple, width:int=1): rect = surface.get_rect() pointlist = [(rect.left, rect.top), (rect.right - 1, rect.top), (rect.right - 1, rect.bottom - 1), (rect.left, rect.bottom - 1)] pygame.draw.lines(surface, color, True, pointlist, width)
def get_image(self): """Draw the rectange on a transparent surface.""" img = Surface(self.rect.size).convert_alpha() img.fill((0, 0, 0, 0), special_flags=pg.BLEND_RGBA_MULT) draw.rect(img, self.model.color, img.get_rect(), 1) img.fill((255, 255, 255, 128), special_flags=pg.BLEND_RGBA_MULT) return img
class Robot(Sprite): color = 255,255,0 size = 10,10 health = 1 weight = 2 iscarried = False childshield = 0; def __init__(self,loc,bounds): Sprite.__init__(self) self.image = Surface(self.size) self.rect = self.image.get_rect() self.rect.bottomleft = loc self.image.fill(self.color) self.makeshield() # def update(self): def makeshield(self): return def update(self): keys = pygame.key.get_pressed() self.rect.clamp_ip(self.bounds) def damage (self, source): if not self.immunitycheck(source): self.health -= 1 print "robot hit" if self.health <= 0: print "Robot killed" # Player.drop() Ask Alec self.kill() def immunitycheck(self, source): return False
def __init__(self, tag, initial_position, rotation=0, fontname=DEFAULT_FONT, fontzoom=5): Sprite.__init__(self) self.tag = copy(tag) self.rotation = rotation font_spec = load_font(fontname) #fonter = font.Font(os.path.join(FONT_DIR, font_spec['ttf']), int(tag['size'] * fontzoom)).render(tag['tag'], True, tag['color']) # changing to allow for arbitrary local fonts fonter = font.Font(font_spec['ttf'], int(tag['size'] * fontzoom)).render(tag['tag'], True, tag['color']) self.tag['size'] *= fontzoom fonter = transform.rotate(fonter, rotation) frect = fonter.get_bounding_rect() frect.x = -frect.x frect.y = -frect.y self.fontoffset = (-frect.x, -frect.y) font_sf = Surface((frect.width, frect.height), pygame.SRCALPHA, 32) font_sf.blit(fonter, frect) self.image = font_sf self.rect = font_sf.get_rect() self.rect.width += TAG_PADDING self.rect.height += TAG_PADDING self.rect.x = initial_position[0] self.rect.y = initial_position[1] self.mask = mask.from_surface(self.image) self.mask = self.mask.convolve(CONVMASK, None, (TAG_PADDING, TAG_PADDING))
class Cell(Sprite): def __init__(self, rank, file, piece: Optional[Surface] = None): super(Cell, self).__init__() self.rank = rank self.file = file self.piece = piece self.color = MEDIUM_WOOD if (RANK_NAMES.index( self.rank) + FILE_NAMES.index(self.file)) % 2 == 0 else WHITE self.image = Surface(CELL_SIZE) self.image.fill(self.color) self.rect = self.image.get_rect() self.rect.x = FILE_NAMES.index(self.file) * CELL_W self.rect.y = list(reversed(RANK_NAMES)).index(self.rank) * CELL_H self.selected = False def update(self, *args, **kwargs): if self.selected: self.image.fill(LIGHT_SEA_GREEN) else: self.image.fill(self.color) if self.piece: Surface.blit(self.image, self.piece, dest=(0, 0)) def __str__(self): return self.file + self.rank
class Enemy (Sprite): size = 50, 30 color = 255,0,0 vx, vy = 6,6 spawntime = 30 spawnticker = 0 def __init__(self,loc, bounds): Sprite.__init__(self) self.image = Surface(self.size) self.rect = self.image.get_rect() self.rect.bottomleft = loc self.image.fill(self.color) self.bounds = bounds self.vx = randrange(-6,6) self.vy = randrange(3,6) def update(self): self.rect.x += self.vx self.rect.y += self.vy #spawn #bounce off side if self.rect.right > self.bounds.right or self.rect.left < self.bounds.left: self.vx *= -1 #kill if out of bounds if self.rect.top > self.bounds.bottom: self.kill()
def blit_info(self): textcolor = (255, 255, 255) font = pygame.font.Font(None, 30) width = (WIDTH-(MATRIS_OFFSET+BLOCKSIZE*MATRIX_WIDTH+BORDERWIDTH*2)) - MATRIS_OFFSET*2 def renderpair(text, val): text = font.render(text, True, textcolor) val = font.render(str(val), True, textcolor) surf = Surface((width, text.get_rect().height + BORDERWIDTH*2), pygame.SRCALPHA, 32) surf.blit(text, text.get_rect(top=BORDERWIDTH+10, left=BORDERWIDTH+10)) surf.blit(val, val.get_rect(top=BORDERWIDTH+10, right=width-(BORDERWIDTH+10))) return surf scoresurf = renderpair("Score", self.matris.score) levelsurf = renderpair("Level", self.matris.level) linessurf = renderpair("Lines", self.matris.lines) combosurf = renderpair("Combo", "x{}".format(self.matris.combo)) height = 20 + (levelsurf.get_rect().height + scoresurf.get_rect().height + linessurf.get_rect().height + combosurf.get_rect().height ) area = Surface((width, height)) area.fill(BORDERCOLOR) area.fill(BGCOLOR, Rect(BORDERWIDTH, BORDERWIDTH, width-BORDERWIDTH*2, height-BORDERWIDTH*2)) area.blit(levelsurf, (0,0)) area.blit(scoresurf, (0, levelsurf.get_rect().height)) area.blit(linessurf, (0, levelsurf.get_rect().height + scoresurf.get_rect().height)) area.blit(combosurf, (0, levelsurf.get_rect().height + scoresurf.get_rect().height + linessurf.get_rect().height)) screen.blit(area, area.get_rect(bottom=HEIGHT-MATRIS_OFFSET, centerx=TRICKY_CENTERX))
class LevelEditorDisplayer: activeLevel = None def __init__(self, bgMangr, musicMangr): self.isDone = 0 self.replacementDisplayerClass= None self.levelDisplayer = None self.bgMangr = bgMangr self.dragging = 0 if self.activeLevel != None: self.levelDisplayer = self.activeLevel events.AddListener( self ) screen = self.bgMangr.screen self.edInterface = EditorInterface( screen ) fauxWidth = screen.get_width() fauxHeight = screen.get_height() - self.edInterface.editPanel.rect.height self.fauxScreen = Surface( (fauxWidth, fauxHeight) ) self.fauxBgMangr = SeamedBackgroundManager(self.fauxScreen) self.levelDisplayer.bgMangr = self.fauxBgMangr self.edInterface.SetLevel( self.levelDisplayer ) self.edInterface.SetBackgroundManager( self.bgMangr ) #---------------------------------------------------------------------- def SignalKey( self, event, upKeys ): #TODO: is this ever called?? self.levelDisplayer.SignalKey( event, upKeys ) self.edInterface.Key(event) #---------------------------------------------------------------------- def MouseDown( self, pos ): self.edInterface.MouseDown( pos ) #---------------------------------------------------------------------- def MouseUp( self, pos ): self.edInterface.MouseUp( pos ) #---------------------------------------------------------------------- def MouseOver( self, event ): self.edInterface.MouseOver( event ) #---------------------------------------------------------------------- def DoGraphics( self, screen, display, timeChange ): if not self.edInterface.levelPaused: self.levelDisplayer.triggerGroup.clear(screen) self.levelDisplayer.DoGraphics( self.fauxScreen, pygame.display, timeChange ) changedRects = self.levelDisplayer.triggerGroup.draw( self.fauxScreen ) pygame.display.update( changedRects ) screen.blit( self.fauxScreen, self.fauxScreen.get_rect() ) self.edInterface.DoGraphics(screen, pygame.display, timeChange) screen.blit( self.edInterface.editPanel.image, self.edInterface.editPanel.rect ) pygame.display.flip()
def __init__(self, surface: pg.Surface): super().__init__(surface) self.field = Field( # "800000503501007000700308210680073000009005000300004805970500680063789000150040007" # "000000000904607000076804100309701080008000300050308702007502610000403208000000000" # "000001030231090000065003100678924300103050006000136700009360570006019843300000000" # "016007803090800000870001260048000300650009082039000650060900020080002936924600510" # "100000569492056108056109240009640801064010000218035604040500016905061402621000005" "100400006046091080005020000000500109090000050402009000000010900080930560500008004" ) self.font = pg.font.SysFont("Vera", 42) self.blocks = [] self.cells = [] self.debugs = [] self._idx = 0 total_size = surface.get_rect() board_size = min(total_size.width * 2 // 3, total_size.height) board_top_space = total_size.height - board_size self._board = pg.Rect(0, board_top_space, board_size, board_size) print(total_size) self.board_surface = surface.subsurface(self._board.inflate(-20, -20)) block_size = (board_size - 20) // 3 cell_size = (block_size - 6) // 3 for x in range(3): for y in range(3): if y == 0: for i in range(3): cellsurface = surface.subsurface( pg.Rect( block_size * x + cell_size * i + 13, block_size * y + board_top_space - cell_size // 2 + 10, cell_size, cell_size // 2, )) self.cells.append( Text(text=f"x: {3*x+i+1}", surface=cellsurface)) for i in range(3): rect = pg.Rect( board_size - 10, board_top_space + 13 + cell_size * i + block_size * x, cell_size // 2, cell_size, ) print(rect) cellsurface = surface.subsurface(rect) self.cells.append( Text(text=f"{3*x+i+1}", surface=cellsurface)) blockrect = pg.Rect(block_size * x, block_size * y, block_size, block_size) blocksurface = self.board_surface.subsurface(blockrect) self.blocks.append(Block(blocksurface, x, y, self.field)) self.debugs.append( Text( text=f"x: , y: ", surface=surface.subsurface(pg.Rect(0, 0, 200, 50)), ))
class Renderable: def __init__(self, siz, posx, posy, color): self.image = Surface(siz) self.image.fill(color) self.rect = self.image.get_rect() self.rect.x = posx self.rect.y = posy @property def x(self): return self.rect.x @x.setter def x(self, val): self.rect.x = val @property def y(self): return self.rect.y @y.setter def y(self, val): self.rect.y = val @property def w(self): return self.rect.right - self.rect.left @property def h(self): return self.rect.bottom - self.rect.top
class Player(Sprite): color = 255, 255, 0 size = 20, 20 def __init__(self, loc, bounds): Sprite.__init__(self) self.image = Surface(self.size) self.rect = self.image.get_rect() self.rect.center = loc self.bounds = bounds self.image.fill(self.color) self.bullets = Group() def update(self): self.rect.center = pygame.mouse.get_pos() self.rect.clamp_ip(self.bounds) def shoot(self): if not self.alive(): return bullet = Bullet(self.bounds) bullet.rect.midbottom = self.rect.midtop self.bullets.add(bullet)
def render(self, text): """ Renders the text using the options first used. """ lines = text.splitlines() img = Surface(self._calculate_image_size(self.font, self.text, self.size, self.line_spacer, self.layers)) if self.bg_transparent: img.set_colorkey(self.background) full_rect = img.get_rect() y = 0 for l in lines: r = self.font.render(l, self.size, self.background, self.bg_transparent, self.layers) r_rect = r.get_rect() if self.bg_transparent: r.set_colorkey(self.background) if self.align == self.A_CENTER: x = self._center_rect_inside_rect(r_rect, full_rect) elif self.align == self.A_LEFT: x = 0 elif self.align == self.A_RIGHT: x = full_rect[3] - r_rect[3] img.blit(r, (x, y)) y += self.line_spacer + r_rect[3] return img
class RoboImages(Sprite): color = 0,0,0 size = 60,60 def __init__(self, parent): Sprite.__init__(self) self.parent = parent self.name = parent.name if parent.name == "baby": self.size = 40,40 self.color = parent.color self.image = Surface(self.size) self.rect = self.image.get_rect() self.rect.centerx = self.parent.rect.centerx self.rect.centery = self.parent.rect.centery self.dir = dir try: self.image = load_image(self.name+'bot') print "found family sprite" except: self.image.fill(self.color) print "failed to load family image" self.image = pygame.transform.scale(self.image, self.size) self.image.set_colorkey((255,255,255)) def update(self): self.rect.center = self.parent.rect.center if not self.parent.alive(): self.kill()
class Enemy(Sprite): size = width,height = 50,50 color = 255,0,0 vx, vy = 6,6 def __init__(self,loc,bounds): Sprite.__init__(self) self.image = Surface(self.size) self.rect = self.image.get_rect() self.bounds = bounds self.image.fill(self.color) self.rect.bottomleft = loc self.vx = randrange(4,8) direction = 2 * randrange(2)- 1 self.vx *= direction def update(self): self.rect.x += self.vx self.rect.y += self.vy if self.rect.left < self.bounds.left or self.rect.right > self.bounds.right: self.rect.x -= 2 * self.vx self.vx = -self.vx if self.rect.top > self.bounds.bottom: self.kill()
def reset_screen(img_file=None, color=BACKGROUND_COLOR): # Test display if not pyg.display.get_init(): pyg.init() # Init screen flag = pyg.FULLSCREEN #| pyg.DOUBLEBUF | pyg.HWSURFACE flag *= Constants.FULLSCREEN flag |= pyg.NOFRAME * NOFRAME screen = pyg.display.set_mode(WINDOW_SIZE, flag) ico = load_image(ICON_FILE).convert_alpha() pyg.display.set_icon(ico) pyg.display.set_caption(WINDOW_TITLE) # Build background background = Surface(WINDOW_SIZE) background.fill(color) # Get background if isinstance(img_file, basestring): image = load_image(img_file).convert_alpha() width = int(WINDOW_WIDTH * REDUCE_FACTOR) height = int(WINDOW_HEIGHT *REDUCE_FACTOR) image = pyg.transform.smoothscale(image, (width,height)) center = WINDOW_WIDTH/2, WINDOW_HEIGHT/2 background.blit(image, image.get_rect(center=center)) # Apply background screen.blit(background, background.get_rect()) pyg.display.flip() # Return screen return screen, background
class Player(Sprite): color = 255,25,69 size = 20,20 def __init__(self, loc, bounds): Sprite.__init__(self) #makes player a sprite object self.image = Surface(self.size) self.rect = self.image.get_rect() self.rect.center = loc self.bounds = bounds self.image.fill(self.color) self.bullets = Group() def update(self): self.rect.center = pygame.mouse.get_pos() #player moves/stays with mouse self.rect.clamp_ip(self.bounds) #cant leave screen bounds def shoot(self): if not self.alive(): return #stop doing anything in this function bullet = Bullet(self.bounds) bullet.rect.midbottom = self.rect.midtop self.bullets.add(bullet)
class Impact(Meteor): size = (100,100) COLOR = 0,140,0 duration = 5 def __init__(self,loc, bounds, duration, kind): #print "explosion!" # Ice should have moving impacts Sprite.__init__(self) self.image = Surface(self.size) self.rect = self.image.get_rect() self.rect.center = loc self.image.fill(self.COLOR) self.bounds = bounds self.duration = duration self.kind = kind if kind == "rock": self.duration = 10 def update(self): self.duration -= 1 if self.duration <= 0: self.coord_x, self.coord_y = self.rect.center self.kill() #def collision(self, robot): def kill (self): Sprite.kill(self)
class Player(Sprite): color = 255, 255, 0 size = 20, 20 def __init__(self, loc, bounds): Sprite.__init__(self) self.image = Surface(self.size) self.rect = self.image.get_rect() self.rect.center = loc self.bounds = bounds self.image.fill(self.color) self.bullets = Group() def update(self): self.rect.center = pygame.mouse.get_pos() self.rect.clamp_ip(self.bounds) def shoot(self): if not self.alive(): return bullet = Bullet(self.bounds) bullet.rect.midbottom = self.rect.midtop self.bullets.add(bullet)
class Impact(Meteor): size = (100,100) COLOR = 0,140,0 duration = 5 dir = 0 damage = 10 def __init__(self,loc, bounds, duration, kind, dir = 0): #print "explosion!" self.dir = dir # Ice should have moving impacts Sprite.__init__(self) self.image = Surface(self.size) self.rect = self.image.get_rect() self.rect.center = loc self.image.fill(self.COLOR) self.bounds = bounds self.duration = duration self.kind = kind self.get_sprite() self.get_sound() self.impact_sfx.stop() self.impact_sfx.play() def get_sprite(self): #return #-----------This will attempt to load an image, and fill if it fails. try: self.image = load_image('explosion_'+self.kind) print "impact explosion yay" except: self.image.fill(self.COLOR) print "failed to find explosion" #Scale the image to the proper size and add random rotation #if randint(0,2) == 0: # self.image = pygame.transform.flip(self.image, True, False) #self.image = pygame.transform.rotate(self.image, randint(-360,360)) self.image = pygame.transform.scale(self.image, self.size) #temp #Anything that's pure white will be transparent self.image.set_colorkey((255,255,255)) #------- def get_sound(self): self.impact_sfx = load_sfx("stockmeteorhit") def update(self): self.duration -= 1 if self.duration <= 0: self.coord_x, self.coord_y = self.rect.center self.kill() #def collision(self, robot): def kill (self): Sprite.kill(self)
class Meteor (Sprite): coord_x = 0 coord_y = 0 size = (1,1) falltime = 60 COLOR = 255,0,0 def __init__(self,loc, bounds, falltime): Sprite.__init__(self) self.image = Surface(self.size) self.rect = self.image.get_rect() self.rect.bottomleft = loc self.image.fill(self.color) self.bounds = bounds self.falltime = falltime def update(): self.falltime -= 1 if falltime <= 0: self.coord_x, self.coord_y = self.rect.center self.impact() self.kill() def impact(): #self.explode = Surface(self.size) print "impact!"
class Sprite(DirtySprite): """The base sprite class that all sprites inherit.""" def __init__(self, scene, size, color): DirtySprite.__init__(self) self.scene = scene self.image = Surface(size).convert_alpha() self.image.fill(color) self.rect = self.image.get_rect() self.x, self.y = 0, 0 self.facing = [0,2] def move(self): """Move the sprite and set it to dirty for the current frame.""" self.dirty = 1 self.rect.move_ip([self.x, self.y]) def update(self): """Update the sprite each frame.""" if (self.x or self.y): self.facing = [self.x, self.y] self.move() self.collide()
class Enemy(Sprite): size = w,h = 40,40 color = 255,0,0 dx,dy = 4,2 score = 1 def __init__(self, game, pos=None): Sprite.__init__(self) self.game = game self.image = Surface(self.size).convert_alpha() self.rect = self.image.get_rect() pygame.draw.ellipse(self.image,self.color,self.rect) if pos is None: pos = randrange(self.game.w - self.w), -self.h self.rect.topleft = pos self.dx = self.dx if randrange(2) else -self.dx def update(self): self.rect.move_ip(self.dx, self.dy) self.rect = self.rect.clamp(self.game.bounds) if self.rect.left == 0 or self.rect.right == self.game.bounds.right: self.dx = -self.dx if self.rect.bottom == self.game.bounds.bottom: self.kill() if self.game.player.alive(): self.game.score -= self.score print self.game.score
class LayoutPanel(BaseWidget): curr_idx = 0 def __init__(self): super().__init__() self.image = Surface((ANCHO, ALTO)) self.image.fill(COLOR_SELECTED) self.rect = self.image.get_rect() self.show() Systems.init() self.panels = [] for panel in panels: self.panels.append(panel(self)) self.current = self.panels[self.curr_idx] self.current.show() a = Arrow(self, 'backward', 180, self.rect.left + 16, self.rect.bottom) b = Arrow(self, 'forward', 0, self.rect.right - 16, self.rect.bottom) e = NewButton(self, (self.rect.w // 5) * 1, self.rect.bottom - 26) d = LoadButton(self, (self.rect.w // 5) * 2, self.rect.bottom - 26) c = SaveButton(self, (self.rect.w // 5) * 3, self.rect.bottom - 26) g = ClearButton(self, (self.rect.w // 5) * 4, self.rect.bottom - 26) SwapSystem(self, ANCHO - 200, 2) Renderer.add_widget(a) Renderer.add_widget(b) Renderer.add_widget(c) Renderer.add_widget(d) Renderer.add_widget(e) Renderer.add_widget(g) WidgetHandler.add_widget(c) WidgetHandler.add_widget(d) WidgetHandler.add_widget(e) WidgetHandler.add_widget(g) self.load_button = d def cycle(self, delta): if 0 <= self.curr_idx + delta < len(self.panels): self.current.hide() self.curr_idx += delta self.current = self.panels[self.curr_idx] if self.current.skippable is True and self.current.skip is True: self.cycle(delta) return # si se saltea un panel, no hay que mostrar el panel siguiente 2 veces. self.current.show() def set_skippable(self, name, value): panel = [i for i in self.panels if i.name == name][0] panel.skip = value def __repr__(self): return 'Layout Panel'
def game_loop(): """basic game loop""" # now setup and initialize everything scr = display.set_mode(size=(800, 600)) d = display d.set_caption("Pysnake") init() # make some black `background` bkg = Surface(scr.get_size()) bkg = bkg.convert() # font to be incorporated TODO: fn = font.Font(None, 36) tex = fn.render("Hello world", 1, (255, 255, 255)) tex_pos = tex.get_rect() tex_pos.centerx = bkg.get_rect().centerx tex.blit(bkg, tex_pos) # basic _not so_ `global` variables position = (0, 0) # current snake position vector = (20, 0) # mr. Snakes moves to right snakes = [(0, 0)] # snake is array of cells length = 5 # initial snake's lenght appleh = spawn_apple(scr, snakes) # initial apple while 1: # game loop for e in event.get(): if e.type == QUIT: quit() if e.type == KEYDOWN: if e.key == K_d: vector = (20, 0) if e.key == K_a: vector = (-20, 0) if e.key == K_w: vector = 0, -20 if e.key == K_s: vector = 0, 20 bkg.fill((0, 0, 0)) position = position[0] + vector[0], position[1] + vector[1] # move the snake if position in snakes: # collision detected vector = (0, 0) # TODO: if appleh == position: # collision with apple length += 1 appleh = spawn_apple(scr, snakes) snakes.insert(0, position) # add current position to snake array if len(snakes) > length: # if the snake is longer, than he should be snakes.pop() # pop his tail for pos in snakes: # for each cell in snake's list draw_cell(pos, bkg) # draw the cell draw_appleh(appleh, bkg) scr.blit(bkg, (0, 0)) d.flip() # print(snakes) print(appleh) time.wait(125) # you may set this to smaller number
class Player(Sprite): color = 255, 255, 255 lives = 5 size = 20, 20 speed = 7 health = 100 speedmod_rad = 0 # default -2 speedmod_carrying = 0 # default -2 speedmods = [0, 0] # element 0 is carried, element 1-X is environment. def __init__(self, loc, bounds): Sprite.__init__(self) self.image = Surface(self.size) self.rect = self.image.get_rect() self.image = load_image("icemeteor") self.rect.center = loc self.bounds = bounds self.carrying = None def grab(self, robot): if not self.carrying: self.carrying = robot self.speedmods[0] = -robot.weight def drop(self): self.carrying = None self.speedmods[0] = 0 def update(self): speedtotal = 0 for element in self.speedmods[:]: speedtotal += element if self.speed + speedtotal < 0: speedtotal = self.speed keys = pygame.key.get_pressed() if keys[K_DOWN] or keys[K_s]: self.rect.y += self.speed + speedtotal if keys[K_UP] or keys[K_w]: self.rect.y += -(self.speed + speedtotal) if keys[K_LEFT] or keys[K_a]: self.rect.x += -(self.speed + speedtotal) if keys[K_RIGHT] or keys[K_d]: self.rect.x += self.speed + speedtotal self.rect.clamp_ip(self.bounds) # stays within bounds if self.carrying: self.carrying.rect.center = self.rect.center # clamps robot to player def damage(self, source): "Applies damage effect unique to the robot. source is the object, source_element is the damage type" if source.kind != "radiation": print "player hit: ", source, " ", source.kind if source.kind == "rock": print "Player was hit by a rock!" self.health -= 25 if self.health <= 0: self.lives -= 1
def __init__( self, screen: "in_game.screen.screen.InGameScreen", surface: Surface, fonts: Dict[str, Font], sounds: Dict[str, Sound], images: Dict[str, Surface], player: "in_game.play_area.sprites.player.Player") -> None: self.__screen = screen self.__surface = surface self.__fonts = fonts self.__sounds = sounds self.__images = images self.__keyboard = Keyboard( screen, surface, player, self.__fonts, WHITE) for event_handler in self.__keyboard.get_event_handlers(): screen.add_event_handler(event_handler) block_rect = surface.get_rect( topleft=(PlayArea.LEFT_MARGIN, PlayArea.TOP_MARGIN), width=surface.get_width() - PlayArea.LEFT_MARGIN, height=surface.get_height() - PlayArea.TOP_MARGIN) block_surface = surface.subsurface(block_rect) self.__block_area = BlockArea(self, block_surface, fonts, images, sounds, player) player_string = "PLAYER {0:d}: ".format(player.get_number()) size = self.__fonts["big"].size(player_string) initial_pos = (self.__surface.get_width() // 2 - size[0], 5) self.__player_text = pygame.sprite.GroupSingle( TextSprite(initial_pos, player_string, self.__fonts["big"], GREEN) ) initial_pos = (self.__surface.get_width() // 2, 5) score = Score(initial_pos, fonts["big"], sounds["score"]) self.__score = pygame.sprite.GroupSingle(score) self.__debug_info = pygame.sprite.GroupSingle(DebugInfo(self, fonts)) self.__scroll_velocity = 8 self.__line_numbers = pygame.sprite.OrderedUpdates() self.__active_power_up_jump = GroupSingleAnyRect() self.__active_power_up_shield = GroupSingleAnyRect() self.__game_over_score = pygame.sprite.GroupSingle() # (735 - 35) / 32 = 22 self.__max_line_numbers = round((surface.get_height() - PlayArea.TOP_MARGIN) / Block.BLOCK_HEIGHT) if player.get_joystick() is not None: screen.add_event_handler(PlayerJoystickEventHandler(screen, player.get_joystick(), player)) event_handler = PlayerKeyboardEventHandler( screen, PlayArea.key_mappings[player.get_number() - 1], player) screen.add_event_handler(event_handler) self.__game_over_bg = None
class PopUpMessage(BaseWidget): blinking = False ticks = 0 def __init__(self, text): super().__init__() self.layer = 50 self.image = Surface([200, 200]) self.rect = self.image.get_rect(center=(ANCHO // 2, (ALTO // 2) - 100)) self.image.fill(COLOR_AREA, [1, 1, self.rect.w - 2, self.rect.h - 2]) size = 14 f = self.crear_fuente(size) f2 = self.crear_fuente(20) success = False message = None while success is False: try: message = render_textrect(text, f, self.rect.inflate(-5, -3), COLOR_TEXTO, COLOR_AREA, 1) success = True except TextRectException: size -= 1 f = self.crear_fuente(size) msg_rect = message.get_rect(x=3, centery=self.rect.centery - self.rect.y) self.image.blit(message, msg_rect) self.blink_area = self.image.fill((100, 100, 100), [1, 1, self.rect.w - 31, 25]) self.write(' X ', f2, (200, 0, 0), right=self.rect.w - 2, y=1) self.close_area = Rect(367, self.rect.y, 32, 30) self.show() def on_mousebuttondown(self, event): if event.button == 1: if self.close_area.collidepoint(event.pos): self.hide() WidgetHandler.unlock() def blink(self): self.blinking = True def update(self): j = 8 if self.blinking: self.ticks += 1 t = self.ticks if (0 < t <= j) or (j * 2 + 1 <= t <= j * 3) or ( j * 4 + 1 <= t <= j * 5) or (j * 6 + 1 <= t <= j * 7): self.image.fill((200, 50, 0), self.blink_area) elif (j + 1 <= t <= j * 2) or (j * 3 + 1 <= t <= j * 4) or ( j * 5 + 1 <= t <= j * 6) or (j * 7 + 1 <= t <= j * 8): self.image.fill((255, 255, 0), self.blink_area) else: self.image.fill((100, 100, 100), self.blink_area) self.blinking = False self.ticks = 0
class Enemy_visitor(sprite.Sprite): def __init__(self, x) -> None: super().__init__() self.image = Surface((3, win_height)) self.image.fill((0, 0, 0)) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = 0
def scaling_repeat(surface: Surface, size: (int, int)): return_surface = Surface(size, SRCALPHA) return_surface.fill((0, 0, 0, 0), ) i, j = 0, 0 while True: while True: return_surface.blit( surface, (i, j, surface.get_rect().width, surface.get_rect().height)) j += surface.get_rect().height if j > size[0]: break j = 0 i += surface.get_rect().width if i > size[0]: break return return_surface
class Border(pygame.sprite.Sprite): def __init__(self, size, center, color=BLACK, opacity=255, *groups): super().__init__(*groups) pygame.sprite.Sprite.__init__(self) self.image = Surface(size) self.image.fill(color) self.rect = self.image.get_rect() self.rect.center = center
def check_aliens_bottom(ai_settings: Settings, screen: Surface, stats: GameStats, sb: Scoreboard, ship: Ship, aliens: Group, bullets: Group): screen_rect = screen.get_rect() for alien in aliens.sprites(): if alien.rect.bottom >= screen_rect.bottom: ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets) break
class Scaner(sprite.Sprite): def __init__(self, x) -> None: super().__init__() self.image = Surface((10, win_height)) self.image.fill((0, 0, 0)) self.rect = self.image.get_rect() self.rect.centerx = x self.rect.y = 0
def __init__(self, texture: pygame.Surface, scale: np.array, keep_proportions: bool=False): Shape.__init__(self) if keep_proportions: scale_normalized = scale / np.linalg.norm(scale) scale = np.array(texture.get_rect().size) * scale_normalized scale = tuple(map(int, scale)) self.texture = pygame.transform.scale(texture, scale).convert_alpha() self.mask = pygame.mask.from_surface(self.texture)
def __init__(self, sur: pygame.Surface, rotation_point=None): self._sur = sur super(RotationSurface, self).__init__( (sur.get_width() * 2, sur.get_height() * 2), pygame.SRCALPHA) self._rotation_point = None self.rotation_point = rotation_point if rotation_point is not None else sur.get_rect( ).center self._cache = {}
class Tail(sprite.Sprite): def __init__(self): super().__init__() self.tail = Surface([60, 60]) self.tail.fill(BLUE) self.rect = self.tail.get_rect() self.rect.x = -250 self.rect.y = -250
class Platform(Sprite): def __init__(self, x, y): Sprite.__init__(self) self.image = Surface((25, 20)) self.image.fill((255, 22, 255)) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y
def update(self, player: PlayerSprite, enemies: Group, screen: Surface): if (self._data.health <= 0): self.kill() enemies.remove(self) try: for enemy in enemies: if sprite.collide_circle(self, enemy) and enemy != self: distance = math.hypot((enemy.rect.x - self.rect.x), (enemy.rect.y - self.rect.y)) if (distance < 400): target_direction = Vector2( (self.rect.x - enemy.rect.x), (self.rect.y - enemy.rect.y)) target_direction.scale_to_length(self._data.vel * 0.001) self.rect.x += target_direction.x self.rect.y += target_direction.y # Delete enemy when it comes into contact with player if sprite.collide_mask( player, self) is not None and not player.invulnerable: player.take_damage(1) self.kill() enemies.remove(self) # Type 2 enemy specification # Auto fire towards player at a given rate n = time.get_ticks() if (self._charging) <= 1000: self._charging = n - self._start self._pstart = time.get_ticks() target_direction = Vector2(-self.rect.x + player.rect.x, -self.rect.y + player.rect.y) target_direction.scale_to_length(self._data.vel * 2) self.rect.x += target_direction.x self.rect.y += target_direction.y elif (self._charging > 1000): self._pausing = time.get_ticks() - self._pstart if (self._pausing) > 550: self._charging = 0 self._pausing = 0 self._start = time.get_ticks() screen_rect = screen.get_rect() self.rect.clamp_ip(screen_rect) self._data.pos = Vector2(self.rect.center) self._calc_rotation(player) except ValueError: return
class Sprite(DirtySprite): def __init__(self): DirtySprite.__init__(self) if not self.data['group'] == "text": self.image = Surface(self.data['size']).convert_alpha() self.image.fill(self.data['color']) self.rect = self.image.get_rect() self.stopped = True self.x, self.y = 0, 0 self.alpha = None self.align() def align(self): size = self.data['size'] pos = self.data['pos'] offset = self.data['offset'] w,h = State.window.get_size() if self.data['align'] == "relative": if pos == "topleft": self.rect.topleft = offset elif pos == "top": self.rect.centerx = (w/2) + offset[0] self.rect.top = offset[1] elif pos == "topright": self.rect.topright = [ w - offset[0], offset[1] ] elif pos == "left": self.rect.left = offset[0] self.rect.centery = (h/2) + offset[1] elif pos == "center": self.rect.center = [ (w/2) + offset[0], (h/2) + offset[1] ] elif pos == "right": self.rect.right = w - offset[0] self.rect.centery = (h/2) - offset[1] elif pos == "bottomleft": self.rect.bottomleft = [ offset[0], h - offset[1] ] elif pos == "bottom": self.rect.centerx = (w/2) + offset[0] self.rect.bottom = h - offset[1] elif pos == "bottomright": self.rect.bottomright = [ w - offset[0], h - offset[1] ] elif self.data['align'] == "tile": self.rect.topleft = ( (pos[0] + offset[0]) * size[0], (pos[1] + offset[1]) * size[1]) def do_actions(self): for action in self.data['actions']: eval(action)(self) def move(self): self.dirty = 1 speed = self.data['speed'] self.rect.move_ip([self.x * speed, self.y * speed]) def update(self): self.do_actions() if not self.stopped: self.move()
def __init__(self, game, image: pg.Surface, x, y): self._layer = 2 # required for pygame.sprite.LayeredUpdates: set before adding it to the group! super().__init__(game.all_sprites, game.birds) self._game = game self.image = image self.origin_image = self.image self.rect = image.get_rect(x=x, y=y) self._vel_y = 0 self.score = 0
def genera_immagini_chunk(self): filename = r"../graphics/results/"+ self.pkl_name.split('/')[-1] if os.path.isfile(filename): print "[WORLD MAKER]: nothing to save..." return z_max = self.maximun dz_height = int((z_max)*(BLOCCOY-2*DY)) height = int(2*DY*(self.dimy-1)+BLOCCOY + dz_height) width = int(BLOCCOX*(self.dimx)) print "[WORLD MAKER]: generation of chunk images\t" background_final = Surface((width, height)) background_final.set_colorkey(TRANSPARENCY) background_final.fill(TRANSPARENCY) #sea_background = Surface((width, height)) #sea_background.set_colorkey(TRANSPARENCY) #sea_background.fill(TRANSPARENCY) for z in range(self.dimz): background = Surface((width, height)) #immagine con i tiles bassi foreground = Surface((width, height)) #immagine con i tiles alti background.fill(TRANSPARENCY) foreground.fill(TRANSPARENCY) background.set_colorkey(TRANSPARENCY) foreground.set_colorkey(TRANSPARENCY) for y in range(self.dimy): for x in range(self.dimx): t_type = self.matrix[z][y][x] tile = self.load_tile(t_type,z,1) tile_up = self.load_tile(t_type,z,0) if tile: xo = width/2 + (x-y-1)*DX yo = (x+y)*DY - z*DZ + dz_height tileRect = tile.get_rect() tileRect.topleft = (int(xo),int(yo)+BLOCCOY/2) background.blit(tile,tileRect) if tile_up: xo = width/2 + (x-y-1)*DX yo = (x+y)*DY - z*DZ + dz_height tileRect = tile_up.get_rect() tileRect.topleft = (int(xo),int(yo)) #if t_type == T_ACQUA: # sea_background.blit(tile_up,tileRect) #else: foreground.blit(tile_up,tileRect) background_final.blit(background,background.get_rect()) background_final.blit(foreground,background.get_rect()) data = Image.tostring(background, "RGBA") surf = Image.fromstring(data, (width, height), 'RGBA', False) Image.save(surf,r"../graphics/results/hill_"+str(z)+"_d.png") data = Image.tostring(foreground, "RGBA") surf = Image.fromstring(data, (width, height), 'RGBA', False) Image.save(surf,r"../graphics/results/hill_"+str(z)+"_u.png") #data = Image.tostring(sea_background, "RGBA") #surf = Image.fromstring(data, (width, height), 'RGBA', False) #Image.save(surf,r"../graphics/results/sea.png") Image.save(background_final,r"../graphics/results/all_hill.png") pickle.dump( self.matrix, open( r"../graphics/results/"+self.pkl_name.split('/')[-1], "wb" ) )
def draw(self, surface: pygame.Surface) -> List[MouseRegion]: surface.fill(self.BG_COLOR) if not self.input.value: return [] frame_surface = _opencv_to_pygame(self.input.value) target_rect = frame_surface.get_rect().fit(surface.get_rect()) target_surface = surface.subsurface(target_rect) pygame.transform.scale(frame_surface, target_rect.size, target_surface) return [MouseRegion(self.input.value.source, target_rect, (self.input.value.width, self.input.value.height))]
def __init__(self, img: pygame.Surface, cols, rows): self.img = img self.cols = cols self.rows = rows self.imgSize = img.get_rect().size self.cellSize = pygame.Rect(0, 0, self.imgSize[0] / self.cols, self.imgSize[1] / self.rows) self.__calculate() self.cellCount = len(self.cells)
class Box(Sprite): def __init__(self, color, x=0, y=0): super().__init__() self.image = Surface((50, 50)) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.color = color self.image.fill(self.color)
class TextPanel(Sprite): def __init__(self): super().__init__() self._image = Surface((130, 50)) self._image.fill(RED) font = Font(pygame.font.match_font('arial'), 18) font_sc = font.render('Привет', 1, GREEN) self._image.blit( font_sc, font_sc.get_rect(center=self._image.get_rect().center))
def update(self, player: PlayerSprite, enemies: Group, screen: Surface): if self._data.health <= 0: self.dead = True self.kill() if sprite.collide_mask(player, self) is not None and not player.invulnerable: player.take_damage(1.5) self.take_damage(50) state = self._data.state if state is BossState.MOVEDOWN: target_direction = Vector2(0, 1) self._data.attack_speed = 2000 self._calc_rotation(player) self.image.set_alpha(255) self._data.vel = 6 self._weapon.fire(player, self._data.attack_speed, 10, self.rect) self._weapon.update() self.invulnerable_start = time.get_ticks() elif state is BossState.MOVEUP: target_direction = Vector2(0, -1) self._data.attack_speed = 2000 self._calc_rotation(player) self.image.set_alpha(255) self._data.vel = 6 self._weapon.fire(player, self._data.attack_speed, 10, self.rect) self._weapon.update() self.invulnerable_start = time.get_ticks() elif state is BossState.TRANSITION: target_direction = Vector2(0, 0) self._weapon = self.temp_weapon self._weapon.spawn() self._data.invulnerable = True self.image.set_alpha(100) self._set_enraged_image(ResourceContainer()) elif state is BossState.ENRAGED: self._data.invulnerable = False target_direction = player._data.pos - self._data.pos target_direction = self._avoid_player(player, target_direction) self._data.attack_speed = 900 self._calc_rotation(player) self.image.set_alpha(255) self._data.vel = 7 self._weapon.fire(player, self._data.attack_speed, 20, self.rect, 3) self._weapon.update() if target_direction.length() != 0: target_direction.scale_to_length(self._data.vel) screen_rect = screen.get_rect() self._data.pos += target_direction self.rect = self.image.get_rect(center=self._data.pos) self.rect.clamp_ip(screen_rect)
class Window(BaseWidget): def __init__(self): super().__init__() self.image = Surface((ANCHO, ALTO)) self.image.fill(COLOR_BOX) self.rect = self.image.get_rect() Renderer.add_widget(self) WidgetHandler.add_widget(self)
def render(self, surface: pygame.Surface) -> pygame.Surface: surface.fill(GameConfig.COLOUR_RED) rect = surface.get_rect() image = SplashScreen.logo image_rect = image.get_rect() mid_x = rect.w / 2 - (image_rect.w / 2) mid_y = rect.h / 2 - (image_rect.h / 2) surface.blit(SplashScreen.logo, (mid_x, mid_y)) return surface
class Block(Sprite): '''A plain coloured block that the window can draw''' def __init__(self, *, topleft:tuple=(0, 0), colour:Colour=Colour('black'), dimensions:tuple): super().__init__() self.image = Surface(dimensions) self.image.fill(colour) self.rect = self.image.get_rect() self.rect.topleft = topleft
def __init__(self, game, image: pg.Surface, x, y): self._layer = 2 super().__init__(game.all_sprites, game.birds) self._game = game self.image = image self.origin_image = self.image self.rect = image.get_rect(x=x, y=y) self._vel_y = 0 self.score = 0
class Robot(Sprite): color = 255,255,0 size = 20,20 health = 1 weight = 2 iscarried = False childshield = 0 name = "empty" def __init__(self,loc,bounds): Sprite.__init__(self) self.bounds = bounds self.image = Surface(self.size) self.rect = self.image.get_rect() self.rect.bottomleft = loc self.image.fill(self.color) self.makeshield() self.sprite = RoboGroup.robosprites.add(RoboImages (self)) self.get_sound() #def update(self): def get_sound(self): self.death_sfx = load_sfx("brotherbotdeath") self.hiss_sfx = load_sfx("hiss") def makeshield(self): return def update(self): keys = pygame.key.get_pressed() self.rect.clamp_ip(self.bounds) childsprite.update def damage (self, source): if not self.immunitycheck(source): self.health -= source.damage print "robot hit" if source.kind == "fire": DebrisGroup.debris.add(Spark(self)) self.hiss_sfx.stop() self.hiss_sfx.play() else: DebrisGroup.debris.add(Gear(self)) if self.health <= 0: print "Robot killed" self.death_sfx.stop() self.death_sfx.play() self.kill() def immunitycheck(self, source): if source.kind =="radiation": return True else: return False
class Ball(Sprite): def __init__(self): super().__init__() self.image = Surface([10, 10]) self.image.fill(Color('red')) self.rect = self.image.get_rect() def update(self): self.rect = self.rect.move(10, 0)
def get_aa_round_rect(size, radius, color): surface = Surface(size, flags=SRCALPHA).convert_alpha() rect = Rect((0, 0), size) color = Color(*color) alpha = color.a color.a = 0 rectangle = Surface(size, SRCALPHA) #here 5 is an arbitrary multiplier, we will just rescale later circle = Surface([min(size) * 5, min(size) * 5], SRCALPHA) draw.ellipse(circle, (0,0,0), circle.get_rect(), 0) circle = transform.smoothscale(circle, (2*radius, 2*radius)) #now circle is just a small circle of radius #blit topleft circle: radius_rect = rectangle.blit(circle, (0, 0)) #now radius_rect = Rect((0, 0), circle.size), rect=Rect((0, 0), size) #blit bottomright circle: radius_rect.bottomright = rect.bottomright #radius_rect is growing rectangle.blit(circle, radius_rect) #blit topright circle: radius_rect.topright = rect.topright rectangle.blit(circle, radius_rect) #blit bottomleft circle: radius_rect.bottomleft = rect.bottomleft rectangle.blit(circle, radius_rect) #black-fill of the internal rect rectangle.fill((0, 0, 0), rect.inflate(-radius_rect.w, 0)) rectangle.fill((0, 0, 0), rect.inflate(0, -radius_rect.h)) #fill with color using blend_rgba_max rectangle.fill(color, special_flags=BLEND_RGBA_MAX) #fill with alpha-withe using blend_rgba_min in order to make transparent #the rectangle.fill((255, 255, 255, alpha), special_flags=BLEND_RGBA_MIN) surface.blit(rectangle, rect.topleft) return surface