def __init__(self, data, frame_name): self.name = frame_name self.image_file = data['image_file'] self.image = data['image'] anchor = data.get('anchor') if anchor: self.anchor = Vector2(anchor['x'], anchor['y']) else: self.anchor = Vector2(0, 0) rect = data.get('rect') if rect: self.rect = Rect(rect['x'], rect['y'], rect['width'], rect['height']) else: self.rect = Rect(0, 0, self.image.width, self.image.height) attack_box = data.get('attack_box') if attack_box: if attack_box['width'] < 0: attack_box['x'] += attack_box['width'] attack_box['width'] = -attack_box['width'] if attack_box['height'] < 0: attack_box['y'] += attack_box['height'] attack_box['height'] = -attack_box['height'] self.attack_box = Rect(attack_box['x'], attack_box['y'], attack_box['width'], attack_box['height']) else: self.attack_box = None hit_box = data.get('hit_box') if hit_box: if hit_box['width'] < 0: hit_box['x'] += hit_box['width'] hit_box['width'] = -hit_box['width'] if hit_box['height'] < 0: hit_box['y'] += hit_box['height'] hit_box['height'] = -hit_box['height'] self.hit_box = Rect(hit_box['x'], hit_box['y'], hit_box['width'], hit_box['height']) else: self.hit_box = Rect(0, 0, 0, 0)
def __init__(self, filename): self._tmx_data = pytmx.TiledMap(filename, invert_y=True, image_loader=self._image_loader) self._size = self._tmx_data.width * self._tmx_data.tilewidth, self._tmx_data.height * self._tmx_data.tileheight self._layer_offsets = [ Vector2(0, 0) for _ in range(0, len(self._tmx_data.layers)) ] self._drawable = QuadDrawable()
def update(self, game_speed, axis): if axis > 0: self.side_trail.size = self.side_trail_dimensions self.side_trail.pos = PHYSICS_SCALE * ( self._ship._physicsShip.body.transform * (self.offset_x / PHYSICS_SCALE, self.offset_y / PHYSICS_SCALE)) self.side_trail.angle = self.offset_angle + self._ship._quad.angle else: self.side_trail.size = Vector2(0, 0)
def draw_char(self, screen, font_size, char, x, y, scale=1): font = self._font_faces[font_size] c = font.get_char(char) s = self._character_program self._quad.texture = self._page_textures[font_size][c.page_index] self._quad.size = Vector2(c.width, c.height) * scale self._quad.pos = Vector2(x, y + c.offset_y * scale) self._quad.shader = s s.bind() s.set_uniform_matrix4('projection', screen.projection_matrix.m) s.set_uniform_2f('area_pos', c.x / font.page_width, c.y / font.page_height) s.set_uniform_2f('area_size', c.width / font.page_width, c.height / font.page_height) self._quad.draw(screen) return c.advance_x
def __init__(self, ship, offset_x, offset_y): self._isBoosting = False self._ship = ship self.offset_x = offset_x self.offset_y = offset_y self.engine_trail_dimensions = Vector2(130 * self._ship.size, 344 * self._ship.size) self.engine_trail = QuadDrawable(0, 0, self.engine_trail_dimensions.x, self.engine_trail_dimensions.y) self.engine_trail.texture = Texture.load_from_file( 'resources/images/ship/trail.png') # Don't ask why 173... self.engine_trail.anchor = Vector2(65 * self._ship.size, 173 * self._ship.size) self.engine_trail.shader = ShaderProgram.from_files( vert_file='resources/shaders/base.vert', frag_file='resources/shaders/rgba.frag') self.update(0, 0, False)
def generate_asteroid(self): # Picks a random movement direction direction = Vector2() angle = random.random() * math.pi * 2 direction.x = math.cos(angle) direction.y = math.sin(angle) # Places the asteroid outside of the screen position = Vector2() position.x = SCREEN_WIDTH / 2 + direction.x * (SCREEN_WIDTH / 1.5) position.y = SCREEN_HEIGHT / 2 + direction.y * (SCREEN_HEIGHT / 1.5) speed = -Vector2(direction.x, direction.y) * 1000 * random.random() torque = 1 * random.random() asteroid = Asteroid(self, position.x, position.y, speed=speed, torque=torque) self.asteroids.append(asteroid)
def update(self, game_speed, trigger_intensity, boost): self._isBoosting = boost """`trigger_intensity` is a number from 0 to 1 representing how much a player is pressing the controller's right trigger. """ self.engine_trail.size = self.engine_trail_dimensions * ( 1 if boost else trigger_intensity) self.engine_trail.pos = Vector2( self._ship._quad.pos.x + self.offset_x, self._ship._quad.pos.y + self.offset_y, ) self.engine_trail.angle = self._ship._quad._angle
def update(self, screen): pos = self._physics.body.position if pos.x < 0 or pos.x > self._world.bounds.w / PHYSICS_SCALE or \ pos.y < 0 or pos.y > self._world.bounds.h / PHYSICS_SCALE: # Bullet is outside the screen self.remove_bullet() else: # Update the position of the bullet pos *= PHYSICS_SCALE self._quad.pos = Vector2(pos[0], pos[1]) self._quad.angle = self._physics.body.angle pos /= PHYSICS_SCALE
def __init__( self, world, bullet_mgr, controllers, x, y, z=0, angle=0, color='standard', ): super().__init__(world, x, y, z) self.world = world self._dim = Vector2(130 * SCALE, 344 * SCALE) self._angle = angle self._physicsShip = PhysicsShip( self, world.physicsWorld, x / config.PHYSICS_SCALE, y / config.PHYSICS_SCALE, angle=angle, ) # Used by ship components to scale themselves self.size = SCALE self._quad = QuadDrawable(0, 0, self._dim.x, self._dim.y) self._quad.pos = self._position self._quad.anchor = self._dim.__div__(2.0) texture_file = SHIP_TEXTURES.get(color, SHIP_TEXTURES['standard']) self._quad.texture = Texture.load_from_file(texture_file) self._quad.shader = ShaderProgram.from_files(vert_file='resources/shaders/base.vert', frag_file='resources/shaders/rgba.frag') self.controllers = controllers self.pilotController = controllers[0] if len(controllers) else None self.shieldController = controllers[1] if len(controllers) > 1 else None self.turretController = controllers[2] if len(controllers) > 2 else None self.shields = [ Shield(self, world), Shield(self, world), ] self.turret_right = Turret(self, bullet_mgr, offset_x=-59 * SCALE, offset_y=2 * SCALE) self.turret_left = Turret(self, bullet_mgr, offset_x=59 * SCALE, offset_y=2 * SCALE) self.ship_state = ShipState(self) self.trail = Trail(self, 0, 0) self.side_trail_left = SideTrail(self, 28 * SCALE, 40 * SCALE, -45) self.side_trail_right = SideTrail(self, -25 * SCALE, 40 * SCALE, 225)
def draw(self, screen): if self._frame is None: return self._drawable.pos = Vector2( self._x, self._y) # - camera.offset.x, self._y - camera.offset.y) self._drawable.draw(screen) # DEBUG boxes if Sprite.DEBUG: # TODO: !!! pass
def __init__(self, width, height, cloud_list): start_x = random.randint(0, width) start_y = random.randint(0, height) cloud_number = random.randint(0, len(cloud_list)) self.pos = Vector2(start_x, start_y) self.speed_x = (random.random() - 0.5) / 10 self.speed_y = (random.random() - 0.5) / 10 self.quad = None size = calculate_size(width, height) create_cloud_quad(self, size, cloud_list, cloud_number)
def update(self, game_speed): self.stage.update(game_speed) for e in self.asteroids: e.update(game_speed) for e in self.entities: e.update(game_speed) should_gen_asteroid = random.randint(0, 10000) if should_gen_asteroid < 10: self.generate_person() elif should_gen_asteroid < 20: self.generate_derelict() elif should_gen_asteroid < 100: self.generate_asteroid() self.check_asteroids() # Check position of physical objects for e in self.entities: if not isinstance(e, Ship): continue pos = e._physicsShip.body.position force_dir = Vector2() if pos.x < 0: force_dir = Vector2(1, 0) elif pos.x > self.bounds.w / PHYSICS_SCALE: force_dir = Vector2(-1, 0) elif pos.y < 0: force_dir = Vector2(0, 1) elif pos.y > self.bounds.h / PHYSICS_SCALE: force_dir = Vector2(0, -1) intensity = 100 force_dir *= intensity force_apply_pos = e._physicsShip.body.GetWorldPoint( localPoint=(0.0, 0.0)) e._physicsShip.body.ApplyLinearImpulse((force_dir.x, force_dir.y), force_apply_pos, True)
def generate_asteroid(self): # Picks a random movement direction direction = Vector2() angle = random.random() * math.pi * 2 direction.x = math.cos(angle) direction.y = math.sin(angle) # Places the asteroid outside of the screen position = Vector2() position.x = SCREEN_WIDTH / 2 + direction.x * (SCREEN_WIDTH / 1.5) position.y = SCREEN_HEIGHT / 2 + direction.y * (SCREEN_HEIGHT / 1.5) assets = [ 'resources/images/asteroides/asteroid_01.png', 'resources/images/asteroides/asteroid_02.png', 'resources/images/asteroides/asteroid_03.png', 'resources/images/asteroides/asteroid_04.png', 'resources/images/asteroides/asteroid_05.png', 'resources/images/asteroides/asteroid_06.png', 'resources/images/asteroides/asteroid_07.png', 'resources/images/asteroides/asteroid_08.png', 'resources/images/asteroides/asteroid_09.png', 'resources/images/asteroides/asteroid_10.png', 'resources/images/asteroides/asteroid_11.png', 'resources/images/asteroides/asteroid_12.png', 'resources/images/asteroides/asteroid_13.png', 'resources/images/asteroides/asteroid_14.png', ] speed = -Vector2(direction.x, direction.y) * 500 * random.random() torque = 1 * random.random() asteroid = Asteroid(self, position.x, position.y, speed=speed, torque=torque, asset=assets[random.randint(0, len(assets) - 1)]) self.asteroids.append(asteroid)
def __init__(self, begin_x, begin_y, width, height, planet_list): start_x = begin_x + width / 8 + random.randint(-width / 4, width / 4) start_y = begin_y + height / 8 + random.randint( -height / 4, height / 4) planet_number = random.randint(0, len(planet_list)) self.pos = Vector2(start_x, start_y) self.speed_x = (random.random() - 0.5) / 100 self.speed_y = (random.random() - 0.5) / 100 self.rotation_speed = (random.random() - 0.5) / 800 self.quad = None size = calculate_size(width, height) create_planet_quad(self, size, planet_list, planet_number)
def __init__(self, bullet_mgr, world): super().__init__(world, 0, 0, 0) # The visual representation of the bullet. self.owner = None self._world = world self._quad = QuadDrawable() self._quad.texture = Texture.load_from_file( 'resources/images/bullet.png') self._quad.size = Vector2(self._quad.texture.width, self._quad.texture.height) self._quad.anchor_to_center() # Attach physics only in the initialize method self.bullet_radius = min(self._quad.size.x, self._quad.size.y) / PHYSICS_SCALE / 2 self._angle = None self.bullet_mgr = bullet_mgr
def destroy_ship(self): pos = self._physicsShip.body.position * config.PHYSICS_SCALE x, y = pos self.world.asteroids.append(Asteroid( self.world, x, y - 30, Vector2(random() * 30 - 15, random() * -100), random() * 3.0, 'resources/images/derelict/part_01.png', config.SHIP_SCALE )) self.world.asteroids.append(Asteroid( self.world, x + 30, y + 30, Vector2(random() * 60 + 30, random() * 60 + 30), random() * 3.0, 'resources/images/derelict/part_02.png', config.SHIP_SCALE )) self.world.asteroids.append(Asteroid( self.world, x - 30, y + 30, Vector2(random() * -60 - 30, random() * 60 + 30), random() * 3.0, 'resources/images/derelict/part_03.png', config.SHIP_SCALE )) self.world.asteroids.append(Asteroid( self.world, x, y - 30, Vector2(random() * 3.0 - 1.5, random() * -10), random() * 3.0, 'resources/images/people/pilot.png', config.SHIP_SCALE )) self.world.asteroids.append(Asteroid( self.world, x + 30, y + 30, Vector2(random() * 6.0 + 3.0, random() * 6.0 + 3.0), random() * 3.0, 'resources/images/people/gunner.png', config.SHIP_SCALE )) self.world.asteroids.append(Asteroid( self.world, x - 30, y + 30, Vector2(random() * -6.0 - 3.0, random() * 6.0 + 3.0), random() * 3.0, 'resources/images/people/technician.png', config.SHIP_SCALE ))
def __init__(self, frames_store): self._frames_store = frames_store self._x = 0 self._y = 0 self._flags = 0 self._angle = 0 self._scale = Vector2(1, 1) # Collision detection self._attack_box = None self._hit_box = None # Frames and animations self._frame = None self._animation = None self._animation_name = None self._animation_frame_index = None self._animation_frame_delay = 0 self._animation_speed = 1 self._animating = False # Drawing self._drawable = QuadDrawable()
def _set_animation_frame(self, frame_index): self._animation = self._frames_store.get_animation( self._animation_name) self._animation_frame_index = frame_index self.animation_frame = self._animation.frames[ self._animation_frame_index] new_frame = self._animation.frames[frame_index] self._animation_frame_delay = new_frame.delay self._frame = self._frames_store.get_frame(new_frame.frame_name) # Override animation flip if the frame is also flipped flags = self._flags if self.animation_frame.flip_x: flags |= FramesStore.FLAG_FLIP_X if self.animation_frame.flip_y: flags |= FramesStore.FLAG_FLIP_Y # Updates the drawable self._drawable.texture = self._frame.image self._drawable.scale = Vector2(self._frame.rect.w, self._frame.rect.h).dot(self._scale) self._drawable.anchor = self._frame.anchor.dot(self._scale) self._drawable.flip_x = (flags & FramesStore.FLAG_FLIP_X > 0) self._drawable.flip_y = (flags & FramesStore.FLAG_FLIP_Y > 0)
def __init__(self, x=0.0, y=0.0, scale_x=1, scale_y=1, angle=0): super().__init__(x=x, y=y, scale_x=scale_x, scale_y=scale_y, angle=angle) self._anchor = Vector2(0, 0) self._m_anchor = Matrix4() self._vao = glGenVertexArrays(1) glBindVertexArray(self._vao) # Vertices self._vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self._vbo) self._vertices = np.array([0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], dtype=np.float32) glBufferData(GL_ARRAY_BUFFER, self._vertices.nbytes, self._vertices, GL_STATIC_DRAW) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, None) # Texture coordinates self._vbo_uvs = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self._vbo_uvs) self._texture_coords = np.array([0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], dtype=np.float32) glBufferData(GL_ARRAY_BUFFER, self._texture_coords.nbytes, self._texture_coords, GL_STATIC_DRAW) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, None) glBindVertexArray(0) if self._default_shader is None: self._setup_default_shader() self.shader = self._default_shader
sdl2.ext.line(surface, color, (x1, y1, x2, y2)) def draw_rect(surface, x, y, width, height): color = sdl2.ext.Color(255, 0, 0) sdl2.ext.fill(surface, color, ((x - width / 2) * 10, (y - height / 2) * 10, width * 10, height * 10)) contact_listener = ContactListener() physicsWorld = b2World(gravity=(0, 0), contactListener=contact_listener) pShip = PhysicsShip(object(), physicsWorld, 50, 50) pShip2 = PhysicsShip(object(), physicsWorld, 80, 80) pShield = PhysicsShield(object(), physicsWorld, Vector2(60, 60), 20) # pBullet = PhysicsBullet(object(), physicsWorld, 10, 20, 8, 13) pAsteroid = PhysicsAsteroid(object(), physicsWorld, 100, 100) sdl2.ext.init() window = sdl2.ext.Window("2D drawing primitives", size=(1920, 1080)) window.show() windowsurface = window.get_surface() def draw_polygon(screen, body, polygon): vertices = [(body.transform * v) * 10 for v in polygon.vertices] vertices = [(v[0], 1080 - v[1]) for v in vertices] for i in range(0, len(vertices)): draw_line(screen, int(vertices[i][0]), int(vertices[i][1]),
def __init__(self, width, height): super().__init__(width, height) texture = Texture.load_from_file('resources/images/logo.png') self._logo = QuadDrawable(0, 0, texture.width, texture.height) self._logo.anchor = Vector2(texture.width / 2, texture.height / 2) self._logo.texture = texture
def __init__(self, world, x, y, z=0): self._world = world self._position = Vector2(x, y) self._z = z self.should_be_removed = False
def __init__(self): self._size = Vector2() self.texture_id = 0
import logging from mgl2d.app import App from mgl2d.graphics.quad_drawable import QuadDrawable from mgl2d.graphics.screen import Screen from mgl2d.graphics.texture import Texture from mgl2d.math.vector2 import Vector2 logging.basicConfig(level=logging.INFO) app = App() screen = Screen(800, 600, 'Quad drawable') screen.print_info() # Textured quad centered quad = QuadDrawable(400, 300, 200, 200) quad.texture = Texture.load_from_file('data/texture.png') quad.anchor = Vector2(100, 100) def draw_frame(screen): quad.draw(screen) def update_frame(delta_ms): quad.angle += 0.1 pass app.run(screen, draw_frame, update_frame)
def scale_from_texture(self): self.scale = Vector2(self._texture.width, self._texture.height)
def update(self, game_speed): self._physicsShip.update_forces(self.pilotController) for c in self.controllers: c.update() # if c.is_button_pressed(GameController.BUTTON_DIR_PAD_UP): # if self.turretController == c: # self.turretController = None # if self.shieldController == c: # self.shieldController = None # self.pilotController = c # elif c.is_button_pressed(GameController.BUTTON_DIR_PAD_DOWN): # if self.pilotController == c: # self.pilotController = None # if self.shieldController == c: # self.shieldController = None # self.turretController = c # elif c.is_button_pressed(GameController.BUTTON_DIR_PAD_LEFT): # if self.turretController == c: # self.turretController = None # if self.pilotController == c: # self.pilotController = None # self.shieldController = c if self.pilotController and self.ship_state.state == ShipState.LIVE: boost = self.pilotController.is_button_down(GameController.BUTTON_A) trigger_intensity = self.pilotController.get_axis(GameController.AXIS_TRIGGER_RIGHT) or 0.0 self.trail.update(game_speed, trigger_intensity, boost) axis_intensity = self.pilotController.get_axis(GameController.AXIS_LEFT_X) or 0.0 self.side_trail_left.update(game_speed, axis_intensity) self.side_trail_right.update(game_speed, -axis_intensity) if self.shieldController and self.ship_state.state == ShipState.LIVE: shield0_input_values = ( self.shieldController.get_axis(GameController.AXIS_LEFT_X) or 0.0, self.shieldController.get_axis(GameController.AXIS_LEFT_Y) or 0.0, 0.0, ) shield1_input_values = ( self.shieldController.get_axis(GameController.AXIS_RIGHT_X) or 0.0, self.shieldController.get_axis(GameController.AXIS_RIGHT_Y) or 0.0, 0.0, ) else: shield0_input_values = (0.0, 0.0, 0.0) shield1_input_values = (0.0, 0.0, 0.0) self.shields[0].update(game_speed, shield0_input_values) self.shields[1].update(game_speed, shield1_input_values) if self.turretController and self.ship_state.state == ShipState.LIVE: turret_left_x, turret_left_y = ( self.turretController.get_axis(GameController.AXIS_LEFT_X) or 0.0, self.turretController.get_axis(GameController.AXIS_LEFT_Y) or 0.0, ) turret_right_x, turret_right_y = ( self.turretController.get_axis(GameController.AXIS_RIGHT_X) or 0.0, self.turretController.get_axis(GameController.AXIS_RIGHT_Y) or 0.0, ) threshold = 0.2 turret_left_fire = (self.turretController.get_axis(GameController.AXIS_TRIGGER_LEFT) or 0.0) > threshold turret_right_fire = (self.turretController.get_axis(GameController.AXIS_TRIGGER_RIGHT) or 0.0) > threshold else: turret_left_x, turret_left_y = (0, 0) turret_right_x, turret_right_y = (0, 0) turret_left_fire = turret_right_fire = False self.turret_left.update( game_speed, turret_left_x, turret_left_y, turret_left_fire, is_right_wing=False, ) self.turret_right.update( game_speed, turret_right_x, turret_right_y, turret_right_fire, is_right_wing=True, ) self._angle = self._physicsShip.body.angle + math.pi pos = self._physicsShip.body.position * config.PHYSICS_SCALE self._position = Vector2(pos[0], pos[1]) self._quad.pos = self._position self._quad.angle = self._angle self.ship_state.update( time_passed_ms=(game_speed * config.GAME_FRAME_MS), )
def update(self, screen): self.quadm.size = Vector2(self.quadm.scale.x, self.quadm.scale.y * 0.9) if self.quadm.scale.x < 0.01: self.should_be_removed = True self.quadm.size = Vector2(0, 0)
quad = QuadDrawable(100 + x * 200, 100 + y * 200, size_x=120, size_y=120) quad.texture = Texture.load_from_file('data/texture.png') quad.anchor_to_center() quads.append(quad) # Flipped horizontally quads[1].flip_x = True # Flipped vertically quads[2].flip_y = True # Flipped in both directions quads[3].flip_x = quads[3].flip_y = True # Scaled smaller quads[4].scale = Vector2(0.8, 0.8) # Scaled bigger quads[5].scale = Vector2(1.2, 1.2) # Rotated 45 degrees quads[6].angle = math.pi / 4 # Rotated 22 degrees and scaled to 50% quads[7].angle = math.pi / 8 quads[7].scale = Vector2(0.8, 0.8) # Stretched quads[8].scale = Vector2(0.5, 1.2) def draw_frame(screen): for q in quads: q.draw(screen)
import math from Box2D import b2Vec2 from mgl2d.graphics.quad_drawable import QuadDrawable from mgl2d.graphics.shader_program import ShaderProgram from mgl2d.graphics.texture import Texture from mgl2d.math.vector2 import Vector2 import config from config import PHYSICS_SCALE from game.entities.shield_state import ShieldState from game.entity import Entity from physics.physics_shield import PhysicsShield SHIP_SIZE = Vector2(109, 156) HALF_ARC_DEGREES = 40 INERTIA = True class Shield(Entity): def __init__(self, ship, world): super().__init__(ship._world, 0, 0) self._ship = ship self._quad = QuadDrawable(0, 0, 0, 0) self._quad.texture = Texture.load_from_file( 'resources/images/shield_arc.png') self._quad.shader = ShaderProgram.from_files( vert_file='resources/shaders/base.vert', frag_file='resources/shaders/rgba.frag') self._quad.size = Vector2(self._quad.texture.width,
def update(self, game_speed): super().update(game_speed) self._logo.pos = Vector2(self.width / 2, self.height / 2)