class GameScene(Scene): def __init__(self): super().__init__() self.w_width = int(c.screen_resolution[0]) w_height = int(c.screen_resolution[1]) c.change_window_location( c.monitor_dimensions[0] / 2 - self.w_width / 2, c.monitor_dimensions[1] / 2 - w_height / 2) self.screen = display.set_mode((self.w_width, w_height)) self.screen_rect = self.screen.get_rect() self.bg = Surface(self.screen.get_size()) self.bg.convert() self.bg.fill((100, 155, 200)) self.ball = Ball((0, 0, 0), c.radius1) self.block = Block(c.blue, 200, 25) self.sprites_list = Group(self.ball, self.block) self.score_label = ScoreLabel() self.game_over = False def render(self): self.screen.blit(self.bg, (0, 0)) self.screen.blit( self.score_label.image, (self.w_width / 2 - self.score_label.image.get_width() / 2, 0)) self.sprites_list.draw(self.screen) def update(self): self.sprites_list.update(self) self.score_label.update() def handle_events(self, events): pass
def load_sprite_sheet( sheetname, nx, ny, scalex=-1, scaley=-1, colorkey=None, ): fullname = os.path.join("assets/sprites", sheetname) sheet = load(fullname) sheet = sheet.convert() sheet_rect = sheet.get_rect() sprites = [] sizey = sheet_rect.height / ny if isinstance(nx, int): sizex = sheet_rect.width / nx for i in range(0, ny): for j in range(0, nx): rect = Rect((j * sizex, i * sizey, sizex, sizey)) image = Surface(rect.size) image = image.convert() image.blit(sheet, (0, 0), rect) if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0, 0)) image.set_colorkey(colorkey, RLEACCEL) if scalex != -1 or scaley != -1: image = transform.scale(image, (scalex, scaley)) sprites.append(image) else: #list sizex_ls = [sheet_rect.width / i_nx for i_nx in nx] for i in range(0, ny): for i_nx, sizex, i_scalex in zip(nx, sizex_ls, scalex): for j in range(0, i_nx): rect = Rect((j * sizex, i * sizey, sizex, sizey)) image = Surface(rect.size) image = image.convert() image.blit(sheet, (0, 0), rect) if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0, 0)) image.set_colorkey(colorkey, RLEACCEL) if i_scalex != -1 or scaley != -1: image = transform.scale(image, (i_scalex, scaley)) sprites.append(image) sprite_rect = sprites[0].get_rect() return sprites, sprite_rect
def createSolidButton(x, y, width, height, colorNormal, colorPressed, onClickedFunc): """ Creates a solid button, where colorNormal is the normal, unpressed color, and colorPressed is the pressed color. colorNormal and colorPressed are tuples, containing red, blue, green. """ normalSurface = Surface((width, height)) normalImage = normalSurface.convert() normalImage.fill(colorNormal) pressedSurface = Surface((width, height)) pressedImage = pressedSurface.convert() pressedImage.fill(colorPressed) return Button(x, y, normalImage, pressedImage, onClickedFunc, 0)
def smart_convert( original: pygame.Surface, colorkey: Optional[ColorLike], pixelalpha: bool, ) -> pygame.Surface: """ Return new pygame Surface with optimal pixel/data format This method does several interactive_tests on a surface to determine the optimal flags and pixel format for each tile surface. Parameters: original: tile surface to inspect colorkey: optional colorkey for the tileset image pixelalpha: if true, prefer per-pixel alpha surfaces Returns: new tile surface """ # tiled set a colorkey if colorkey: tile = original.convert() tile.set_colorkey(colorkey, pygame.RLEACCEL) # TODO: if there is a colorkey, count the colorkey pixels to determine if RLEACCEL should be used # no colorkey, so use a mask to determine if there are transparent pixels else: tile_size = original.get_size() threshold = 254 # the default try: # count the number of pixels in the tile that are not transparent px = pygame.mask.from_surface(original, threshold).count() except: # pygame_sdl2 will fail because the mask module is not included # in this case, just convert_alpha and return it return original.convert_alpha() # there are no transparent pixels in the image if px == tile_size[0] * tile_size[1]: tile = original.convert() # there are transparent pixels, and set for perpixel alpha elif pixelalpha: tile = original.convert_alpha() # there are transparent pixels, and we won't handle them else: tile = original.convert() return tile
class Player(Sprite): def __init__(self, x, y): super().__init__() self.xvel = 0 self.yvel = 0 self.onGround = True self.image = Surface((32, 32)) self.image.fill(Color("#00FFFF")) self.image.convert() self.rect = Rect(x, y, 32, 32) def update(self): self.rect = self.rect.move(3, 0)
class ShipRocket(Ship): def __init__(self, size, seed): super(ShipRocket, self).__init__(size, seed) # Structure of the ship is a central tube with surface variations # A symmetrical / asymmetrical collection of one or more thrusters encircling the back numThrusters = self.Rship.randint(2, 7) self.thrusterRadius = self.Rship.randint(self.width >> 3, self.width >> 2) self.thrusterLength = self.Rship.randint(self.height >> 2, self.height >> 1) self.thrusterAngle = int(360 / numThrusters) self.thrusters = [] thrusterSeed = self.Rthrust.randint(1000000000, 9999999999) for i in xrange(0, numThrusters + 1): A = (self.thrusterAngle * i) % MAXANG self.thrusters.append( (Thruster(self.thrusterRadius << 1, self.thrusterLength, thrusterSeed, self.basecol, self.flines, randint(0, 10), randint(2, 12)), (COS[A], SIN[A]))) self.chassis = [] y = 0 x = (self.width >> 1) - (self.chassisWidth >> 1) self.model = Part( "Ship", Thruster(self.chassisWidth, self.chassisLength, self.shipSeed, self.basecol, self.flines, self.decayamount, self.panelsize), (0, 0, 0)) y = self.model.height - 1 - self.thrusterLength - self.Rship.randint( 0, self.model.height >> 3) for (img, (x, z)) in self.thrusters: #self.gfx.blit(img,((self.width>>1)+thustHarnessRadius*theta,(self.height-1-self.thrusterLength))) self.model.add( Part( "Thruster", Thruster(self.thrusterRadius << 1, self.thrusterLength, thrusterSeed, self.basecol, self.flines, self.decayamount, self.panelsize), (x * (self.model.width >> 1), y, (z * (self.model.width >> 1))))) # Render all the parts self.gfx = Surface(size, SRCALPHA) self.gfx.convert() print "Drawing" self.model.draw(self.gfx) self.rotation = 0 self.gfxrot = self.gfx
def __init__(self, x: int, y: int, spritesheet: Surface): """ Creates a berry object. @param x: x position of the berry in *world coordinates* @param y: y position of the berry in *world coordinates* @param spritesheet: a surface containing all costumes for the berry """ Sprite.__init__(self) self.position = Vector2(x, y) spritesheet.convert() spritesheet.set_colorkey(Color(128, 51, 0)) self.image = spritesheet self.rect = self.image.get_rect(center=self.position)
def _create_road_segment(self): """Create the bmp for a road segment """ # logg = getMyLogger(f"c.{__name__}._create_road_segment") self.segment_wid = 350 self.segment_hei = 150 if self.render_mode == "human": line_wid = 2 mid_hei = self.segment_hei // 2 seg_surf = Surface((self.segment_wid, self.segment_hei)) seg_surf = seg_surf.convert() segment_grey = (128, 128, 128) seg_surf.fill(segment_grey) # Rect(left, top, width, height) -> Rect line_white = (255, 255, 255) line_rect = 0, mid_hei - line_wid, self.segment_wid, line_wid draw.rect(seg_surf, line_white, line_rect) line_rect = self.segment_wid - line_wid, 0, line_wid, self.segment_hei draw.rect(seg_surf, line_white, line_rect) self.segment_orig = seg_surf elif self.render_mode == "console": seg_surf = Surface((self.segment_wid, self.segment_hei)) self.segment_orig = seg_surf else: raise ValueError(f"Unknown render mode {self.render_mode}")
class Terrain(): def __init__(self): self._loadImages() self.stopped = True self.surface = Surface((config['SCREEN_SIZE'][0], config['SCREEN_SIZE'][1] - config['GROUND_POSITION'])) self.surface = self.surface.convert() self.xOffset = 0 def getSurf(self, multiplier = 1): self._fillWithTextures(multiplier) return self.surface def start(self): self.stopped = False def stop(self): self.stopped = True def getCoords(self): return (0,config['GROUND_POSITION']) def _loadImages(self): self.backImg, self.backImgRect = load_image('terrain.png', TERRAIN_SIZE) self.foreImg, self.foreImgRect = load_image('terrain_fore.png', TERRAIN_SIZE) def _fillWithTextures(self, multiplier = 1): totalXSpace = config['SCREEN_SIZE'][0] + (2 * TERRAIN_SIZE[0]) for y in range(0, config['SCREEN_SIZE'][1], TERRAIN_SIZE[1]): for x in range(-TERRAIN_SIZE[0], totalXSpace, TERRAIN_SIZE[0]): self.surface.blit(self.backImg, (x + self.xOffset,y)) self.surface.blit(self.foreImg, (x + self.xOffset, 0)) if not self.stopped: self.xOffset = (self.xOffset - (config['PX_STEP'] * multiplier)) % TERRAIN_SIZE[0]
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
def __init__(self, *, player_icon: pygame.Surface, **kwargs): super().__init__(player_icon=player_icon, **kwargs) self.sprites = tmx.SpriteLayer() self.tilemap.layers.append(self.sprites) start_cell = self.tilemap.layers['triggers'].find('player')[0] self.player = Player(self.sprites, image=player_icon.convert(), location=(start_cell.px, start_cell.py), tilemap=self.tilemap) self.tilemap.set_focus(start_cell.px, start_cell.py, force=True)
class GameMap(object): def __init__(self, gameClient, mapWidth, mapHeight): self.mapWidth = mapWidth self.mapHeight = mapHeight self.gameClient = gameClient self.updated = True self.tilesize = TILESIZE self.widthInPixels = self.mapWidth*self.tilesize self.heightInPixels = self.mapHeight*self.tilesize self.backgroundLayer = TileLayer(gameClient, self.mapWidth, self.mapHeight, "01") self.foregroundLayer = TileLayer(gameClient, self.mapWidth, self.mapHeight, "02") self.spriteLayer = SpriteLayer(gameClient, self.mapWidth, self.mapHeight) self.mapSurface = Surface((self.mapWidth * self.tilesize, self.mapHeight * self.tilesize)) self.updateMapSurface() def clearTileLayers(self): self.backgroundLayer.clearSurface() self.foregroundLayer.clearSurface() def updateMapSurface(self): if self.updated: self.backgroundLayer.blitTiles(self.gameClient) self.foregroundLayer.blitTiles(self.gameClient) self.updated = False self.mapSurface.blit(self.backgroundLayer.getSurface(), self.backgroundLayer.getSurface().get_rect()) #self.mapSurface.blit(self.foregroundLayer.getSurface(), self.foregroundLayer.getSurface().get_rect()) self.mapSurface.convert() def getWidthInPixels(self): return self.widthInPixels def getHeightInPixels(self): return self.heightInPixels def getSizeInPixels(self): return (gameClient.gameMap.getWidthInPixels(), gameClient.gameMap.getHeightInPixels)
def render(points, colour, degraded, R, lines, panelsize): (r, g, b) = colour minx = 999999999 miny = 999999999 maxx = -999999999 maxy = -999999999 # Scan the points for min/max dimensions for (x, y) in points: if minx == None or x < minx: minx = x if minx == None or x > maxx: maxx = x if miny == None or y < miny: miny = y if maxy == None or y > maxy: maxy = y # Normalise the dimensions and allocate image storage to draw into width = int(maxx - minx) height = int(maxy - miny) # Conditionally normalise the points to the workspace - a transformation if minx != 0 or miny != 0: newPoints = [] for (x, y) in points: newPoints.append((x - minx, y - miny)) points = newPoints # print points cx = width >> 1 result = Surface( (width << 1, height), SRCALPHA ) # Target image has to cater for two flipped images, so twice the size result.convert() result.blit( renderhalf((width, height), points, colour, degraded, R, lines, panelsize, False), (width - 1, 0)) result.blit( pygame.transform.flip( renderhalf((width, height), points, colour, degraded, R, lines, panelsize, False), True, False), (0, 0)) if GLOBDEBUG == True: pygame.image.save( result, "RENDER_" + str(randint(1000000000, 9999999999)) + "TEST.png") return result
def load_base(self): """ Load the base (back surface) for the world """ width, height = (WORLD_MAP_SIZE[0] * TILE_SIZE, WORLD_MAP_SIZE[1] * TILE_SIZE) image = Surface((TILE_SIZE, TILE_SIZE)) image.convert() base = pygame.Surface((width, height)) base.convert() # Fill in sky with blue base.fill(Color(0, 0, 255), Rect(0, 0, width, height / 2)) # Fill in ground with brown base.fill(Color("#573B0C"), Rect(0, height / 2, width, height / 2)) return base
def create_surface(self): surface = Surface((self.rect.width, self.rect.height)) surface.fill((244, 158, 66)) # Orange pygame.draw.line(surface, (0, 0, 0), \ (self.rect.width - 1, 0), (self.rect.width - 1, self.rect.height - 1)) pygame.draw.line(surface, (0, 0, 0), \ (0, self.rect.height - 1), (self.rect.width - 1, self.rect.height - 1)) self.image = surface.convert()
def __init__(self): super().__init__() self.rect = Rect(0, 0, 10, 10) surface = Surface(self.rect.size) draw.circle(surface, (232, 54, 42), self.rect.center, 5) self.image = surface.convert()
def void_frame(size, bck): surface = Surface(size) try: surface.fill(bck) surface.set_colorkey(bck, RLEACCEL) except TypeError: surface.fill(WHITE) surface.set_colorkey(constants.WHITE, RLEACCEL) return surface.convert()
def __init__(self, x, y, **kwargs): img = Surface((50,50)) img = img.convert() img.fill(PINK_TRANSPARENT) img.set_colorkey(PINK_TRANSPARENT) col_rect = Rect(24,24,2,2) TryParticle.__init__(self, x=x, y=y, gravity = 0.5, has_gravity=True, image = img, col_rect=col_rect, life_time=100, collides=True) FadeOutParticle.__init__(self, fade_out_time = 30, life_time = 30) RandomSpeedParticle.__init__(self, max_speed = 10, delta_ang = 360, min_speed=5)
def create_surface(self, color): width = self.rect.width height = self.rect.height surface = Surface((width, height)) surface.fill(color) draw.line(surface, (0, 0, 0), (width - 1, 0), (width - 1, height - 1)) draw.line(surface, (0, 0, 0), (0, height - 1), (width - 1, height - 1)) self.image = surface.convert()
class BasicBlock(Sprite): def __init__(self, color, startx, starty, width, height, name): super(BasicBlock, self).__init__() self.image = Surface([width, height]) self.image.fill(color) self.image.convert() if not name.endswith(".none"): self.name = name self.image = pygame.image.load( "./minigames/img/build_a_network/{}.png".format(name)) self.image.convert() else: self.name = name.split(".")[0] self.rect = self.image.get_rect() self.rect.x = startx self.rect.y = starty
def get_surface(self): surface = Surface(self.size) if self.colorkey: surface.fill(self.colorkey) if 0 < self.alpha < 255: surface.set_alpha(self.alpha, RLEACCEL) self.blit_templates(surface) ## self.blit_corners(surface) ## self.blit_sides(surface) surface.set_colorkey(self.colorkey, RLEACCEL) surface.set_clip(self.clip) return surface.convert()
class Light: def __init__(self, label, radius, colour): self.label = label self.radius = radius self.R, self.G, self.B = colour self.A = 255 self.gfx = None def apply(self, img, pos): for (x, y) in pos: if self.gfx == None: self.gfx = Surface( ((self.radius << 1) + 1, (self.radius << 1) + 1), SRCALPHA) self.gfx.convert() gfxdraw.filled_circle(self.gfx, self.radius, self.radius, int(self.radius), (self.R, self.G, self.B, self.A)) r2 = self.radius img.blit(self.gfx, (x - r2, y - r2), special_flags=BLEND_ADD)
def get_tile(self, name, colorkey=None, tile_pos=None): key = (name, tile_pos) if not self.tiles.has_key( key ): image = util.load_image(TILES_DIR, name) image = util.load_image(TILES_DIR, name).convert() if tile_pos is not None: tmp = Surface( (TILE_SIZE, TILE_SIZE) ) rect = Rect(tile_pos[0]*TILE_SIZE, tile_pos[1]*TILE_SIZE,TILE_SIZE,TILE_SIZE) tmp.blit(image, (0,0), rect) image = tmp.convert() self.tiles[key] = image return self.tiles[key]
def __init__(self, **kwargs): BaseParticle.__init__(self) self.custom_properties = { 'color': { "type": tuple, "destination" : "color", "default": WHITE }, 'size': { "type": tuple, "destination" : "size", "default": (1,1) }, } parser = ArgumentParser(self.custom_properties, kwargs, self.__dict__) self.parse_catching_errors(parser, self.custom_properties, kwargs, self.__dict__) # Create the image color img = Surface(self.size) img.fill(self.color) self.image = img.convert()
def shadowed_frame(size, pressed=False, thick=1, color=constants.BRAY, light=None, dark=None): """Returns a sdl surface. Function used as default design for elements.""" if size[1] < 1: size = (size[0], 16) surface = Surface(size) shadowed_frame_blit(surface, pygame.Rect((0, 0), size), pressed, thick, color, light, dark) return surface.convert()
class Organism(Entity): def __init__(self, x, y, level, color = None): Entity.__init__(self) self.image = Surface((16, 16)) if color: self.image.fill(color) self.image.convert() self.rect = Rect(x, y, 16, 16) self.level = level def random_adjacent_coords(self, clear = False): x, y = self.tile_coords() off_x, off_y = 0, 0 while (off_x == 0 and off_y == 0) or not self.level.clear_at_tile(x + off_x, y + off_y): off_x = 1 - randint(0, 2) off_y = 1 - randint(0, 2) return x + off_x, y + off_y def adjacent_entities(self): adjacent_entities = [] x, y = self.tile_coords() for d in DIRECTIONS: entity = self.level.entity_at(x + d[0], y + d[1]) if entity: adjacent_entities.append(entity) return adjacent_entities
def setupGame(show_all=False, SEED=42): # load cards pygame.init() screen = pygame.display.set_mode((GAMEWIDTH, GAMEHEIGHT)) pygame.display.set_caption("Truco") pygame.display.update() for img_name in os.listdir(DATAPATH): if img_name == "back01.gif": BACK1 = Card(img_name) elif img_name == "back02.gif": BACK2 = Card(img_name) elif img_name == "back03.gif": BACK3 = Card(img_name) elif img_name == "back04.gif": BACK4 = Card(img_name) elif img_name == "back05.gif": BACK5 = Card(img_name) elif img_name[0:4] != "back": DECKDICT[img_name[0:-4]] = Card(img_name) else: print("Image not identified!") raise Exception # load sounds pygame.mixer.init(22100, -8, 1, 4) fanSound = load_sound("cardFan.wav") playSound = load_sound("cardPlay.wav") # background background = Surface(screen.get_size()) background = background.convert() background.fill((0, 128, 0)) screen.blit(background, (0, 0)) # players random.seed(SEED) players = [None, None, None, None] players[0] = Hand(screen, True, P1POS, HORIZONTAL, BACK1) players[1] = Hand(screen, show_all, P2POS, VERTICAL, BACK5) players[2] = Hand(screen, show_all, P3POS, HORIZONTAL, BACK3) players[3] = Hand(screen, show_all, P4POS, VERTICAL, BACK4) game = TrucoEnv(players, screen, background, fanSound, playSound) return game
class Sprite: """ A class to represent a sprite. Used for pygame displaying. Image generated with given color and size. """ # default constructor (must be called if overrided by inheritance) def __init__(self, x: int, y: int, w: int, h: int, color: tuple): self.__color = color self._image = Surface((w, h)) self._image.fill(self.color) self._image = self._image.convert() self.rect = Rect(x, y, w, h) self.camera_rect = self.rect.copy() # Public getters for _image & __color so they remain private @property def image(self) -> Surface: return self._image @property def color(self) -> tuple: return self.__color @color.setter def color(self, new: tuple) -> None: " Called when Sprite.__setattr__('color',x)." assert isinstance(new, tuple) and len(new) == 3, "Value is not a color" self.__color = new #update image surface self._image.fill(self.color) def draw(self, surface: Surface) -> None: """ Render method,Should be called every frame after update. :param surface pygame.Surface: the surface to draw on. """ # If camera instancied: calculate render positon if Camera.instance: self.camera_rect = Camera.instance.apply(self) surface.blit(self._image, self.camera_rect) else: surface.blit(self._image, self.rect)
def __init__(self, x: int, y: int, spritesheet: Surface): """ Creates a bear object. @note Not yet tested for cases where multiple bears existing in one scene. @param x: x position of the bear in *world coordinates* @param y: y position of the bear in *world coordinates* @param spritesheet: a surface containing all costumes for the bear. You might want to split the sprite sheet into individual costumes in this function. """ Sprite.__init__(self) # Position-related variables self.position = Vector2(x, y) self.speed = 25 self.directions = [ Vector2(0, -1), Vector2(-1, 0), Vector2(1, 0), Vector2(0, 1) ] self.direction = Vector2(0, -1) self.walking = False # Costume-related variables spritesheet = spritesheet.convert() spritesheet.set_colorkey(Color(128, 51, 0)) self.costumes = [] for i in range(12): row, column = divmod(i, 3) surface = Surface((50, 50)).convert_alpha() surface.fill(Color(0, 0, 0, 0)) surface.blit(spritesheet, surface.get_rect(), area=Rect(column * 50, row * 50, 50, 50)) self.costumes.append(surface) # State variables self.direction_number = 0 self.costume_number = 0 self.image = self.costumes[self.costume_number] # Required by PyGame self.rect = self.image.get_rect( center=self.position) # Required by PyGame self.timer = 0 self.walking_start_time = 0
def get_image(self, x: int, y: int, width: int, height: int, alpha: bool = False) -> Surface: """ Extracts sprite of given point (x, y) (left, top) and width and height. Alpha boolean keyword argument for converting the sprite in alpha or non-alpha. """ image = Surface((width, height)) image.blit(self.spritesheet, (0, 0), (x, y, width, height)) image.set_colorkey((0, 0, 0)) image.set_alpha(255) if alpha: return image.convert_alpha() return image.convert()
def shadowed_frame(size, pressed=False, thick=1, color=constants.BRAY, light=None, dark=None): """Returns a sdl surface. Function used as default design for elements.""" if size[1] < 1: size = (size[0], 16) surface = Surface(size) shadowed_frame_blit( surface, pygame.Rect( (0, 0), size), pressed, thick, color, light, dark) return surface.convert()
def regular_polygon(radius, sides, thickness=0, angle=0., color=constants.BLACK): """Angle is the offset angle in degrees""" surface = Surface((2 * radius, 2 * radius)) different = different_color(color) surface.fill(different) surface.set_colorkey(different, RLEACCEL) angle = radians(angle) alpha = 2 * pi / sides # constant # building points points = list() for i in range(sides): ai = i * alpha + angle pix = cos(ai) * radius + radius piy = sin(ai) * radius + radius points.append((pix, piy)) pygame.draw.polygon(surface, color, points, thickness) return surface.convert()
def regular_polygon( radius, sides, thickness=0, angle=0., color=constants.BLACK): """Angle is the offset angle in degrees""" surface = Surface((2 * radius, 2 * radius)) different = different_color(color) surface.fill(different) surface.set_colorkey(different, RLEACCEL) angle = radians(angle) alpha = 2 * pi / sides # constant # building points points = list() for i in range(sides): ai = i * alpha + angle pix = cos(ai) * radius + radius piy = sin(ai) * radius + radius points.append((pix, piy)) pygame.draw.polygon(surface, color, points, thickness) return surface.convert()
def load_graphics(self): degrees = [-90, -65, -45, -20, 0, 20, 45, 65, 90] degree_images = [] for degree in degrees: image = data.load_image('tman_arm_%d.png' % degree) degree_images.append(image) twisters = range(4) twister_images = [] for twister in twisters: image = data.load_image('tman_twister_%d.png' % (twister + 1)) twister_images.append(image) torso_image = data.load_image('tman_torso.png') size = torso_image.get_rect().width, torso_image.get_rect().height self.frames = {} for degree_image, degree in zip(degree_images, degrees): self.frames[degree] = {} for twister_image, twister in zip(twister_images, twisters): self.frames[degree][twister] = {} image = Surface(size) image = image.convert() image.fill(COLORKEY) image.set_colorkey(COLORKEY) image.blit(torso_image, (0,0)) image.blit(twister_image, (0,0)) image.blit(degree_image, (0,0)) self.frames[degree][twister]['right'] = image image = pygame.transform.flip(image, True, False) self.frames[degree][twister]['left'] = image self.degree = 0 self.side = 'right' self.twister = 0 self.image = self.frames[self.degree][self.twister][self.side] self.rect = self.image.get_rect()
def draw_blank_grid() -> Surface: """Draws the blank game matrix grid surface.""" grid = Surface((333, 663)) grid = grid.convert(grid) grid.fill(Colors.Black.value) pygame.draw.line(grid, Colors.White.value, (0, 0), (332, 0)) pygame.draw.line(grid, Colors.White.value, (0, 1), (332, 1)) pygame.draw.line(grid, Colors.White.value, (0, 0), (0, 662)) pygame.draw.line(grid, Colors.White.value, (1, 0), (1, 662)) pygame.draw.line(grid, Colors.White.value, (0, 662), (332, 662)) pygame.draw.line(grid, Colors.White.value, (0, 661), (332, 661)) pygame.draw.line(grid, Colors.White.value, (332, 0), (332, 662)) pygame.draw.line(grid, Colors.White.value, (331, 0), (331, 662)) for i in range(1, 10): x = (i * 33) + 1 pygame.draw.line(grid, Colors.Gray.value, (x, 2), (x, 660)) for i in range(1, 20): y = (i * 33) + 1 pygame.draw.line(grid, Colors.Gray.value, (2, y), (330, y)) return grid
def basic_bckgr(size, color=constants.BLACK): surface = Surface(size) surface.fill(color) return surface.convert()
class Bar(Sprite): def __init__(self, factor, height, *groups): Sprite.__init__(self, *groups) self.factor = factor self.height = height self.put(0, 0) self.create_image() def update(self, *args): self.create_image() self.update_color() self.update_size() self.create_bar() self.fill_image() def get_max_value(self): pass def get_value(self): pass def create_image(self): self.size = (self.get_max_value() * self.factor) self.image = Surface((self.size, self.height)) self.image = self.image.convert() self.image.set_colorkey(COLORKEY) self.rect = self.image.get_rect() self.rect.left = self.x self.rect.bottom = self.y def update_color(self): color_value = int(255 * self.get_value() / self.get_max_value() ) if 200 <= color_value <= 255: self.color = (0, color_value, 0) elif 90 <= color_value < 200: self.color = (255, color_value + 55, 0) else: self.color = (255-color_value, 0, 0) def update_size(self): self.size = int(self.size * self.get_value() / self.get_max_value() ) def create_bar(self): self.bar = Surface((self.size, 10)) self.bar.fill(self.color) def fill_image(self): self.image.fill(COLORKEY) rect = self.bar.get_rect() rect.bottom = self.image.get_rect().bottom self.image.blit(self.bar, rect) self.draw_border() def put(self, x, y): self.x = x self.y = y def draw_border(self): rect = self.image.get_rect() pygame.draw.rect(self.image, (0, 0, 0), rect, 1)
def simple_frame(size, color=constants.BRAY): surface = Surface(size) surface.fill(color) return surface.convert()
def basic_cursor(height, thickness=1, color=constants.BLACK): begin = (0, 0) end = (0, height) surface = Surface((thickness, height)) pygame.draw.line(surface, color, begin, end, thickness) return surface.convert()
class Background(): def __init__(self): self.loadImages() self.stopped = True self.layer0, self.layer0_rect = backgroundImages[0] # cambia il tempo del gioco ogni tot FPS self.timeTracker = 0 # 0 = mattina, 1 = pomeriggio, 2 = tramonto, 3 = notte self.timePhase = 0 self.layer1, self.layer1_rect = load_image( 'background1.png', SCREEN_SIZE, 0.8) self.layer1Offset = 0 self.layer1Step = 3 self.layer2, self.layer2_rect = load_image( 'background2.png', SCREEN_SIZE, 0.3) self.layer2Offset = -35 self.layer2Step = 1 self.snowSize = (1198, 380) self.snow, self.snow_rect = load_image('snow.png', self.snowSize) self.snowOffset = 0 self.snowStep = 4 self.background = Surface(SCREEN_SIZE) self.background = self.background.convert() self.background.fill(WHITE) self._updateImages() # randomize snow time start createTimeout(800, 6000, self.randomizeSnow) def loadImages(self): for i in range(4): backgroundImages.append(load_image('background/' + str(i) + '.png',SCREEN_SIZE)) def getSurf(self): self._updateImages() return self.background def getCoords(self): return (0, 0) def start(self): self.stopped = False def stop(self): self.stopped = True def randomizeSnow(self): self.snowStep = randrange(3, 6) print(self.snowStep) def _updateImages(self): self.changeTime() self.background.blit(self.layer0, (0, 0)) self.background.blit(self.snow, (0, self.snowOffset)) self.background.blit( self.snow, (0, self.snowOffset - self.snowSize[1])) self.snowOffset = (self.snowOffset + self.snowStep) % self.snowSize[1] self.background.blit(self.layer1, (0 - self.layer1Offset, 135)) self.background.blit( self.layer1, (SCREEN_SIZE[0] - self.layer1Offset, 135)) self.background.blit(self.layer2, (0 - self.layer2Offset, 135)) self.background.blit( self.layer2, (SCREEN_SIZE[0] - self.layer2Offset, 135)) if not self.stopped: self.layer1Offset = (self.layer1Offset + self.layer1Step) % SCREEN_SIZE[0] self.layer2Offset = (self.layer2Offset + self.layer2Step) % SCREEN_SIZE[0] def changeTime(self): if self.timeTracker == 0: self.layer0, self.layer0_rect = backgroundImages[self.timePhase] self.timePhase = (self.timePhase + 1) % 4 self.timeTracker = (self.timeTracker + 1) % CHANGE_TIME_SKIPPER
def load_pygame(filename): """ load a tiled TMX map for use with pygame """ from pygame import Surface import pygame, os tiledmap = load_tmx(filename) # cache will find duplicate tiles to reduce memory usage # mostly this is a problem in the blank areas of a tilemap cache = {} # just a precaution to make sure tileset images are added in the correct order for firstgid, t in sorted([(t.firstgid, t) for t in tiledmap.tilesets]): path = os.path.join(os.path.dirname(tiledmap.filename), t.source) image = pygame.image.load(path) w, h = image.get_rect().size tile_size = (t.tilewidth, t.tileheight) # some tileset images may be slightly larger than the tiles area # ie: may include a banner, copyright, etc. this compensates for that for y in range(0, int(h / t.tileheight) * t.tileheight, t.tileheight): for x in range(0, int(w / t.tilewidth) * t.tilewidth, t.tilewidth): # somewhat handle transparency, though colorkey handling is not tested if t.trans is None: tile = Surface(tile_size, pygame.SRCALPHA) else: tile = Surface(tile_size) # blit the smaller portion onto a new image from the larger one tile.blit(image, (0, 0), ((x, y), tile_size)) # make a unique id for this image, not sure if this is the best way, but it works key = pygame.image.tostring(tile, "RGBA") # make sure we don't have a duplicate tile try: tile = cache[key] except KeyError: if t.trans is None: tile = tile.convert_alpha() else: tile = tile.convert() tile.set_colorkey(t.trans) # update the cache cache[key] = tile tiledmap.images.append(tile) # correctly handle transformed tiles. currently flipped tiles # work by creating a new gid for the flipped tile and changing the gid # in the layer to the new gid. for layer in tiledmap.tilelayers: for x, y, gid, trans in layer.flipped_tiles: fx = trans & FLIP_X == FLIP_X fy = trans & FLIP_Y == FLIP_Y tile = pygame.transform.flip(tiledmap.images[gid], fx, fy) tiledmap.images.append(tile) # change the original gid in the layer data to the new gid layer.data[y][x] = len(tiledmap.images) - 1 del layer.flipped_tiles del cache return tiledmap
class Tower(sprite.Sprite): """ Base Tower Class """ def __init__(self, pos): sprite.Sprite.__init__(self) self.name = "Tower" self.pos = pos self.grid_pos = tuple([x/40 for x in self.pos]) self.image = Surface((40, 40)).convert() self.kills = 0 self.damage_done = 0 self.image.fill((225, 50, 50)) self.rect = Rect(self.pos, self.image.get_size()) self.projectile = Surface((10, 10)).convert() self.projectile.fill((0, 255, 255)) self.projectile_speed = 5 self.projectiles = sprite.Group() self.turn_yield = 0 self.radius = 200 self.fire_rate = 1 self.damage = 25 self.level = 1 self.upgrade_cost = 5 self.description = "A basic tower with moderate fire speed and damage." self.cost = 25 self.value = self.cost self.target = None self.last_shot = time.time() self.image.convert() self.projectile.convert() self.frame = TowerFrame(self) def update(self, monsters, screen, screen_rect): # If there is no target if self.target is None: for monster in monsters: if monster.can_move: if sprite.collide_circle(monster, self): self.target = monster break # Shoot at the target if self.target is not None: # If the target has gone out of range if not sprite.collide_circle(self.target, self): self.target = None else: self.shoot() if self.target.health <= 0: self.target = None self.projectiles.update(monsters, screen_rect) self.projectiles.draw(screen) def update_info(self): self.frame = TowerFrame(self) def shoot(self): if time.time() - self.last_shot >= self.fire_rate: self.projectiles.add(Projectile(pos=(self.rect.x, self.rect.y), tower=self, target=self.target, image=self.projectile, speed=self.projectile_speed, damage=self.damage)) self.last_shot = time.time() def upgrade(self): if self.level < 5: self.damage += 5 self.projectile_speed -= 0.5 self.level += 1 self.update_info() return True return False
screen.blit(background, (0, 0)) display.flip() sleep(0.1) if i >= 2 : _linux_set_time(dt.timetuple()) urlopen("http://127.0.0.1/functions/cron.php?change=" + dr.strftime("%s")).read() break # Initialisation display.init() font.init() screen = display.set_mode([320, 240]) background = Surface(screen.get_size()) background = background.convert() # Récupération de la config conf_file = open("../conf/wake.json") conf = jload(conf_file) # Définition des polices font_filename = font.match_font(conf["general"]["font"]) font = font.Font(font_filename, 135) #font_time = font.Font(font_filename, 135) # Definition et coloration des images image_temp = image.load("images/misc/temp.png")