def _initSpellImage(self): self.fireball = image.load("Res/fireball.png") self.teleport = image.load("Res/teleport.png") self.frostNova = image.load("Res/frostnova.png") self.fireNova = image.load("Res/firenova.jpg") self.shield = image.load("Res/shield.png")
def load_frames(self, path, frames, convert_alpha=False): """ Load a sequence of image named 1.ext...*frames*.ext from *path* *ext* must be consistent :param path: Path in list format pointing to a directory :param frames: Number of frames to load :param convert_alpha: whether surfaces are converted with convert_alpha() :return: a list of surfaces """ dir_path = self.get_path(path) extension = "" for name in listdir(dir_path): file = join(dir_path, name) if isfile(file): striped, file_ext = splitext(name) if striped == "1": extension = file_ext break surfs = [] for c in range(1, frames + 1): file = join(dir_path, str(c) + extension) if convert_alpha: surfs.append(load(file).convert_alpha()) continue surfs.append(load(file).convert()) return surfs
def load_tile(element, side=1): # side = 1: bottom, side = 0: top """ :type side: object :param element: :param side: :return: """ if element == T_VOID: return False else: if side == 1: # tile = Image.load(r"../graphics/tile"+element+".png") if element == T_ACQUA: tile = py_image.load(r"../graphics/tile" + element + ".png") return tile if element.startswith(T_SABBIA): tile = py_image.load(r"../graphics/tile0_base.png") else: tile = py_image.load(r"../graphics/tile" + element + ".png") tile = tile.subsurface(0, (BLOCCOY / 2), BLOCCOX, BLOCCOY / 2) # left top width height # tile = tile.subsurface(0,side*(BLOCCOY/2),BLOCCOX,BLOCCOY/2)#left top width height else: tile = py_image.load(r"../graphics/tile" + element + ".png") if T_ACQUA == element: return False tile = tile.subsurface(0, 0, BLOCCOX, BLOCCOY / 2) # left top width height if element.startswith(T_SABBIA): tile = py_image.load(r"../graphics/tile" + T_SABBIA + "_top_" + element.split('_')[-1] + ".png") return tile
def __init__(self, level, size, player): State.State.__init__(self) G.play_amb() # loads image if not already if not CutScene.IMAGE: CutScene.IMAGE = PI.load("sprites/images/down.jpg").convert() self.image = CutScene.IMAGE # lets us know when to fade in self.fade_in = True # the x variable of the black shade surface self.dx = G.Globals.WIDTH # the x, y top left positions self.x = 0 self.y = 0 self.time = 0 # surface that shades over image to create sliding effect self.slide_surface = PG.Surface((self.dx, G.Globals.HEIGHT + G.Globals.HUD_HEIGHT)) self.level = level self.size = size self.player = player if level == 5: images = [] img_1 = PI.load("sprites/images/enter.jpg").convert() img_2 = PI.load("sprites/images/catfight.jpg").convert() images.append(img_1) images.append(img_2) G.Globals.STATE = StoryBoard.StoryBoard("story_texts/boss_text.txt", images)
def __init__(self, surf_width, surf_height, loc_x, loc_y, direction, volume): self.time = 0.0 self.volume = volume #set speed self.vx = ROCKET_VELOCITY self.surf_width = surf_width self.surf_height = surf_height #load image PS.Sprite.__init__(self) if not Virusbubble.IMAGE: self.IMAGE = PI.load("enemy_animation/virus/projectile.png").convert_alpha() self.IMAGE_NEG = PI.load("enemy_animation/virus/projectile_neg.png").convert_alpha() self.image = self.IMAGE self.rect = self.image.get_rect() #position rocket self.rect.centery = loc_y self.rect.centerx = loc_x self.sound = PM.Sound("Sounds/effects/virus_attack.ogg") self.sound.set_volume(self.volume) self.KILL = False self.moving_right = direction
def loadImage(self, imageName, alpha = True): imagePath = "../resrc/img/RPG/" + imageName + ".png" if alpha: img = load(imagePath).convert_alpha() else: img = load(imagePath).convert() return img
def __init__(self, direction, resourcePath): self.direction = direction if (self.direction == "up"): self.image = image.load(resourcePath + "img/uparrow.png") elif (self.direction == "down"): self.image = image.load(resourcePath + "img/downarrow.png") self.rect = Rect((0, 0), self.image.get_size())
def __init__(self): super(Level0, self).__init__() self.activeSprites = sprite.RenderClear() self.drawnSprites = [] self.npc = GameObject(image.load('User.png'), 100,50) self.activeSprites.add(self.npc) self.block1 = GameObject(image.load('platform.png'), 100, 400) self.activeSprites.add(self.block1); self.mousex = 0 self.mousey = 0 #The highest height our npc #can climb. If a the dY with a #point is higher than this, the #npc will just fall to his death self.MAX_HILL_HEIGHT = 3 self.toDrawRectTopLeft = (0,0) self.toDrawRectBottomRight = (0,0) self.drawing = False self.pts = [] print "Level 0 initialized."
def __init__(self,imagefile,soundfile,trgtimg,trgtsnd): self.image = scale(image.load(imagefile), SIZE).convert() self.fill = scale(image.load(BASE),SIZE).convert() self.sound = mixer.Sound(soundfile) self.trgtimg = trgtimg self.trgtsnd = trgtsnd self.result = [not(self.trgtimg),not(self.trgtsnd)]
def __init__(self, rect, surface, level): # how long the puddle will last before it disappears self.lifetime = self.set_life(level) # if not Trap.IMAGE: Trap.IMAGE = PI.load("FPGraphics/Food/IceCreamPuddle.png") \ .convert_alpha() Trap.static_image = Trap.IMAGE Trap.image = self.static_image # load animation images self.load_images() if not Puddle.IMAGE: Puddle.IMAGE = PI.load("FPGraphics/Food/IceCreamPuddle.png") \ .convert_alpha() self.static_image = Puddle.IMAGE self.image = self.static_image self.load_images() self.rect = rect self.x = self.rect.x self.y = self.rect.y self.dropped = False self.disappear = False self.set_anim_start() self.num_frames = 3 self.type = 'E' # initialize parent class Trap.__init__(self, surface, rect, self.type, 'E', self.lifetime)
def sup_load_images(self): SuperSlime.IMAGES = [] sheet = PI.load( "sprites/images/slime_sprite_sheet.png").convert_alpha() c_surface = PG.Surface((sheet.get_width(), sheet.get_height())).convert() c_surface.fill((150, 0, 150)) sheet.blit(c_surface, (0, 0), None, PG.BLEND_ADD) key = sheet.get_at((0, 0)) for y in range(4): for x in range(5): surface = PG.Surface((30, 20)).convert() surface.set_colorkey(key) surface.blit(sheet, (0, 0), (x * 30, y * 20, 30, 20)) SuperSlime.IMAGES.append(surface) SuperSlime.DEATH_IMAGES = [] sheet = PI.load( "sprites/images/slime_sprite_sheet_death.png").convert_alpha() c_surface = PG.Surface((sheet.get_width(), sheet.get_height())).convert() c_surface.fill((150, 0, 150)) sheet.blit(c_surface, (0, 0), None, PG.BLEND_ADD) key = sheet.get_at((0, 0)) for y in range(2): for x in range(4): surface = PG.Surface((30, 20)).convert() surface.set_colorkey(key) surface.blit(sheet, (0, 0), (x * 30, y * 20, 30, 20)) SuperSlime.DEATH_IMAGES.append(surface)
def loadTextures(self): self.main_wall_texture = image.load(os.path.join('data', 'walls.png')).convert() main_texture_size = self.main_wall_texture.get_size() self.textures_count = round(main_texture_size[1]/self.texture_size) self.texture_types_count = round(main_texture_size[0]/self.texture_size) self.wall_textures = [] for i in range(self.textures_count): texture_types = [] for t in range(self.texture_types_count-1): texture_type = [] x = t * self.texture_size y = i * self.texture_size for strip in range(self.texture_size): texture_type.append( self.main_wall_texture.subsurface((x, y, 1, self.texture_size)).convert() ) x = x + 1 texture_types.append(texture_type) self.wall_textures.append(texture_types) pass self.main_sprite_texture = image.load(os.path.join('data', 'sprites.png')).convert() self.sprites_count = self.main_sprite_texture.get_size()[0]//self.texture_size self.sprites = [] for i in range(self.sprites_count): sprite = [] x = i * self.texture_size y = 0 for strip in range(self.texture_size): sprite.append( self.main_sprite_texture.subsurface((x, y, 1, self.texture_size)).convert() ) x = x + 1 self.sprites.append(sprite) pass
def load_images(self): self.health = SHIPHEALTH self.IMAGES = [] self.NEG_IMAGES = [] walkr = "enemy_animation/spaceship/1.png" walkl = "enemy_animation/spaceship/-1.png" self.IMAGES.append(PI.load(walkr).convert_alpha()) self.NEG_IMAGES.append(PI.load(walkl).convert_alpha())
def setPic(self): if (self.color == 'black'): self.image = image.load("C:\Users\Colleen\Pictures\usedInSomething\BlackRook.png").convert_alpha() # convert alpha preserves per pixel transparency elif (self.color == 'white'): self.image = image.load("C:\Users\Colleen\Pictures\usedInSomething\whiteRook.png").convert_alpha() else: print "Color issue with Rook"
def _initNpcImage(self): leviathan = image.load("Res/leviathan.png") bahamut = image.load("Res/bahamut.png") ifrit = image.load("Res/ifrit.png") self.npc.append(leviathan) self.npc.append(bahamut) self.npc.append(ifrit)
def __init__(self, nr_of_rectangles): self.image_e = load("e.png") self.image_x = load("x.png") self.image_o = load("o.png") #TODO add the o image dimensions = Rectangle(0, 0, self.image_x.get_width(), self.image_x.get_height()) self.players_turn = 0 Board.__init__(self, nr_of_rectangles, dimensions)
def load_images(self): images = [] images.append(PI.load("FPGraphics/Title/TitleFood.png") .convert_alpha()) images.append(PI.load("FPGraphics/Title/TitlePlayer.png") .convert_alpha()) images.append(PI.load("FPGraphics/Title/TitleBG.png") .convert_alpha()) return images
def draw_walls(self, screen): wall_pic = image.load("assets/brick.png") unbreakable_wall_pic = image.load("assets/wall.png") for wall in self.wall_rects: if wall.wall.breakable: screen.blit(wall_pic, (wall.x, wall.y)) else: screen.blit(unbreakable_wall_pic, (wall.x, wall.y))
def load_images(self): sheetR = PI.load("FPGraphics/Food/IceCreamWalkRight.png").convert_alpha() sheetL = PI.load("FPGraphics/Food/IceCreamWalkLeft.png").convert_alpha() sheetF = PI.load("FPGraphics/Food/IceCreamWalkFront.png").convert_alpha() sheetB = PI.load("FPGraphics/Food/IceCreamWalkBack.png").convert_alpha() self.IMAGES_RIGHT = self.load_images_helper(self.IMAGES_RIGHT, sheetR) self.IMAGES_LEFT = self.load_images_helper(self.IMAGES_LEFT, sheetL) self.IMAGES_FRONT = self.load_images_helper(self.IMAGES_FRONT, sheetF) self.IMAGES_BACK = self.load_images_helper(self.IMAGES_BACK, sheetB)
def load_images(self, t): ##load hot pad images if t == 0: sheet = PI.load("FPGraphics/tiles/lv2Tiles/heatPadAnim.png").convert_alpha() ##load cold pad images if t == 1: sheet = PI.load("FPGraphics/tiles/lv3Tiles/coldPadAnim.png").convert_alpha() # else: self.IMAGES = self.load_images_helper(self.IMAGES, sheet)
def __init__(self, frame, path='./'): self.frame = frame self.stars = [ image.load(path + 'stars1.png').convert_alpha(), image.load(path + 'stars2.png').convert_alpha(), image.load(path + 'stars3.png').convert_alpha() ] self.offsets = [0, 0, 0] self.increments = [4, 2, 1]
def __init__(self,sx=0, sy=0): global attacktimeout, attack self.img = image.load(os.path.join("assets", "stone.png")).convert_alpha() self.keafriend = image.load(os.path.join("assets", "keacarrystone.png")).convert_alpha() self.x = sx self.y = sy self.grabed = False self.initial = True self.deliverymode = False
def load_images(self): self.health = DOGHEALTH self.IMAGES = [] self.NEG_IMAGES = [] for i in range (1, 6): walkr = "enemy_animation/sparky/" + str(i) + ".png" self.IMAGES.append(PI.load(walkr).convert_alpha()) walkl = "enemy_animation/sparky/-" + str(i) + ".png" self.NEG_IMAGES.append(PI.load(walkl).convert_alpha())
def load_images(): images_loaded = {} for png_file in [f[:-4] for f in listdir('../art') if f[-4:] == '.png']: images_loaded[png_file] = image.load( '../art/{}.png'.format(png_file)) for png_file in [f[:-4] for f in listdir('../art/biomes') if f[-4:] == '.png']: images_loaded[png_file] = image.load( '../art/biomes/{}.png'.format(png_file)).convert() return images_loaded
def add_path(new_path): if type(new_path) == tuple: for path in new_path: if type(new_path) == str: path = image.load(path).convert_alpha() enums.PATHS.append(path) else: if type(new_path) == str: new_path = image.load(new_path).convert_alpha() enums.PATHS.append(new_path)
def add_map(new_map): if type(new_map) == tuple: for nmap in new_map: if type(new_map) == str: nmap = image.load(nmap).convert_alpha() enums.MAPS.append(nmap) else: if type(new_map) == str: new_map = image.load(new_map).convert_alpha() enums.MAPS.append(new_map)
def init_terrain_mask(self): map_image_cache[TERRAIN_MASK_JUNGLE_HIGH_48] = image.load("image/mask/jungle_high_48.bmp").convert_alpha() map_image_cache[TERRAIN_MASK_JUNGLE_HIGH_48].set_colorkey((247,0,255)) map_image_cache[TERRAIN_MASK_JUNGLE_HIGH_64] = image.load("image/mask/jungle_high_64.bmp").convert_alpha() map_image_cache[TERRAIN_MASK_JUNGLE_HIGH_64].set_colorkey((247,0,255)) map_image_cache[TERRAIN_MASK_JUNGLE_LOW_48] = image.load("image/mask/jungle_low_48.bmp").convert_alpha() map_image_cache[TERRAIN_MASK_JUNGLE_LOW_48].set_colorkey((247,0,255)) map_image_cache[TERRAIN_MASK_JUNGLE_LOW_64] = image.load("image/mask/jungle_low_64.bmp").convert_alpha() map_image_cache[TERRAIN_MASK_JUNGLE_LOW_64].set_colorkey((247,0,255))
def __init__(self): State.State.__init__(self) PX.stop() """self.sound = PX.Sound("music/march.wav") self.sound.play()""" Intro.FONT = PF.Font("fonts/red_october.ttf", 18) img_1 = PI.load("sprites/images/intro1.jpg").convert() img_2 = PI.load("sprites/images/intro2.jpg").convert() img_3 = PI.load("sprites/images/intro3.jpg").convert() img_4 = PI.load("sprites/images/intro4.jpg").convert() img_5 = PI.load("sprites/images/instructions.jpg").convert() self.strings1 = [] self.strings2 = [] self.images = [] self.index = -1 self.time = 0 self.strings1.append("In a secret government lab, deep " + "within a deserted Russian town,") self.strings2.append("Scientists concocted experiments on" + " a large group of specimens.") self.strings1.append("Through a series of radioactive experiments" + " and countless injections") self.strings2.append("a powerful new age weapon was created.") self.strings1.append("A fierce creature: the product of science" + " and one's worst fears") self.strings2.append("was brought into this world as a dangerous " + "and sentient being.") self.strings1.append("It is now time for you to make your escape " + "from the lab,") self.strings2.append("for you are now, the Gamma Ray Kitten.") self.strings1.append("") self.strings2.append("") self.images.append(img_1) self.images.append(img_2) self.images.append(img_3) self.images.append(img_4) self.images.append(img_5) self.surf1 = Intro.FONT.render(self.strings1[self.index], True, (255, 0, 0)) self.surf2 = Intro.FONT.render(self.strings2[self.index], True, (255, 0, 0)) self.xy1 = ((400 - self.surf1.get_width() / 2, 500 - self.surf1.get_height())) self.xy2 = ((400 - self.surf2.get_width() / 2, 500 + self.surf2.get_height())) self.fadein = 0 self.fadeout = 255 self.fade_value = 100
def read_navdata(nav_file): navdata = openJSON(JSON.Navi + nav_file) navdata["sprite1"] = load(Sprite.Navi + navdata["sprite1"]) navdata["sprite2"] = load(Sprite.Navi + navdata["sprite2"]) for cannon in navdata["available_cannons"].values(): cannon["rel_pos"] = Vec2d(cannon["rel_pos"]['x'], cannon["rel_pos"]['y']) cannon["type"] = openJSON( JSON.Cannons + cannon["type"] + '.JSON') #reading cannon datas cannon["type"]["sprite1"] = load(Sprite.Cannons + cannon["type"]["sprite1"]) cannon["type"]["sprite2"] = load(Sprite.Cannons + cannon["type"]["sprite2"]) return navdata
def load_image(self, path, convert_alpha=False): """ Load an image file :param path: Path to the image in list format :param convert_alpha: *boolean* convert surfaces with convert_alpha() :return: surface """ if convert_alpha: return load(self.get_path(path)).convert_alpha() return load(self.get_path(path)).convert()
GREEN = (0, 255, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) ORANGE = (255, 128, 0) PURPLE = (255, 0, 255) CYAN = (0, 255, 255) BLACK = (0, 0, 0) StdFont = "Archivo-SemiBold" GameSpeed = 60 WindowWidth = 1024 WindowHeight = 768 #Load files once. playerimg = image.load(path.join('images', 'avatar.png')) facedownimg = image.load(path.join('images', 'cards', 'cardback.png')) cardvalues = [i.split(",") for i in open("values.txt").read().split("\n")] cardimages = {} botnames = [ "Terry", "Hannah", "Steve", "Mark", "James", "Jed", "Rachael", "Brian", "Chadwick", "Wolfgang" ] def loadCardImages(): for card in cardvalues: img_code = card[0] img = image.load(path.join('images', 'cards', img_code + '.png')) cardimages[img_code] = img
from pygame import image from util import randomPosition tree = image.load("tree.gif") class Tree(): def __init__(self): self.position = randomPosition() self.image = tree.convert() self._pos = (self.position["x"], self.position["y"]) self._class = "Tree"
def __load_sprite(self): self.__bonus = load('files/textures/icons/protect.png').convert_alpha() self._sprite = self.__bonus self.width = self._sprite.get_width() self.height = self._sprite.get_height()
def __init__(self, x, y): Sprite.__init__(self) self.image = load('images/Fire.png') self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y
class testBeacon(Decor): over = True sprite = image.load(path.join('src/gfx/test', 'testBeacon.png'))
import game_config as gc from animal import animal from time import sleep def find_index(x, y): row = y // gc.img_size col = x // gc.img_size index = row * gc.num_tiles_side + col return index pygame.init() game_window = pygame.display.set_mode((512, 512)) pygame.display.set_caption("rhyme_python_animal_game") match = image.load("other\matched.png") # game_window.blit(match, [0,0]) # display.flip() run = True tiles = [animal(i) for i in range(0, gc.num_tiles_total)] current_image = [] while run: current_events = event.get() for e in current_events: if e.type == pygame.QUIT: run = False if e.type == pygame.KEYDOWN: if e.key == pygame.K_ESCAPE: run = False
def draw(surface): img = image.load('../images/tiles.xpm') surface.blit(img, Rect((0, 0, 32, 32)), Rect((0, 0, 32, 32))) pygame.display.update()
# merge two images into one using Pygame Liblary from pygame import image, Rect maze = image.load('maze.png') player = image.load('player.png') maze.blit(player, Rect((32, 32, 64, 64)), Rect((0, 0, 32, 32))) image.save(maze, 'merged.png')
while (True): init() len_cm = int(size_check * len_check) len_aim = int(size_aim * len_check) global len_menu len_menu = int((len_check * (num_raw - 1) + 2 * len_frame) * 0.2) maxn_x = len_check * (num_line - 1) + 2 * len_frame maxn_y = len_check * (num_raw - 1) + 2 * len_frame + len_menu + len_check screen = set_mode((maxn_x, maxn_y)) set_caption("shudu Ver 0.1") background = load('resource/bg.jpg').convert_alpha() background = smoothscale(background, (maxn_x, maxn_y)) button_restart = myButton('resource/red_cm.png', 'resource/blue_cm.png', (int(maxn_x / 2), int(maxn_y - len_menu / 2))) button_set = myButton('resource/red_cm_set.png', 'resource/blue_cm_set.png', (int(maxn_x / 4), int(maxn_y - len_menu / 2))) button_retract = myButton( 'resource/red_cm_retract.png', 'resource/blue_cm_retract.png', (int(3 * maxn_x / 4), int(maxn_y - len_menu / 2))) bt = ['1'] bt_name = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] for i in range(1, 10): #print(i)
from pygame import image, mask, draw, Surface cross = image.load('data/cross.png') # a simple 3x3 cross ene = image.load('data/ene.png') # an "L" shape ele = image.load('data/ele.png') # an "n" shape # select the image here. chosen = cross mask_elem = mask.from_surface(chosen) chosen.fill((255, 0, 0)) coords = [] # this is the first part of the alogorithm. # it looks at the image-mask and gets all the valid vertices. # since the pixels are squares, each one has 4 vertices. # repeated vertices are ignored. for y in range(3): for x in range( 3): # I used "3" here because the images are 3x3px; for simplicity if mask_elem.get_at((x, y)): for dx, dy in [(x, y), (x + 1, y), (x, y + 1), (x + 1, y + 1)]: if (dx, dy) not in coords: coords.append((dx, dy)) vertex = coords[0] vertices = [] # this part analizes the vertices and puts them in order, to trace the perimeter of the figure. # It tries to go right from the start, then down, then left, then up to return to the original # start point. while len(coords):
def animate(self, direction, position, repeat, special_render_item, render_single_frame=None, finished=False): if not self.finished and not finished: if special_render_item and 'sound' in special_render_item: if self.sound_playing != sound_cache[ special_render_item['sound']]: self.sound_play_start = 9999999999 self.sound_playing = sound_cache[special_render_item['sound']] self.play_animation_sound( sound_cache[special_render_item['sound']]) else: if self.sound_playing != self.sound: self.sound_play_start = 9999999999 self.sound_playing = self.sound self.play_animation_sound(self.sound) self.cycletime += config.clock animation_size = len(self.image_list[direction]) if animation_size > 0: if self.cycletime > self.interval[self.render_idx]: self.cycletime = 0 if self.render_idx + 1 == animation_size: if repeat == -1: self.render_idx = (self.render_idx + 1) % animation_size elif self.repeat + 1 < repeat: self.render_idx = (self.render_idx + 1) % animation_size self.repeat += 1 elif self.repeat + 1 == repeat: self.repeat = 0 self.finish() else: self.render_idx = (self.render_idx + 1) % animation_size render_image = None if render_single_frame is not None: self.render_idx = render_single_frame if self.image_list[direction][self.render_idx] is not None: render_image = self.image_list[direction][ self.render_idx].copy() if finished: tmp = image.load("image/mask/finished.bmp").convert() render_image.blit(tmp, (0, 0), None, BLEND_RGBA_MULT) if special_render_item and 'mask' in special_render_item: pixel_array = PixelArray( map_image_cache[special_render_item['mask']]) render_image_pixel_array = PixelArray(render_image) for i in range(len(render_image_pixel_array)): for j in range(len(render_image_pixel_array[0])): if pixel_array[i][j] != map_image_cache[ special_render_item['mask']].map_rgb( 247, 0, 255): render_image_pixel_array[i][j] = Color( 247, 0, 255, 0) render_image = render_image.convert_alpha() render_image.set_colorkey(self.color_key) render_queue.append((0, render_image, position))
def DrawBackground(screen): background_image = image.load("Images/Battle/grass.png") screen.blit(background_image, (0, 0))
def playing(i): v = 1 color_change = n = 0 img_alpha_change = 1 m = 0 z = 10 # Play/pause x, y, size: ppx = 395 ppy = 655 pps = 50 # Next x, y, size: nx = 455 ny = 665 ns = 32 # Previous x, y, size: pvx = 350 pvy = 665 pvs = 32 # Booleans: playrun = True clicking = False nclicking = False pclicking = False pause = False pr = 10 seg = 0 minu = 0 mixer.init() mixer.music.load(songs[i]) mixer.music.play() som = mixer.Sound(songs[i]) song = som s = song.get_length() nn = 0 ppclicking = False # Loop da função: while playrun: mus_pos = mixer.music.get_pos() / 1000 mx1, my1 = pg.mouse.get_pos() rtx = rty = 0 rtsize = 40 # Mouse sobre o botão de return: if 0 < mx1 < 42 and 0 < my1 < 42: rtx = rty = - 2 rtsize = 47 return_button = transform.scale(image.load('./assets/return2.png'), (rtsize, rtsize)) # Mouse sobre play/pause: if 394 < mx1 < 446 and 654 < my1 < 706 and not ppclicking: ppx = 394 ppy = 654 pps = 52 else: ppx = 395 ppy = 655 pps = 50 play_icon = transform.scale(image.load('./assets/play.png'), (pps, pps)) pause_icon = transform.scale(image.load('./assets/pause.png'), (pps, pps)) previous_icon = transform.scale(image.load('./assets/previous.png'), (ns, ns)) # Mouse sobre o botão next: if 453 < mx1 < 487 and 663 < my1 < 697 and not nclicking: nx = 454 ny = 664 ns = 35 else: nx = 455 ny = 665 ns = 32 next_icon = transform.scale(image.load('./assets/next.png'), (ns, ns)) # Mouse sobre o botão previous: if 349 < mx1 < 383 and 663 < my1 < 697 and not pclicking: pvx = 349 pvy = 664 pvs = 35 else: pvx = 350 pvy = 665 pvs = 32 previous_icon = transform.scale(image.load('./assets/previous.png'), (pvs, pvs)) # Mouse sobre a bolinha azul: if pr - 20 < mx1 < pr + 20 and 698 < my1 < 720: m = 7 else: m = 0 for event1 in pg.event.get(): if event1.type == pg.QUIT: playrun = False if event1.type == MOUSEBUTTONDOWN: button_number1 = event1.button if button_number1 == 1: # Clicando no botão de return: if 10 < mx1 < 40 and 10 < my1 < 40: mixer.music.stop() pause = True playrun = False # Clicando na bolinha azul: if pr - 15 < mx1 < pr + 15 and 705 < my1 < 720: m = 8 clicking = True # Clicando na barra de progresso: elif pr + 15 < mx1 < 850 or 10 < mx1 < pr - 15: if 705 < my1 < 720: clicking = True # Clicando no play/pause: if 394 < mx1 < 449 and 654 < my1 < 708 and pr >= 849 and not clicking: mixer.music.stop() mixer.music.play() pr = 50 nn = 0 pause = False elif 394 < mx1 < 449 and 654 < my1 < 708 and pr < 849: ppclicking = True # Clicando no botão next: if 453 < mx1 < 485 and 663 < my1 < 697: nclicking = True # Clicando no botão previous: if 349 < mx1 < 383 and 663 < my1 < 697: pclicking = True # Soltando o clique: if event1.type == MOUSEBUTTONUP: button_number1 = event1.button if color_change >= 80 and button_number1 == 1 and clicking: clicking = False prt = pr - 14 if pr <= 10: pr = 10 mixer.music.play() pause = False if pr >= 849: mixer.music.stop() pr = 849 pause = True if mx1 <= 10: pr = 10 n = 0 if 10 < mx1 < 849: d = 840 / s n = prt / d nn = n - mus_pos mixer.music.set_pos(n) pr = mx1 - 4 pause = False elif ppclicking and pr < 849: ppclicking = False if not pause: mixer.music.pause() pause = True elif pause: mixer.music.unpause() mixer.music.set_pos(mus_pos) pause = False elif nclicking: nclicking = False pr -= pr mixer.music.unload() mixer.quit() i += 1 if i >= len(songs): i = 0 playrun = False playing(i) elif pclicking: pr -= pr mixer.music.unload() mixer.quit() i -= 1 if i < 0: i = len(songs) - 1 playrun = False playing(i) # Apertando teclas: if event1.type == KEYDOWN: key1 = pg.key.get_pressed() if key1[pg.K_RIGHT]: divi = 814 / s prt = pr - 10 pos_mus = prt / divi if pos_mus < s - 5: if pos_mus == s: mixer.music.stop() pause = True pr = 850 n += 5 pr += divi * 5 mixer.music.play(i, n) if key1[pg.K_LEFT]: pause = False prt = pr - 10 divi = 814 / s if pr > 10: n -= 5 if n < 0: n = 0 pr -= divi * 5 if pr < 10: pr = 10 mixer.music.play(i, n) if key1[pg.K_ESCAPE]: z -= 20 fade = 0 pause = True if not pause: if key1[pg.K_SPACE]: if pr >= 850: mixer.music.rewind() pr = 10 pause = False else: mixer.music.pause() pause = True elif pause: if key1[pg.K_SPACE]: mixer.music.unpause() pause = False if key1[pg.K_KP_PLUS] or key1[pg.K_UP]: v += 0.1 if v >= 1: v = 1 pg.mixer.music.set_volume(v) screen.blit(volume, (708, 650)) if key1[pg.K_KP_MINUS] or key1[pg.K_DOWN]: v -= 0.1 if v <= 0: v = 0 pg.mixer.music.set_volume(v) screen.blit(volume, (708, 650)) # Velocidade da bolinha azul: if ppclicking: pps = 50 ppx = 395 ppy = 655 if nclicking: nx = 455 ny = 665 ns = 32 if pclicking: pvx = 350 pvy = 665 pvs = 32 d = 840 / s prt = pr - 10 # Conversor do contador de tempo: if mus_pos + nn < s: pos_mus = mus_pos + nn if mus_pos <= 0: pos_mus = s seg = int(pos_mus) minu = int(pos_mus / 60) if seg >= minu * 60: seg -= minu * 60 if clicking: pr = mx1 - 4 m = 8 if pr > 850: pr = 850 elif pr < 10: pr = 10 elif not clicking and not pause: pr = ((mus_pos + nn) * d) + 10 if pr < 10: pr = 10 mixer.music.stop() mixer.music.play() if pr > 849: pr = 849 pause = True mixer.music.stop() # Variações de transparência: color_change += z img_alpha_change += 3.5 * z if img_alpha_change > 255: img_alpha_change = 255 if img_alpha_change <= 0: playrun = False mixer.quit() if color_change > 80: color_change = 80 if color_change < 0: color_change = 0 # Tela da música: rect1_size = (860, 45) rect2_size = (860, 41) transp = pg.Surface(rect1_size, pg.SRCALPHA) barra_transp = pg.Surface(rect2_size, pg.SRCALPHA) branco = (color_change * 1.8, color_change * 1.8, color_change * 1.8) volume = quicksand20.render(f'Volume {int(v * 100)}%', True, (color_change * 3, color_change * 3, color_change * 3)) azul_escuro = (0, 0, color_change * 1.8) azul_medio = (0, 0, color_change * 2) preto_transp = (0, 0, 0, color_change * 1.5) azul_escuro_transp = (0, 0, 50, color_change * 2.5) screen.fill((0, 0, 0)) # Retângulo grande preto transparente: pg.draw.rect(transp, azul_escuro_transp, transp.get_rect(), 0) # Capas dos álbuns: capa.set_alpha(img_alpha_change) screen.blit(capa, (- 700, 0)) pg.draw.rect(screen, (0, 0, 0), (0, 0, 860, 45)) screen.blit(transp, (0, 0)) # Retângulo azul: pg.draw.rect(barra_transp, azul_escuro_transp, barra_transp.get_rect(), 0) # Retângulo preto transparente: screen.blit(barra_transp, (0, 610)) # Títulos das músicas: dtext = 38 - tams_fontes[i] if dtext > 9: dtext = 9 screen.blit(t**s[i], (10, 605 + dtext)) # Barra de progresso branca: pg.draw.rect(screen, branco, (10, 710, 840, 3)) # Barra de progresso azul: pg.draw.rect(screen, azul_escuro, (10, 710, pr - 7, 3)) # Bolinha da barra de progresso: pg.draw.circle(screen, azul_medio, center=(pr, 710), radius=m) # Botão de voltar ao menu: screen.blit(return_button, (rtx, rty)) # Pause/play: if not pause: screen.blit(pause_icon, (ppx, ppy)) if pause: screen.blit(play_icon, (ppx, ppy)) # Próxima/anterior: screen.blit(next_icon, (nx, ny)) screen.blit(previous_icon, (pvx, pvy)) # Contador de tempo: contador = quicksand20n.render('{:0>2d}:{:0>2d}'.format(minu, seg), True, (255, 255, 255)) barra = quicksand20n.render('/', True, (255, 255, 255)) screen.blit(contador, (15, 675)) screen.blit(barra, (73, 675)) screen.blit(dur_mus[i], (90, 675)) pg.display.update()
import time import datetime import pygame as pg from pygame import mixer, image, display, transform from pygame.locals import * import multiprocessing as mp # Iniciando o pygame: pg.init() exit = Event() screen = display.set_mode((860, 720)) # Imagens: back = transform.scale(image.load('./assets/back.jpg'), (860, 720)) back2 = transform.scale(image.load('./assets/back.jpg'), (1060, 559)) player_icon = transform.scale(image.load('./assets/player_back.jpg'), (100, 100)) # Fontes dos textos: pg.font.init() quicksand80 = pg.font.SysFont("quicksand", 80) notomono35 = pg.font.SysFont("notomono", 35) notomono30_italic = pg.font.SysFont("notomono", 30, italic=True) quicksand22 = pg.font.SysFont("quicksand", 22) quicksand22b = pg.font.SysFont("quicksand", 22, bold=True) notomono22 = pg.font.SysFont("notomono", 22) quicksand20 = pg.font.SysFont("quicksand", 20, bold=True) quicksand20n = pg.font.SysFont("quicksand", 20) quicksand16 = pg.font.SysFont('quicksand', 16, italic=True)
def loadCardImages(): for card in cardvalues: img_code = card[0] img = image.load(path.join('images', 'cards', img_code + '.png')) cardimages[img_code] = img
def __init__(self, x, y, path, wname): self.path = path self.wname = wname self.image = Surface((width, height)) self.x = x self.y = y self.startpos = (x, y) self.onground = True self.xvel = 0 self.yvel = 0 self.hp = 20 self.hunger = 20 Player_load(self, path, wname) self.spawnpoint = (x, y) self.started = False self.stay_sprites = [transform.scale(load(path+"/resources/textures/glo/player/stay0.png"), (int(width*1.2), height)),\ transform.scale(load(path+"/resources/textures/glo/player/stay1.png"), (int(width*1.2), height)),\ transform.scale(load(path+"/resources/textures/glo/player/stay2.png"), (int(width*1.2), height)),\ transform.scale(load(path+"/resources/textures/glo/player/stay1.png"), (int(width*1.2), height))] self.stayr_sprites = [transform.scale(load(path+"/resources/textures/glo/player/stayr0.png"), (int(width*1.2), height)),\ transform.scale(load(path+"/resources/textures/glo/player/stayr1.png"), (int(width*1.2), height)),\ transform.scale(load(path+"/resources/textures/glo/player/stayr2.png"), (int(width*1.2), height)),\ transform.scale(load(path+"/resources/textures/glo/player/stayr1.png"), (int(width*1.2), height))] self.run_sprites = [transform.scale(load(path+"/resources/textures/glo/player/run0.png"), (int(width*1.2), height)),\ transform.scale(load(path+"/resources/textures/glo/player/run1.png"), (int(width*1.2), height))] self.runr_sprites = [transform.scale(load(path+"/resources/textures/glo/player/runr0.png"), (int(width*1.2), height)),\ transform.scale(load(path+"/resources/textures/glo/player/runr1.png"), (int(width*1.2), height))] self.stay_anim = Animation(self.stay_sprites, 500) self.stayr_anim = Animation(self.stayr_sprites, 500) self.run_anim = Animation(self.run_sprites, 200) self.runr_anim = Animation(self.runr_sprites, 200) self.dt = 0 self.clock = time.Clock() self.right = False self.air = 20 self.pink = Surface((width, height)) self.pink.fill(PINK) self.jump_delay = 0 self.timers = { "hunger_hp": 0, "air_hp": 0, "air": 0, "hunger": 0, "hp_hunger_plus": 0, }
from pygame import display, event, image from time import sleep from animal import Animal def find_index_from_xy(x, y): row = y // gc.IMAGE_SIZE col = x // gc.IMAGE_SIZE index = row * gc.NUM_TILES_SIDE + col return row, col, index pygame.init() display.set_caption('My Game') screen = display.set_mode((gc.SCREEN_SIZE, gc.SCREEN_SIZE)) matched = image.load('other_assets/matched.png') running = True tiles = [Animal(i) for i in range(0, gc.NUM_TILES_TOTAL)] current_images_displayed = [] while running: current_events = event.get() for e in current_events: if e.type == pygame.QUIT: running = False if e.type == pygame.KEYDOWN: if e.key == pygame.K_ESCAPE: running = False
class FlappyBird(object): init() fps_clock = time.Clock() screen_width = 288 screen_height = 512 screen = display.set_mode((screen_width, screen_height)) display.set_caption('Flappy Bird') base_image = load(os.path.join(base_path, 'assets/base.png')).convert_alpha() background_image = load( os.path.join(base_path, 'assets/background-black.png')).convert() pipe_images = [ rotate( load(os.path.join(base_path, 'assets/pipe-green.png')).convert_alpha(), 180), load(os.path.join(base_path, 'assets/pipe-green.png')).convert_alpha() ] bird_images = [ load(os.path.join(base_path, 'assets/redbird-upflap.png')).convert_alpha(), load(os.path.join(base_path, 'assets/redbird-midflap.png')).convert_alpha(), load(os.path.join(base_path, 'assets/redbird-downflap.png')).convert_alpha() ] bird_hitmask = [pixels_alpha(image).astype(bool) for image in bird_images] pipe_hitmask = [pixels_alpha(image).astype(bool) for image in pipe_images] fps = 100 pipe_gap_size = 100 pipe_velocity_x = -4 # parameters for bird min_velocity_y = -8 max_velocity_y = 10 downward_speed = 2 upward_speed = -9 bird_index_generator = cycle([0, 1, 2, 1]) def __init__(self): self.iter = self.bird_index = self.score = 0 self.bird_width = self.bird_images[0].get_width() self.bird_height = self.bird_images[0].get_height() self.pipe_width = self.pipe_images[0].get_width() self.pipe_height = self.pipe_images[0].get_height() self.bird_x = int(self.screen_width / 5) self.bird_y = int((self.screen_height - self.bird_height) / 2) self.base_x = 0 self.base_y = self.screen_height * 0.79 self.base_shift = self.base_image.get_width( ) - self.background_image.get_width() pipes = [self.generate_pipe(), self.generate_pipe()] pipes[0]["x_upper"] = pipes[0]["x_lower"] = self.screen_width pipes[1]["x_upper"] = pipes[1]["x_lower"] = self.screen_width * 1.5 self.pipes = pipes self.current_velocity_y = 0 self.is_flapped = False def generate_pipe(self): x = self.screen_width + 10 gap_y = randint(2, 10) * 10 + int(self.base_y / 5) return { "x_upper": x, "y_upper": gap_y - self.pipe_height, "x_lower": x, "y_lower": gap_y + self.pipe_gap_size } def is_collided(self): # Check if the bird touch ground if self.bird_height + self.bird_y + 1 >= self.base_y: return True bird_bbox = Rect(self.bird_x, self.bird_y, self.bird_width, self.bird_height) pipe_boxes = [] for pipe in self.pipes: pipe_boxes.append( Rect(pipe["x_upper"], pipe["y_upper"], self.pipe_width, self.pipe_height)) pipe_boxes.append( Rect(pipe["x_lower"], pipe["y_lower"], self.pipe_width, self.pipe_height)) # Check if the bird's bounding box overlaps to the bounding box of any pipe if bird_bbox.collidelist(pipe_boxes) == -1: return False for i in range(2): cropped_bbox = bird_bbox.clip(pipe_boxes[i]) min_x1 = cropped_bbox.x - bird_bbox.x min_y1 = cropped_bbox.y - bird_bbox.y min_x2 = cropped_bbox.x - pipe_boxes[i].x min_y2 = cropped_bbox.y - pipe_boxes[i].y if np.any(self.bird_hitmask[ self.bird_index][min_x1:min_x1 + cropped_bbox.width, min_y1:min_y1 + cropped_bbox.height] * self.pipe_hitmask[i][min_x2:min_x2 + cropped_bbox.width, min_y2:min_y2 + cropped_bbox.height]): return True return False def next_frame(self, action, text=''): pump() reward = 1 terminal = False # Check input action if action == 0: # 0 means flap self.current_velocity_y = self.upward_speed self.is_flapped = True # Update score bird_center_x = self.bird_x + self.bird_width / 2 for pipe in self.pipes: pipe_center_x = pipe["x_upper"] + self.pipe_width / 2 if pipe_center_x < bird_center_x < pipe_center_x + 5: self.score += 1 break # get detal_x, detal_y for pipe in self.pipes: if self.bird_x < pipe["x_lower"] + self.pipe_width: detal_x = pipe['x_lower'] + self.pipe_width - self.bird_x detal_y = pipe['y_lower'] - self.bird_y + self.bird_height # a triangle points = ((self.bird_x, self.bird_y + self.bird_height), (pipe['x_lower'] + self.pipe_width, pipe['y_lower']), (self.bird_x, pipe['y_lower'])) break # Update index and iteration if (self.iter + 1) % 3 == 0: self.bird_index = next(self.bird_index_generator) self.iter = 0 self.base_x = -((-self.base_x + 100) % self.base_shift) # Update bird's position if self.current_velocity_y < self.max_velocity_y and not self.is_flapped: self.current_velocity_y += self.downward_speed if self.is_flapped: self.is_flapped = False self.bird_y += min( self.current_velocity_y, self.bird_y - self.current_velocity_y - self.bird_height) if self.bird_y < 0: self.bird_y = 0 # Update pipes' position for pipe in self.pipes: pipe["x_upper"] += self.pipe_velocity_x pipe["x_lower"] += self.pipe_velocity_x # Update pipes if 0 < self.pipes[0]["x_lower"] < 5: self.pipes.append(self.generate_pipe()) if self.pipes[0]["x_lower"] < -self.pipe_width: del self.pipes[0] if self.is_collided(): terminal = True reward = -1000 self.__init__() # show info font = pygame.font.Font('freesansbold.ttf', 20) info = font.render(text, False, (255, 200, 10)) # Draw everything self.screen.blit(self.background_image, (0, 0)) self.screen.blit(self.base_image, (self.base_x, self.base_y)) self.screen.blit(self.bird_images[self.bird_index], (self.bird_x, self.bird_y)) for pipe in self.pipes: self.screen.blit(self.pipe_images[0], (pipe["x_upper"], pipe["y_upper"])) self.screen.blit(self.pipe_images[1], (pipe["x_lower"], pipe["y_lower"])) self.screen.blit(info, (0, 100)) pygame.draw.polygon(display.get_surface(), (255, 0, 0), points, width=1) image = array3d(display.get_surface()) display.update() self.fps_clock.tick(self.fps) return image, reward, terminal, self.score, str( (int(detal_x / 4), int(detal_y / 4)))
def init_screen1(self): # Background self.background1 = image.load('./Media/Images/background2.jpg')
import os from pygame.image import load crossimg = load(os.path.join("images", "CROSS.png")) noughtimg = load(os.path.join("images", "NOUGHT.png"))
def fire(x, y, surface): """Fires crystal at x and y by next render""" ammo = image.load("assets/crystal.png") surface.blit(ammo, x, y)
def house(self): self.surface = image.load(self.resourcePath + "img/house.png") self.eventName = "house"
def on_init(self): self.image = image.load(self.__IMAGE_FILE__).convert_alpha() self.rect = self.image.get_rect(topleft=(self.x, self.y))
def __init__(self, img): Sprite.__init__(self) self.surface = Surface((1280, 720), SRCALPHA) self.image = image.load(img).convert_alpha() self.surface.blit(self.image, (0, 0))
draw.line(folder_image, (255, 255, 255, 255), [3, 15], [3, 1], 2) draw.arc(folder_image, (255, 255, 255, 255), [0, 1, 13, 15], 0, pi / 1.9, 2) draw.arc(folder_image, (255, 255, 255, 255), [0, 1, 13, 15], 3 * pi / 2, 2 * pi, 2) return file_image, folder_image else: from directories import getDataFile if sys.platform in ('darwin', 'linux2'): print("*** MCEDIT DEBUG: file_dialog:", __file__) print("*** MCEDIT DEBUG: directory:", os.path.dirname(__file__)) print("*** MCEDIT DEBUG: current directory:", os.getcwd()) try: file_image = image.load('file.png') folder_image = image.load('folder.png') except Exception as e: print("MCEDIT DEBUG: Could not load file dialog images.") print(e) from pygame import draw, Surface from pygame.locals import SRCALPHA from math import pi file_image = Surface((16, 16), SRCALPHA) file_image.fill((0, 0, 0, 0)) draw.lines(file_image, (255, 255, 255, 255), False, [[3, 15], [3, 1], [13, 1]], 2) draw.line(file_image, (255, 255, 255, 255), [3, 7], [10, 7], 2) folder_image = Surface((16, 16), SRCALPHA) folder_image.fill((0, 0, 0, 0))
def upload(self, img): self.image = image.load(img).convert_alpha() self.surface.fill(Color("black")) self.surface.blit(self.image, (0, 0))
from pygame import display, event, image from animal import Animal from time import sleep def find_index(x, y): row = y // gc.IMAGE_SIZE col = x // gc.IMAGE_SIZE index = row * gc.NUM_TILES_SIDE + col return index pygame.init() display.set_caption("My Game") screen = display.set_mode((512, 512)) matched = image.load('More_assets/check.png') running = True tiles = [Animal(i) for i in range(0, gc.NUM_TILES_TOTAL)] current_images = [] while running: current_events = event.get() for e in current_events: if e.type == pygame.QUIT: running = False if e.type == pygame.KEYDOWN: if e.key == pygame.K_ESCAPE: running = False
def __load_icon(self): self._sprite = load('files/textures/icons/health.png').convert_alpha() self.icon_width = self._sprite.get_width() self.icon_height = self._sprite.get_height()
import pygame from pygame.image import load from pygame.transform import scale neighbours = [] neighbours.append(scale(load("./images/0.png"), (25, 25))) neighbours.append(scale(load("./images/1.png"), (25, 25))) neighbours.append(scale(load("./images/2.png"), (25, 25))) neighbours.append(scale(load("./images/3.png"), (25, 25))) neighbours.append(scale(load("./images/4.png"), (25, 25))) neighbours.append(scale(load("./images/5.png"), (25, 25))) neighbours.append(scale(load("./images/6.png"), (25, 25))) neighbours.append(scale(load("./images/7.png"), (25, 25))) neighbours.append(scale(load("./images/8.png"), (25, 25))) hidden = scale(load("./images/hidden.png"), (25, 25)) flagged = scale(load("./images/flagged.png"), (25, 25)) bomb = scale(load("./images/bomb.png"), (25, 25))
def render_image(surface: Surface, coordinates: tuple[int, int], image_name: str): loaded_image = image.load(image_name) surface.blit(loaded_image, (coordinates[1] * Dimension.BRICK_SIZE, coordinates[0] * Dimension.BRICK_SIZE))