def testUpdateSpriteFrame(self): topLeft = sf.Vector2( self.base_entity._frame_size.x * self.base_entity._frame, self.base_entity._frame_size.y * self.base_entity._direction) self.base_entity.update_sprite_frame() self.assertTrue(self.base_entity._sprite.texture_rectangle == sf.Rectangle(topLeft, self.base_entity._frame_size)) # change properties self.base_entity._direction = LEFT self.base_entity._frame = 2 # update topLeft variable topLeft = sf.Vector2( self.base_entity._frame_size.x * self.base_entity._frame, self.base_entity._frame_size.y * self.base_entity._direction) # check to make sure that sprite frame has not been updated self.assertFalse(self.base_entity._sprite.texture_rectangle == sf.Rectangle(topLeft, self.base_entity._frame_size)) # update frame and check # for equality self.base_entity.update_sprite_frame() self.assertTrue(self.base_entity._sprite.texture_rectangle == sf.Rectangle(topLeft, self.base_entity._frame_size))
def __init__(self, speed, starting_position, texture, window_rectangle, collision_manager): self.window_rectangle = window_rectangle self.starting_position = starting_position self.speed = speed self.collision_manager = collision_manager self.direction = 1 if speed > 0 else -1 # Plane fly_anim = Animation() fly_anim.texture = texture fly_anim.add_frame(sf.Rectangle((0, 0), (88, 73))) fly_anim.add_frame(sf.Rectangle((88, 0), (88, 73))) fly_anim.add_frame(sf.Rectangle((176, 0), (88, 73))) fly_anim.add_frame(sf.Rectangle((88, 0), (88, 73))) self.plane = AnimatedSprite(sf.seconds(0.2), False, True) self.plane.play(fly_anim) self.plane.size = sf.Vector2(self.plane.global_bounds.width / 2, self.plane.global_bounds.height / 2) self.plane.origin = self.plane.global_bounds.width / 2.0, self.plane.global_bounds.height / 2.0 self.plane.scale((self.direction * 0.5, 0.5)) self.plane.position = self.starting_position self.plane_speed = sf.Vector2(speed, 0) self.is_dead = False self.jump_time = None self.plane_jumped = False self.immortal = None self.bullets = set() SoundManager.play_player_appear_sound()
def new_intersects(obj, rectangle): l, t, w, h = rectangle rectangle = sf.Rectangle((l, t), (w, h)) left = max(obj.left, rectangle.left) top = max(obj.top, rectangle.top) right = min(obj.right, rectangle.right) bottom = min(obj.bottom, rectangle.bottom) if left < right and top < bottom: return sf.Rectangle((left, top), (right - left, bottom - top))
def __init__(self, width, data, tilesets, layer): super(TileGroup, self).__init__() tileset = [] x = 0.0 y = 0.0 for d in data: if (d > 0): for t in tilesets: if (t['firstgid'] <= d): tileset = t break tile = SpriteEntity(texture=TM.get('tiles/' + tileset['image']), layer=layer) tiles_per_line = tileset['imagewidth'] // tileset['tilewidth'] tile_offset = d - tileset['firstgid'] tile.texture_rectangle = sf.Rectangle( (((tile_offset % tiles_per_line) * 32), ((tile_offset // tiles_per_line) * 32)), (32, 32)) tile.texture_rectangle tile.position = sf.Vector2(x, y) self.children.append(tile) x += 1.0 if (x >= width): x = 0.0 y += 1.0
def __init__(self): # Window self.window = sf.RenderWindow(sf.VideoMode(WWIDTH, WHEIGHT), WTITLE, sf.Style.CLOSE | sf.Style.TITLEBAR, SETTINGS) self.window.framerate_limit = 60 # Clock self.clock = sf.Clock() # View self.view = sf.View(sf.Rectangle((0, 0), (WWIDTH, WHEIGHT))) self.window.view = self.view # Loading assets self.load_assets() self.backgrounds = [sf.Sprite(self.bg_texture) for i in xrange(2)] self.grounds = [sf.Sprite(self.ground_texture) for i in xrange(2)] self.grounds[0].position = 0, 409 self.grounds[1].position = 0, 409 # Plane fly_anim = Animation() fly_anim.texture = self.plane_sheet fly_anim.add_frame(sf.Rectangle((0, 0), (88, 73))) fly_anim.add_frame(sf.Rectangle((88, 0), (88, 73))) fly_anim.add_frame(sf.Rectangle((176, 0), (88, 73))) fly_anim.add_frame(sf.Rectangle((88, 0), (88, 73))) self.plane = AnimatedSprite(sf.seconds(0.2), False, True) self.plane.play(fly_anim) self.plane.origin = self.plane.global_bounds.width / 2.0, self.plane.global_bounds.height / 2.0 self.plane.position = sf.Vector2(150, 200) self.plane_speed = sf.Vector2(0.0, 0.0) self.jump_time = None self.plane_jumped = False # Rocks self.rocks = [] self.spawn_rocks()
def _display_main_monster(self): monster = sf.Sprite(self._monster_texture) monster.texture_rectangle = sf.Rectangle( (0, 0), (self._monster_texture.width, self._monster_texture.height)) monster.position = ( (settings.windowWidth - self._monster_texture.width) / 2, (settings.windowHeight - self._monster_texture.height) / 2)
def __init__(self, window): State.__init__(self, window) #self.debug = [] self.busses = [] self.creatures = [] self.lives = [] self.player = Player(WIDTH / 2, HEIGHT / 2) for i in range(0, random.randint(MIN_GRUES, MAX_GRUES)): creature = Grue(*random_point_not_near(self.player.position)) #print("New Grue at (%s)" % (creature.position)) self.creatures.append(creature) for i in range(0, random.randint(MIN_HEALS, MAX_HEALS)): heal = Lives(random.randrange(0, MAP_WIDTH), random.randrange(0, MAP_HEIGHT)) self.lives.append(heal) self.background = sf.Sprite(sf.Texture.from_file("map2.png")) self.view = sf.View() self.view.reset(sf.Rectangle((0, 0), (WIDTH, HEIGHT))) self.window.view = self.view self.overlay = Overlay(self.player) self.dark_overlay = Overlay(self.player, dark=True) self.life_point_display = PointDisplay( sf.Rectangle((10, 10), (100, 10)), self.player.health, sf.Color.RED) self.stamina_display = PointDisplay( sf.Rectangle((WIDTH - 60 - 10, 10), (60, 10)), self.player.max_stamina, sf.Color.GREEN) self.boss_time = sf.Clock() self.run_timer = sf.Clock() self.treasure_time = sf.Clock() self.stamina_regeneration_timer = sf.Clock() self.is_running = False self.is_dark = False self.has_boss = False self.has_treasure = False
def create_life_tiles(self, window_height, window_width): tile_height = window_height * 1.0 / self.lives tile_x_pos = 0 if self.id == 'left' else window_width - tile_width tile_y_pos = 0 sprites = [] for i in xrange(self.lives): rect = sf.Rectangle((tile_x_pos, tile_y_pos), (tile_width, tile_height)) sprites.append(utils.create_sprite(self.green_texture, rect.width, rect.height, rect.position)) tile_y_pos += tile_height return sprites
def __init__(self, pos, input): self.position = pos # position on gui window (not sfml window) self.position_dirty = True self.local_bounds = sf.Rectangle(pos, sf.Vector2(0, 0)) self.children = [] self.parent = None input.add_key_handler(self) input.add_mouse_handler(self)
def __init__(self): self.window = sf.RenderWindow(sf.VideoMode(WIDHT, HEIGHT), TITLE, sf.Style.DEFAULT, settings) self.circle = sf.CircleShape(50) self.rectangle = sf.RectangleShape((150, 200)) self.rectangle.position = 200, 100 self.view = sf.View() self.view.reset(sf.Rectangle((0, 0), self.window.size)) self.window.view = self.view
def setUp(self): # Animation stuff dudeFrame = 6 dudeFrameCounter = 0 dudeFrameSpeed = 5 # load the textures for possible heroes dudeTextures = [] characters = [] try: dudeTextures.append( sf.Texture.from_file("assets/sprites/dude0.png")) dudeTextures.append( sf.Texture.from_file("assets/sprites/dude1.png")) dudeTextures.append( sf.Texture.from_file("assets/sprites/dude2.png")) except IOError: print("ERROR") exit(1) for dudeTexture in dudeTextures: characters.append(sf.Sprite(dudeTexture)) for i in range(len(characters)): characters[i].ratio = sf.Vector2(4, 4) characters[i].origin = texture_size / 2 characters[i].position = (game_size.x / (len(characters) + 1) * (i + 1), game_size.y / 2) topLeft = sf.Vector2(114, 0) for character in characters: character.texture_rectangle = sf.Rectangle(topLeft, texture_size) level = 1 space = pm.Space() sprite = characters[1] # create hero's physical body dude_body = pm.Body(50, pm.inf) # Has a weight, but cannot rotate # create hero's boundaries dude_poly = pm.Poly.create_box(dude_body, person_size) dude_poly.friction = 1 dude_poly.collision_type = 3 jump_sensor = pm.Poly.create_box(dude_body, size=(50, 2), offset=(0, 65)) jump_sensor.sensor = True jump_sensor.collision_type = 2 space.add(dude_body, dude_poly, jump_sensor) self.base_entity = BaseEntity(dude_body, dude_poly, sprite, sf.Vector2(19, 44))
def intersects(rect1, rect2): # compute the intersection boundaries left = max(rect1.left, rect2.left) top = max(rect1.top, rect2.top) right = min(rect1.right, rect2.right) bottom = min(rect1.bottom, rect2.bottom) # if the intersection is valid (positive non zero area), then # there is an intersection if left < right and top < bottom: return sf.Rectangle((left, top), (right - left, bottom - top))
def __init__(self, window_size, distance_from_base, first_player_tex, second_player_tex, speed): self.window_rect = sf.Rectangle((0, 0), (window_size.x, window_size.y)) self.speed = speed self.first_player_tex = first_player_tex self.second_player_tex = second_player_tex self.left_pos = distance_from_base self.right_pos = window_size.x - distance_from_base self.min_y = PADDING self.max_y = window_size.y - PADDING self.players_by_key = {}
def update(self, dt): self.timer += dt if(self.timer > self.clips[self.play_id]['interval']): self.timer = 0.0 self.sprite.texture = self.clips[self.play_id]['texture'] size = self.clips[self.play_id]['size'] self.texture_rectangle = sf.Rectangle((self.clip_id * size.x, 0), size) if(self.clip_id == (self.clips[self.play_id]['quantity'] - 1)): self.clip_id = 0 else: self.clip_id += 1
def run(self): if not self.load_assets(): sys.exit(-1) self.bird_animation = Animation() self.bird_animation.texture = self.bird_texture self.bird_animation.add_frame(sf.Rectangle((0, 0), (34, 24))) self.bird_animation.add_frame(sf.Rectangle((34, 0), (34, 24))) self.bird_animation.add_frame(sf.Rectangle((68, 0), (34, 24))) self.bird_sprite = AnimatedSprite(sf.seconds(0.2), False, True) self.bird_sprite.position = sf.Vector2(50, 50) while self.window.is_open: for e in self.window.events: self.event_handler(e) elapsed_time = self.clock.restart() self.update(elapsed_time) self.render()
def __init__(self, pos, width, default_text, input): super().__init__(pos, "textbox", 1, 1, input) self.sprite.scale(sf.Vector2(width / self.sprite.texture.width, 1)) self.text_offset = sf.Vector2(7, 3) self.local_bounds = sf.Rectangle( pos, sf.Vector2(width, self.sprite.texture.height)) self.typing = False self.overlapping = False # if the text goes out the textbox self.default_text = default_text self.text = sf.Text(default_text, res.font_farmville, 20) self.text.position = self.local_bounds.position self.text.color = sf.Color.BLACK input.add_text_handler(self)
def main(self): # load big resources first cardPath = os.path.join(os.getcwd(), "res", "cardData.json") allCardData = None with open(cardPath, 'r', encoding="utf-8") as f: allCardData = json.load(f) # SET UP THE GRAPHICS WINDOW window = sf.RenderWindow(sf.VideoMode(1100, 800), 'Mana Burn') window.framerate_limit = 60 window.clear() view = sf.View() view.reset(sf.Rectangle((0, 0), (1100, 850))) window.view = view window.display() # figure out the save game situation currentSavedGame = SavedGame() currentScreen = MainScreen(window, view, currentSavedGame, allCardData) # A clock runs and cleans up dead objects periodically cleanupClock = sf.Clock() # THE UPDATE AND GAME LOOP while window.is_open: for event in window.events: if type(event) is sf.CloseEvent: window.close() if type(event ) is sf.KeyEvent and event.code is sf.Keyboard.ESCAPE: window.close() if type(currentScreen) is MainScreen: if type(event) is sf.MouseButtonEvent: currentScreen.checkClicks(window, event) if type(event) is sf.MouseWheelEvent: currentScreen.checkScroll(window, event) window.clear() currentScreen.update() window.display() if cleanupClock.elapsed_time.seconds >= .5: currentScreen.cleanUp() cleanupClock.restart()
def __init__(self, pos, width, height, color, input): super().__init__(pos, input) self.width = width self.height = height self.center = sf.Vector2(width / 2, height / 2) self.vertices = sf.VertexArray(sf.PrimitiveType.QUADS, 4) self.vertices[0].position = sf.Vector2(pos.x, pos.y) self.vertices[1].position = sf.Vector2(pos.x + self.width, pos.y) self.vertices[2].position = sf.Vector2(pos.x + self.width, pos.y + self.height) self.vertices[3].position = sf.Vector2(pos.x, pos.y + self.height) for i in range(0, 4): self.vertices[i].color = color self.local_bounds = sf.Rectangle(pos, sf.Vector2(width, height)) self.mouse_state = 'up'
def __init__(self, bold=False): if bold: self.texture = sfml.Texture.from_file(constants.SPRITE_FOLDER + 'fontbold.png') self.cw = 9 self.ch = 13 else: self.texture = sfml.Texture.from_file(constants.SPRITE_FOLDER + 'font.png') self.cw = 7 self.ch = 13 self.chars = [] for char in range(256): #Create a sfml sprite object for each letter sprite = sfml.Sprite(self.texture) r = sfml.Rectangle(((char % 16) * self.cw, (char // 16) * self.ch), (self.cw, self.ch)) sprite.texture_rectangle = r self.chars.append(sprite)
def getPosAndRect(self, texture, position): # Some images have their center onscreen, but their top-left corner # offscreen. Image.blit is going to be upset if it gets a negative # position value, so move the position to 0 and use a sub-rectangle of the # source image to create the same effect. x, y = position l, t = (0, 0) w, h = texture.size if x < 0: w += x l -= x x = 0 if y < 0: h += y t -= y y = 0 return (sf.Vector2(x, y), sf.Rectangle(sf.Vector2(l, t), sf.Vector2(w, h)))
def __init__(self): # Window self.window = sf.RenderWindow(sf.VideoMode(WWIDTH, WHEIGHT), WTITLE, sf.Style.CLOSE | sf.Style.TITLEBAR, SETTINGS) self.window.framerate_limit = 60 SoundManager.play_background_music() # Clock self.clock = sf.Clock() # View self.view = sf.View(sf.Rectangle((0, 0), (WWIDTH, WHEIGHT))) self.window.view = self.view # Loading assets self.textures = self.load_assets() self.bg = create_sprite(self.textures['bg'], WWIDTH, WHEIGHT, (0, 0)) self.collision_manager = CollisionManager() self.bonus_manager = BonusManager( self.window, { 'life': sf.Texture.from_file("assets/images/red03.png"), 'bullet': sf.Texture.from_file("assets/images/bulletBonus.png"), 'immortality': sf.Texture.from_file("assets/images/heart.png") }, self.collision_manager) self.obstacles = self.create_obstacles() self.bases = self.create_bases() self.player_manager = PlayerManager(self.window.size, DIST_FROM_BASE, self.textures['plane'], self.textures['human'], SPEED) self.obstacles = list(self.create_obstacles()) self.stopped = False self.gameover = create_sprite(self.textures['aliens_win'], self.window.width, self.window.height, (0, 0))
def __init__(self, position, size, bgcolor, fgcolor, linecolor, linesize, lable, font, fontsize): self._position = position self._size = size self._bgcolor = bgcolor self._fgcolor = fgcolor self._linecolor = linecolor self._linesize = linesize self._lable = lable self._font = font self._fontsize = fontsize #def RecShape(): #RectangleShape self._recShape = sf.RectangleShape() self._recShape.position = self._position self._recShape.size = self._size self._recShape.fill_color = self._bgcolor self._recShape.outline_color = self._linecolor self._recShape.outline_thickness = self._linesize #def Rec(): #Rectangle self._rec = sf.Rectangle(self._position, self._size) #def Text(): #text self._text = sf.Text() self._text.string = self._lable self._text.font = self._font self._text.character_size = self._fontsize self._text.style = sf.Text.BOLD textpos = sf.Vector2( (self._size[0] - self._text.local_bounds.size[0]) / 2, self._size[1] - self._fontsize) + self._position textpos = sf.Vector2( textpos[0], (textpos[1] - (self._text.local_bounds.size[1] / 5))) self._text.position = textpos self._text.color = self._fgcolor
import sfml import random import time import math # Initialize the window window = sfml.RenderWindow(sfml.VideoMode.get_desktop_mode(), 'Rainbow Fire', sfml.window.Style.FULLSCREEN) visible_area = sfml.Rectangle(sfml.Vector2(0, 0), window.size) # Seed random random.seed(time.time()) # Load textures rainbow_dash_tx = sfml.Texture.from_file('rainbow_dash.png') evil_pony_tx = sfml.Texture.from_file('evil_pony.png') blast_tx = sfml.Texture.from_file('blast.png') bullet_tx = sfml.Texture.from_file('bullet.png') # Load sounds blast_sound = sfml.Sound(sfml.SoundBuffer.from_file('blast.wav')) shot_sound = sfml.Sound(sfml.SoundBuffer.from_file('shot.wav')) smash_sound = sfml.Sound(sfml.SoundBuffer.from_file('smash.wav')) # Load font bangers_ft = sfml.Font.from_file('Bangers.ttf') # Score score = 0 score_text = sfml.Text('Score: ' + str(score), bangers_ft, 60) score_text.position = (window.size.x - score_text.global_bounds.width - 20, 10)
def freeup_position(self, position): rect = sf.Rectangle(self.position, sf.Vector2(self.width, self.height)) if rect.contains(position) and position not in self.free_positions: self.free_positions.append(position)
import sfml as sf WIDTH = 640 HEIGHT = 480 MAP_WIDTH = 1000 MAP_HEIGHT = 1400 MAP_RECT = sf.Rectangle((0, 0), (MAP_WIDTH, MAP_HEIGHT)) MIN_GRUES = 15 MAX_GRUES = 20 MIN_HEALS = 2 MAX_HEALS = 6
def recalculate_rect(self): self.__rect = sf.Rectangle(self.__position - self.size / 2.0, self.size) self.__radius = max(self.size.x, self.size.y) * 2
def __init__(self, window): State.__init__(self, window) self.sprite = sf.Sprite(sf.Texture.from_file("endtext.png")) self.view = sf.View() self.view.reset(sf.Rectangle((0, 0), (WIDTH, HEIGHT)))
def get_bounding_rects(self): if self.alive: p = self.sprite.position s = sf.Vector2(40, 40) return sf.Rectangle((p.x - s.x / 2, p.y - s.y / 2), (s.x, s.y))
from collisions import Collidable import sfml as sf from soundmanager import Instance as SoundManager from utils import create_sprite _bullet_tex = sf.Texture.from_file("assets/images/bullet.png") window_rectangle = sf.Rectangle((0, 0), (1200, 750)) class Bullet(Collidable): def get_bounding_rects(self): if self.alive: p = self.sprite.position s = sf.Vector2(40, 40) return sf.Rectangle((p.x - s.x / 2, p.y - s.y / 2), (s.x, s.y)) def collide(self, other): if isinstance(other, Bullet): return if hasattr(other, 'plane') and other.speed * self.speed < 0: SoundManager.play_explosion_sound() self.alive = False if not hasattr(other, 'plane'): SoundManager.play_explosion_sound() self.alive = False def __init__(self, position, speed): self.speed = speed self.position = position
def local_bounds(self): rect = self.animation.frames[self.current_frame] width = abs(rect.width) height = abs(rect.height) return sf.Rectangle((0.0, 0.0), (width, height))