def start_resultmode(result, money): global all_sprites, resultmode_fon, resultmode_money_group, resultmode_score_group, resultmode_total_group global resultmode_menu_button, resultmode_return_button, resultmode_bonus, finish pygame.mixer.music.stop() finish.play() all_sprites = Group() resultmode_fon = Sprite() resultmode_fon.image = pygame.image.load( 'data/Images/game_over_stuff/gameover.png') resultmode_fon.rect = resultmode_fon.image.get_rect() resultmode_fon.rect.x = 182 resultmode_fon.rect.y = 50 all_sprites.add(resultmode_fon) resultmode_menu_button = Sprite() resultmode_menu_button.image = pygame.image.load( 'data/Images/game_over_stuff/menu button.png') resultmode_menu_button.rect = resultmode_menu_button.image.get_rect() resultmode_menu_button.rect.x = 182 + 45 resultmode_menu_button.rect.y = 470 all_sprites.add(resultmode_menu_button) resultmode_return_button = Sprite() resultmode_return_button.image = pygame.image.load( 'data/Images/game_over_stuff/return button.png') resultmode_return_button.rect = resultmode_return_button.image.get_rect() resultmode_return_button.rect.x = 400 resultmode_return_button.rect.y = 470 all_sprites.add(resultmode_return_button) all_sprites.draw(main_screen) resultmode_score_group = Group() transform_number(result, resultmode_score_group, (175 + 182, 205)) resultmode_score_group.draw(main_screen) resultmode_money_group = Group() x = transform_number( str(money) + '+', resultmode_money_group, (150 + 182, 290)) resultmode_money_group.draw(main_screen) bonus = int(result * 0.02) resultmode_bonus = Group() transform_number(bonus, resultmode_bonus, (x, 290)) resultmode_bonus.draw(main_screen) resultmode_total_group = Group() transform_number(money + bonus, resultmode_total_group, (150 + 182, 395)) resultmode_total_group.draw(main_screen) pygame.display.flip() if data['high score'] < result: data['high score'] = result data['money'] += money + bonus
def render_center_info(board_render): center_info_surface = Surface((250, 250)) match = board_render.match group = LayeredUpdates() # Background info_rect = Rect(0, 0, 250, 250) info_rect.center = board_render.surface.get_rect().center pygame.draw.rect(center_info_surface, (0, 0, 0), info_rect) current_path = os.path.dirname(os.path.realpath(__file__)) font_path = os.path.join( current_path, "..", "..", "resources", "fonts", "SourceSans3-Semibold.ttf" ) font = Font(font_path, 30) large_font = Font(font_path, 42) # Round Title round_text = "{} {}".format("East" if match.east_prevalent else "South", match.round_number) round_surface = font.render(round_text, True, (255, 255, 255)) round_sprite = Sprite() round_sprite.image = round_surface round_sprite.rect = round_surface.get_rect() round_sprite.rect.center = info_rect.center round_sprite.rect.y -= (round_surface.get_rect().height // 2) round_sprite.layer = 1 group.add(round_sprite) # Tiles Left in Wall tile_count_surface = large_font.render(str(len(match.current_board.wall)), True, (255, 255, 255)) wall_remaining_sprite = Sprite() wall_remaining_sprite.image = tile_count_surface wall_remaining_sprite.rect = tile_count_surface.get_rect() wall_remaining_sprite.rect.center = info_rect.center wall_remaining_sprite.rect.y += (tile_count_surface.get_rect().height // 3) wall_remaining_sprite.layer = 1 group.add(wall_remaining_sprite) # Wind Markers create_wind_markers(match, info_rect, group) # Turn Marker create_turn_marker(match, info_rect, group) # Riichi Markers create_riichi_markers(match, info_rect, group) background_sprite = Sprite() background_sprite.rect = info_rect background_sprite.image = center_info_surface background_sprite.layer = 0 group.add(background_sprite) return group
def create_turn_marker(board, parent_rect, group): MARKER_OFFSET = 20 MARKER_WIDTH = 5 current_turn = board.current_board.current_turn if current_turn % 2 == 0: marker_size = (parent_rect.width - MARKER_OFFSET, MARKER_WIDTH) else: marker_size = (MARKER_WIDTH, parent_rect.width - MARKER_OFFSET) marker_size_half = (marker_size[0] / 2, marker_size[1] / 2) parent_half_width = parent_rect.width / 2 parent_half_height = parent_rect.height / 2 SEAT_OFFSETS = [ (0, parent_half_height - marker_size_half[1]), (parent_half_width - marker_size_half[0], 0), (0, -parent_half_height + marker_size_half[1]), (-parent_half_width + marker_size_half[0], 0), ] turn_marker_surface = Surface(marker_size) turn_marker_surface.fill((255, 255, 255)) sprite = Sprite() sprite.rect = turn_marker_surface.get_rect() sprite.image = turn_marker_surface sprite.rect.center = parent_rect.center sprite.rect.x += SEAT_OFFSETS[current_turn][0] sprite.rect.y += SEAT_OFFSETS[current_turn][1] sprite.layer = 2 group.add(sprite)
def select(self): self.selected = True select = Sprite() select.image = pygame.image.load("images/Selected.png").convert_alpha() select.rect = self.rect select._layer = 5 self.add(select)
def mark(self): self.marked = True mark = Sprite() mark.image = pygame.image.load("images/Mark.png").convert_alpha() mark.rect = self.rect mark._layer = 4 self.add(mark)
def __init__(self, tile, camera, wx=0, wy=0, color=Color(255, 255, 255)): self.size = TileService.size GameObject.__init__(self, self.size, self.size, wx, wy) sprite = Sprite() sprite.image = TileService.getTile(tile, color) sprite.rect = (wx, wy, self.size, self.size) self.addSprites(sprite, camera)
def prep_lives(self): for x in range(self.stats.lives_left): temp = ImageRect(self.screen, "pac_man_right_1", 18, 18) life = Sprite() life.image = temp.image temp.rect.x = x * 18 temp.rect.bottom = self.screen_rect.bottom - 1 life.rect = temp.rect self.lives.add(life)
def create_grid(self, layer_id, group): layer_level = self.mapa_atual["layers"][layer_id] index_item = -1 for celula in layer_level["grid"]: index_item += 1 if celula == '0': continue y = index_item // layer_level["gridCellsY"] x = index_item % layer_level["gridCellsX"] celula_bloco = Sprite(group) celula_bloco.image = scale( self.tilemap_level.clip_sprite(0, 0, 16, 16), (32, 32)) celula_bloco.rect = Rect(x * 32, y * 32, 32, 32)
def render_bot_icons(board_render): ICON_SIZE = (50, 50) group = LayeredUpdates() SEAT_POS = [ None, (board_render.surface.get_width() - ICON_SIZE[0] - 10, 80), (460 - ICON_SIZE[0] - 10, 10), (10, 80) ] game_view = board_render.match.game_manager.get_active_view() icon_cache = game_view.bot_icon_cache ais = game_view.ai_list ai_icons = [] dud_ai_icon = pygame.Surface(ICON_SIZE, pygame.SRCALPHA) load_image_resource("dudB.png", dud_ai_icon, size=ICON_SIZE) for i in range(4): for icon in icon_cache: if icon['ai'] == ais[i]: surface = pygame.Surface(ICON_SIZE, pygame.SRCALPHA) load_image_resource(icon['icon'], surface, size=ICON_SIZE) ai_icons += [surface] break is_story_mode = hasattr(game_view, "match_dict") for seat in range(4): if seat == 0: continue sprite = Sprite() sprite.rect = (SEAT_POS[seat], ICON_SIZE) sprite.layer = 0 if is_story_mode and seat != 2: sprite.image = dud_ai_icon else: sprite.image = ai_icons[seat] group.add(sprite) return group
def create_wind_markers(match, parent_rect, group): current_path = os.path.dirname(os.path.realpath(__file__)) font_path = os.path.join( current_path, "..", "..", "resources", "fonts", "SourceSans3-Semibold.ttf" ) font = Font(font_path, 40) MARKER_SIZE = (40, 40) MARKER_SIZE_HALF = (MARKER_SIZE[0] / 2, MARKER_SIZE[1] / 2) MARKER_OFFSET = 40 parent_half_width = parent_rect.width / 2 parent_half_height = parent_rect.height / 2 SEAT_OFFSETS = [ (0, parent_half_height - MARKER_SIZE_HALF[1] - MARKER_OFFSET), (parent_half_width - MARKER_SIZE_HALF[0] - MARKER_OFFSET, 0), (0, -parent_half_height + MARKER_SIZE_HALF[1] + MARKER_OFFSET), (-parent_half_width + MARKER_SIZE_HALF[0] + MARKER_OFFSET, 0), ] WIND_ORDERS = [ ["E", "S", "W", "N"], ["N", "E", "S", "W"], ["W", "N", "E", "S"], ["S", "W", "N", "E"], ] current_east_seat = match.current_board.current_dealer wind_order = WIND_ORDERS[current_east_seat] for i in range(4): wind = wind_order[i] background_surface = Surface(MARKER_SIZE) if i == current_east_seat: background_color = (255, 0, 0) else: background_color = (100, 100, 100) background_surface.fill(background_color) font_surface = font.render(wind, True, (255, 255, 255)) font_width, font_height = font.size(wind) background_surface.blit( font_surface, ((MARKER_SIZE[0] - font_width) / 2, (MARKER_SIZE[1] - font_height) / 2), ) sprite = Sprite() sprite.rect = background_surface.get_rect() sprite.image = background_surface sprite.rect.center = parent_rect.center sprite.rect.x += SEAT_OFFSETS[i][0] sprite.rect.y += SEAT_OFFSETS[i][1] sprite.layer = 2 group.add(sprite)
def start_menumode(): global fon, menumode_start_btn, menumode_info_btn, menumode_shop_btn, jar, all_sprites, process_mode, menumode_money_sprites global menumode_high_score_sprites, background_music_playing process_mode = 'menu' fon = pygame.transform.scale( pygame.image.load('data/images/menu/main_menu.png'), (width, height)) main_screen.blit(fon, (0, 0)) menumode_start_btn = StartButton() menumode_info_btn = InfoButton() menumode_shop_btn = ShopButton() jar = MenuJar() all_sprites = Group() all_sprites.add(menumode_start_btn) all_sprites.add(menumode_info_btn) all_sprites.add(menumode_shop_btn) all_sprites.add(jar) menumode_money_sprites = Group() transform_number(data['money'], menumode_money_sprites, (90, 20)) menumode_money_sprites.draw(main_screen) menumode_high_score_sprites = Group() x = 1000 - 25 * (len(str(data['high score'])) + 1) transform_number(data['high score'], menumode_high_score_sprites, (x, 20)) menumode_high_score_sprites.draw(main_screen) high_score = Sprite() high_score.image = pygame.image.load('data/Images/menu/high_score.png') high_score.mask = pygame.mask.from_surface(high_score.image) high_score.rect = high_score.image.get_rect() high_score.mask = pygame.mask.from_surface(high_score.image) high_score.rect.x = 760 - 25 * (len(str(data['high score'])) - 1) high_score.rect.y = 20 all_sprites.add(high_score) all_sprites.draw(main_screen) pygame.display.flip() if not background_music_playing: pygame.mixer.music.load('data/Music/Background.mp3') pygame.mixer.music.play(-1) background_music_playing = True
def create_riichi_markers(match, parent_rect, group): MARKER_OFFSET = 60 MARKER_Y_OFFSET = 10 MARKER_WIDTH = 15 i = -1 for player in match.players: i += 1 if not player.riichi_declared: continue if i % 2 == 0: marker_size = (parent_rect.width - MARKER_OFFSET, MARKER_WIDTH) else: marker_size = (MARKER_WIDTH, parent_rect.width - MARKER_OFFSET) marker_size_half = (marker_size[0] / 2, marker_size[1] / 2) parent_half_width = parent_rect.width / 2 parent_half_height = parent_rect.height / 2 SEAT_OFFSETS = [ (0, parent_half_height - marker_size_half[1] - MARKER_Y_OFFSET), (parent_half_width - marker_size_half[0] - MARKER_Y_OFFSET, 0), (0, -parent_half_height + marker_size_half[1] + MARKER_Y_OFFSET), (-parent_half_width + marker_size_half[0] + MARKER_Y_OFFSET, 0), ] riichi_marker_surface = Surface(marker_size) marker_rect = riichi_marker_surface.get_rect() riichi_marker_surface.fill((255, 255, 255)) pygame.draw.circle( riichi_marker_surface, (255, 0, 0), (marker_rect.width / 2, marker_rect.height / 2), 5, ) sprite = Sprite() sprite.rect = marker_rect sprite.image = riichi_marker_surface sprite.rect.center = parent_rect.center sprite.rect.x += SEAT_OFFSETS[i][0] sprite.rect.y += SEAT_OFFSETS[i][1] sprite.layer = 2 group.add(sprite)
def __init__(self, tile, camera, wx=0, wy=0, color=Color(255,255,255)): self.size = TileService.size GameObject.__init__(self, self.size, self.size, wx, wy) sprite = Sprite() sprite.image = TileService.getTile(tile, color) sprite.rect = ( wx, wy, self.size, self.size ) self.addSprites(sprite, camera) Keyboard.on(Keyboard.keymap['TICK'], self.passTurn, CHARACTER_INPUT_GROUP) Keyboard.on(Keyboard.keymap['MOVE_UP'], partial(self.moveCharacter,0,-1*self.size), CHARACTER_INPUT_GROUP); Keyboard.on(Keyboard.keymap['MOVE_RIGHT'], partial(self.moveCharacter,1*self.size,0), CHARACTER_INPUT_GROUP); Keyboard.on(Keyboard.keymap['MOVE_LEFT'], partial(self.moveCharacter,-1*self.size,0), CHARACTER_INPUT_GROUP); Keyboard.on(Keyboard.keymap['MOVE_DOWN'], partial(self.moveCharacter,0,1*self.size), CHARACTER_INPUT_GROUP); Keyboard.on(Keyboard.keymap['MOVE_UP_RIGHT'], partial(self.moveCharacter,1*self.size,-1*self.size), CHARACTER_INPUT_GROUP); Keyboard.on(Keyboard.keymap['MOVE_UP_LEFT'], partial(self.moveCharacter,-1*self.size,-1*self.size), CHARACTER_INPUT_GROUP); Keyboard.on(Keyboard.keymap['MOVE_DOWN_RIGHT'], partial(self.moveCharacter,1*self.size,1*self.size), CHARACTER_INPUT_GROUP); Keyboard.on(Keyboard.keymap['MOVE_DOWN_LEFT'], partial(self.moveCharacter,-1*self.size,1*self.size), CHARACTER_INPUT_GROUP);
def collapse_layer(old_layer, new_layer, num_tiles=(2, 2)): """Collapse a single layer by joining num_tiles into one tile. A new layer is returned. The old_layer argument is the layer to process. The new_layer argument is the layer to build. The num_tiles argument is a tuple representing the number of tiles in the X and Y axes to join. If a map area is sparse (fewer tiles than num_tiles[0] * num_tiles[1]) the tiles will be kept as they are. If tiles with different characteristics are joined, the results can be unexpected. These characteristics include some flags, depth, colorkey. This can be avoided by pre-processing the map to convert all images so they have compatible characteristics. """ from pygame.sprite import Sprite from gummworld2 import Vec2d # New layer dimensions. num_tiles = Vec2d(num_tiles) tw, th = (old_layer.tile_width, old_layer.tile_height) * num_tiles mw, mh = (old_layer.width, old_layer.height) // num_tiles if mw * num_tiles.x != old_layer.pixel_width: mw += 1 if mh * num_tiles.y != old_layer.pixel_height: mh += 1 # Poke the right values into new_layer. cell_size = max(tw, th) * 2 new_layer.objects = spatialhash.SpatialHash(cell_size) new_layer.width = mw new_layer.height = mh new_layer.tile_width = tw new_layer.tile_height = th # Grab groups of map sprites, joining them into a single larger image. query_rect = pygame.Rect(0, 0, tw - 1, th - 1) for y in range(0, mh * th, th): for x in range(0, mw * tw, tw): query_rect.topleft = x, y sprites = old_layer.objects.intersect_entities(query_rect) if len(sprites) != num_tiles.x * num_tiles.y: for s in sprites: new_layer.add(s) continue # If sprite images have different characteristics, they cannot be # reliably collapsed. In which case, keep them as-is. # incompatible = False image = sprites[0].image flags = image.get_flags() ^ pygame.SRCALPHA colorkey = image.get_colorkey() depth = image.get_bitsize() # This is probably too restrictive. However, some combinations of tiles may # give funky results. # all_details = (flags,colorkey,depth) # for s in sprites[1:]: # if all_details != ( # s.image.get_flags(), # s.image.get_colorkey(), # s.image.get_bitsize(), # ): # incompatible = True # if incompatible: # print('collapse_layer: incompatible image characteristics') # for s in sprites: # new_layer.add(s) # continue # Make a new sprite. new_sprite = Sprite() new_sprite.rect = sprites[0].rect.unionall([s.rect for s in sprites[1:]]) new_sprite.rect.topleft = x, y new_sprite.image = pygame.surface.Surface(new_sprite.rect.size, flags, depth) if colorkey: new_sprite.image.set_colorkey(colorkey) # Blit (x,y) tile and neighboring tiles to right and lower... left = reduce(min, [s.rect.x for s in sprites]) top = reduce(min, [s.rect.y for s in sprites]) for sprite in sprites: p = sprite.rect.x - left, sprite.rect.y - top new_sprite.image.blit(sprite.image.convert(depth, flags), p) new_layer.add(new_sprite) return new_layer
def jump(self): print("I jumped...") # init pygame and create window pygame.init() # init sound mixer pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("A game that doesn't work") clock = pygame.time.Clock() all_sprites = pygame.sprite.Group() player = Player() # player2 = Player() testSprite = Sprite() testSprite.image = pygame.Surface((50,50)) testSprite.image.fill(GREEN) testSprite.rect = testSprite.image.get_rect() testSprite.rect.center = (WIDTH / 2, HEIGHT / 2) # all_sprites.add(player) # all_sprites.add(player2) # all_sprites.add(testSprite) for i in range(0,1): i = Player() i.rect[0] = random.randint(0,WIDTH) i.rect[1] = random.randint(0,HEIGHT) all_sprites.add(i) class Enemy(Sprite): # sprite for enemy
def start_gameplay(): global all_sprites, background, jar, process_mode, bombs, bomb_type, gameplay_time global gameplay_score_counter, gameplay_bombs_counter, gameplay_money_counter, gameplay_health_group global gameplay_score, gameplay_bombs_number, gameplay_bomb_symbol, gameplay_money global gameplay_money_symbol, gameplay_health, gameplay_pause, clock, gameplay_enemies global gameplay_enemies_period, gameplay_wall, background_music_playing, gameplay_clouds process_mode = 'game' all_sprites = Group() clock = pygame.time.Clock() background = Background() all_sprites.add(background) jar = Jar(1) all_sprites.add(jar) bombs = Group() bomb_type = 'apple' gameplay_score = 0 gameplay_score_counter = Group() transform_number(gameplay_score, gameplay_score_counter, (3, 3)) gameplay_score_counter.draw(main_screen) gameplay_bombs_number = 500 gameplay_bomb_symbol = BombSymbol() all_sprites.add(gameplay_bomb_symbol) gameplay_bombs_counter = Group() transform_number(gameplay_bombs_number, gameplay_bombs_counter, (200, 3)) gameplay_bombs_counter.draw(main_screen) gameplay_money = 0 gameplay_money_symbol = MoneySymbol() all_sprites.add(gameplay_money_symbol) gameplay_money_counter = Group() transform_number(gameplay_money, gameplay_money_counter, (370, 3)) gameplay_score_counter.draw(main_screen) gameplay_health = HealthGroup() gameplay_health.draw(main_screen) gameplay_wall = Sprite() gameplay_wall.image = pygame.Surface([1, 650]) gameplay_wall.rect = pygame.Rect(-1, 0, 1, 650) gameplay_pause = PauseBtn() all_sprites.add(gameplay_pause) all_sprites.draw(main_screen) gameplay_enemies = Group() gameplay_time = 0 gameplay_enemies_period = 1.5 pygame.display.flip() pygame.mixer.music.load('data/Music/The Ride of the Valkyries.mp3') pygame.mixer.music.play(-1) background_music_playing = False gameplay_clouds = Group()
def render_score_screen(board_render): should_show_screen = board_render.board_manager.round_should_end group = LayeredUpdates() if not should_show_screen: return group current_path = os.path.dirname(os.path.realpath(__file__)) font_path = os.path.join( current_path, "..", "..", "resources", "fonts", "SourceSans3-Semibold.ttf" ) font = Font(font_path, 40) font_small = Font(font_path, 24) match = board_render.match scores = match.scores delta_scores = match.delta_scores total_scores = list(map(lambda s: s[0] + s[1], zip(scores, delta_scores))) winner_indices = numpy.argwhere(numpy.array(delta_scores) > 0).flatten() winner_names = [] array = numpy.array(total_scores) temp = array.argsort()[::-1] ranks = numpy.empty_like(temp) ranks[temp] = numpy.arange(len(array)) icons = get_object('boticons')['bot'] screen_surface = Surface(board_render.surface.get_size(), pygame.SRCALPHA) screen_surface.fill((0, 0, 0)) ROUND_COMPLETE = "Round Complete" round_complete_surface = font.render(ROUND_COMPLETE, True, (255, 255, 255)) font_width, font_height = font.size(ROUND_COMPLETE) icon_size = (100, 100) player_list = match.ai_list x = screen_surface.get_width() // 5 y = font_height + 5 for seat in range(4): ai_name = player_list[seat] name = None icon = None for entry in icons: if entry['ai'] == ai_name: name = entry['name'] icon = entry['icon'] break if name is None: raise "BOT WAS NOT DEFINED." if seat in winner_indices: winner_names += [name] icon_surface = Surface(icon_size, pygame.SRCALPHA) load_image_resource(icon, icon_surface, size=icon_size) screen_surface.blit( icon_surface, (x, y) ) player_name = font.render(name, True, (255, 255, 255)) _, name_h = font.size(name) screen_surface.blit( player_name, (x + icon_size[0] + 10, y) ) score_string = "{} Points".format(scores[seat]) score_render = font_small.render(score_string, True, (255, 255, 255)) _, score_h = font_small.size(score_string) screen_surface.blit( score_render, (x + icon_size[0] + 10, y + name_h + 5) ) delta_string = "{}{}".format("+" if delta_scores[seat] >= 0 else "", delta_scores[seat]) delta_render = font_small.render(delta_string, True, (255, 255, 255)) _, delta_h = font_small.size(delta_string) screen_surface.blit( delta_render, (x + icon_size[0] + 10, y + name_h + 5 + score_h + 5) ) total_string = "Total: {} Points".format(total_scores[seat]) total_render = font_small.render(total_string, True, (255, 255, 255)) screen_surface.blit( total_render, (x + icon_size[0] + 10, y + name_h + 5 + score_h + 5 + delta_h + 5) ) place_string = "{}".format(ranks[seat] + 1) place_render = font.render(place_string, True, (255, 255, 255)) place_w, place_h = font.size(place_string) screen_surface.blit( place_render, (x - place_w - 5, y + ((icon_size[1] - place_h) // 2)) ) y += icon_size[1] + 70 LOADING_NEXT_ROUND = "Loading next Round..." loading_surface = font.render(LOADING_NEXT_ROUND, True, (255, 255, 255)) loading_width, loading_height = font.size(LOADING_NEXT_ROUND) screen_surface.blit( loading_surface, (screen_surface.get_width() - loading_width - 10, screen_surface.get_height() - loading_height - 10) ) screen_surface.blit( round_complete_surface, ((screen_surface.get_width() // 2) - (font_width // 2), 10), ) result_pos = (screen_surface.get_width() * 0.6, screen_surface.get_height() // 3) if board_render.board_manager.did_exhaustive_draw: EXHAUSTIVE = "Exhaustive Draw" exhaustive_surface = font.render(EXHAUSTIVE, True, (255, 255, 255)) screen_surface.blit( exhaustive_surface, result_pos ) else: WINNERS = "Winners:" winners = ", ".join(winner_names) winner_text = font_small.render(WINNERS, True, (255, 255, 255)) winner_name_text = font_small.render(winners, True, (255, 255, 255)) screen_surface.blit( winner_text, result_pos ) screen_surface.blit( winner_name_text, (result_pos[0], result_pos[1] + winner_text.get_rect().height + 5) ) background_sprite = Sprite() background_sprite.rect = screen_surface.get_rect() background_sprite.image = screen_surface background_sprite.layer = 0 group.add(background_sprite) return group
def _load_tiled_tmx_map(tmx_map, gummworld_map, load_invisible=True): """Load an orthogonal TMX map file that was created by the Tiled Map Editor. If load_invisible is False, layers where visible!=0 will be empty. Their tiles will not be loaded. Thanks to DR0ID for his nice tiledtmxloader module: http://www.pygame.org/project-map+loader+for+%27tiled%27-1158-2951.html And the creators of Tiled Map Editor: http://www.mapeditor.org/ """ # Taken pretty much verbatim from the (old) tiledtmxloader module. from pygame.sprite import Sprite resource = ResourceLoaderPygame() resource.load(tmx_map) tile_size = (tmx_map.tilewidth, tmx_map.tileheight) map_size = (tmx_map.width, tmx_map.height) for layeri,layer in enumerate(tmx_map.layers): gummworld_layer = TiledLayer(gummworld_map, layer, layeri) gummworld_map.layers.append(gummworld_layer) if not layer.visible and not load_invisible: continue if layer.is_object_group: for obj in layer.objects: sprite = Sprite() sprite.image = obj.image sprite.rect = pygame.Rect(obj.x, obj.y, obj.width, obj.height) sprite.type = obj.type sprite.image_source = obj.image_source sprite.name = obj.name sprite.properties = obj.properties gummworld_layer.add(sprite) else: for ypos in xrange(0, layer.height): for xpos in xrange(0, layer.width): x = (xpos + layer.x) * layer.tilewidth y = (ypos + layer.y) * layer.tileheight img_idx = layer.content2D[xpos][ypos] if img_idx == 0: continue try: offx,offy,tile_img = resource.indexed_tiles[img_idx] screen_img = tile_img except KeyError: print 'KeyError',img_idx,(xpos,ypos) continue sprite = Sprite() ## Note: alpha conversion can actually kill performance. ## Do it only if there's a benefit. # if convert_alpha: # if screen_img.get_alpha(): # screen_img = screen_img.convert_alpha() # else: # screen_img = screen_img.convert() # if layer.opacity > -1: # screen_img.set_alpha(None) # alpha_value = int(255. * float(layer.opacity)) # screen_img.set_alpha(alpha_value) # screen_img = screen_img.convert_alpha() sprite.image = screen_img sprite.rect = screen_img.get_rect(topleft=(x + offx, y + offy)) sprite.name = xpos,ypos gummworld_layer.add(sprite)
from pygame.sprite import Group, Sprite window = pygame.display.set_mode((600, 400)) screen = pygame.Surface((600, 400)) clock = pygame.time.Clock() inGame = True im = pygame.image.load('images\\brick.png') im2 = pygame.image.load('images\\q1.png') g = Group() # Первый способ s = Sprite() s.image = im s.rect = s.image.get_rect() s.rect.topleft = 100, 150 s.add(g) # Второй способ class Obj(Sprite): def __init__(self, im, x, y): Sprite.__init__(self) self.image = im self.rect = self.image.get_rect() self.rect.topleft = x, y self.add(g)
def new_sprite(image, rect): sprite = Sprite() sprite.image = image sprite.rect = rect return sprite
screen.blit(background, (0,0)) sprites = Group() def personat(x,y): return noiseat(x*8,y*8) <= 0.95 for x in range(0, background.get_width(), 8): for y in range(0, background.get_height(), 8): present = personat(x/8, y/8) if shownoise and not present: continue sprite = Sprite() sprite.image = Surface((4,4), flags=SRCALPHA) if present: sprite.exists = True male = sex(x/8,y/8) draw.circle(sprite.image, (196,196,255) if male else (255,196,196), (2,2), 2, 1 if shownoise else 0) else: sprite.exists = False if not shownoise: draw.circle(sprite.image, (128,128,128), (2,2), 2, 1) sprite.rect = sprite.image.get_rect().move(x, y) sprites.add(sprite) limit = Clock() done = False
def rotateObject(obj: Sprite, angle): center = obj.rect.center obj.rot_angle = (obj.rot_angle + angle) % 360 obj.image = pygame.transform.rotate(obj.image_org, obj.rot_angle) obj.rect = obj.image.get_rect(center=center)