def renderWeaponPower(self, targetSurface): image = images.get('ui_weaponpower') startLocation = Vector(175, 240 - 11) for _ in range(gamecontroller.getPlayerTank().getWeapon().getLevel()): targetSurface.blit(image, startLocation.toIntTuple()) startLocation = startLocation.add(Vector(7, 0))
def __init__(self, location, graphics, heading=Vector(1, 0)): super().__init__() self.graphics = graphics self.heading = Vector(0, -1) self.direction = Direction.NORTH self.moving = False self.type = type self.maxHitPoints = 10 self.hitpoints = self.maxHitPoints self.movementSpeed = 1 self.scorePoints = 0 self.shielded = False self.shieldEndTime = 0 self.weapon = Weapon(self, level=1) self.controller = None self.controllerTimer = Timer(50) tileBlockedFunction = lambda tile: not tile is None and tile.blocksMovement self.movementHandler = MovementHandler(self, tileBlockedFunction) self.setLocation(location) self.setHeading(heading) self.lastHitTime = None self.lastHitVector = Vector(0, 0) self.destroyCallback = None self.destroyed = False
def renderPlayerHitpoints(self, targetSurface): image = images.get('ui_heart') startLocation = Vector(220, 240 - 11) for _ in range(gamecontroller.getPlayerTank().getHitpoints()): targetSurface.blit(image, startLocation.toIntTuple()) startLocation = startLocation.add(Vector(8, 0))
def renderLives(self, targetSurface): startLocation = Vector(0, 240 - 12) tankImage = images.get('tank1') for _ in range(gamecontroller.getLives()): targetSurface.blit(tankImage, startLocation.toIntTuple()) startLocation = startLocation.add(Vector(16, 0))
def createEnemyTank2(): turretOffsets = { \ Direction.NORTH: Vector(3, -2), \ Direction.EAST: Vector(4, 3), \ Direction.SOUTH: Vector(3, 4), \ Direction.WEST: Vector(-2, 3)} return TankGraphics(3, turretOffsets)
def createEnemyTank1(): turretOffsets = { \ Direction.NORTH: Vector(3, -1), \ Direction.EAST: Vector(2, 3), \ Direction.SOUTH: Vector(3, 1), \ Direction.WEST: Vector(-1, 3)} return TankGraphics(2, turretOffsets)
def createPlayerTank(): turretOffsets = { \ Direction.NORTH: Vector(3, -3), \ Direction.EAST: Vector(4, 3), \ Direction.SOUTH: Vector(3, 4), \ Direction.WEST: Vector(-3, 3)} return TankGraphics(1, turretOffsets)
def __init__(self): self.state = GameStates.MENU self.player = entities.Player(position=Vector(370, 480)) self.enemy_grid = entities.EnemyGrid(dimentions=(8, 3), position=Vector(100, 50), spacing=Vector(80, 90)) self.bullets = [] self.bombs = []
def createEnemyTank3(): turretOffsets = { \ Direction.NORTH: Vector(3, -3), \ Direction.EAST: Vector(2, 3), \ Direction.SOUTH: Vector(3, 2), \ Direction.WEST: Vector(-3, 3)} return TankGraphics(4, turretOffsets)
def render(self, screen, offset, time): extraOffset = Vector(0, 0) if not self.lastHitTime == None and time - self.lastHitTime > 50: extraOffset = self.lastHitVector.multiplyScalar(-1).toUnit() drawOffset = Vector(offset[0], offset[1]) self.graphics.render(screen, drawOffset.add(self.location).add(extraOffset), self.direction) self.controller.render(screen)
def draw_vector(self, vector: Vector, starting_point: Point): # Flip y since 0 0 is at top unscaled_vector_to_draw = BridgeGUI.flip_vector_on_y( vector).get_unit_vector() vector_tail = Vector.from_point(self.scale_point(starting_point)) vector_tip = unscaled_vector_to_draw * BridgeGUI.LENGTH_OF_VECTOR + vector_tail label_position = vector_tail + unscaled_vector_to_draw * BridgeGUI.LENGTH_TO_LABEL self.draw_line(vector_tail, vector_tip, arrow=True) self.draw_label(label_position, vector.get_magnitude().rescale(kN))
def __init__(self, position): self.image = pygame.image.load('data/enemy.png') self.width = self.image.get_rect()[2] self.hieght = self.image.get_rect()[3] self.position = position - Vector(self.width/2.0, self.hieght/2.0) self.step = Vector(30.0, 30.0) self.fire_chance = 0.05 self.fire_rate = 3.0 self.damage = 5 self.max_health = 10 self.health = self.max_health self.color = graphics.Colors.ENEMY
class Entity: def __init__(self): self.location = Vector(0, 0) self.size = Vector(0, 0) self.boundingRectangle = pygame.Rect(0, 0, 0, 0) self.disposable = False self.disposed = False def update(self, time, timePassed): pass def render(self, screen, offset, time): screen.blit(self.image, (int(offset[0] + self.location.x), int(offset[1] + self.location.y))) def getLocation(self): return self.location def setLocation(self, newLocation): self.location = newLocation self.updateBoundingRectangle() def getCenterLocation(self): return self.location.add(self.size.multiplyScalar(0.5)) def centerOn(self, location): self.move(location.subtract(self.size.multiplyScalar(0.5))) def move(self, movementVector): self.setLocation(self.location.add(movementVector)) def setSize(self, newSize): self.size = newSize self.updateBoundingRectangle() def updateBoundingRectangle(self): self.boundingRectangle = pygame.Rect(self.location.x, self.location.y, self.size.x, self.size.y) def markDisposable(self): self.disposable = True def dispose(self): self.disposed = True def getDirectionFromVector(self, vector): if vector.y < 0: return Direction.NORTH elif vector.y > 0: return Direction.SOUTH elif vector.x < 0: return Direction.WEST elif vector.x > 0: return Direction.EAST
def draw_beams(self, bridge: BridgeCalculator): for beam, beam_property in bridge.bridge.beams.items(): self.draw_line(self.scale_point(beam.joint1), self.scale_point(beam.joint2), color=beam_property.beam_group.color) if beam_property.member_force is not None: label_position = Vector.from_point( self.scale_point( beam.joint2)) + BridgeGUI.flip_vector_on_y( Vector.from_a_to_b(beam.joint2, beam.joint1) ) / 2 * self.scale_factor self.draw_label(label_position, beam_property.member_force.rescale(kN))
def _generate_bounding_rect(self): n1_p = Vector(*self.source_node.get_position()) n2_p = Vector(*self.link.target.get_position()) uv = (n2_p - n1_p).unit() start = n1_p + uv * self.source_node.get_radius() end = n2_p - uv * self.link.target.get_radius() #if multiple links ( always ) if self.link.link_num % 2 == 0: targetDistance = self.link.link_num * 2 else: targetDistance = (-self.link.link_num + 1) * 2 start = start.rotated_new(self.arrow_separation * targetDistance, n1_p) end = end.rotated_new(-self.arrow_separation * targetDistance, n2_p) if self.link._failed: link_color = Qt.red else: link_color = Qt.green #rect calculation r = self.weight_rectangle_size mid = (start + end) / 2 w_len = len(str(self.link.label)) * 4 weight_v = Vector(r if w_len <= r else w_len, r) weight_rectangle = QRectF(*(mid - weight_v), *(2 * weight_v)) if end.unit()[0] - start.unit()[0] > 0: link_paint = QLineF(QPointF(*start), QPointF(*end)) else: link_paint = QLineF(QPointF(*end), QPointF(*start)) center_of_rec_x = weight_rectangle.center().x() center_of_rec_y = weight_rectangle.center().y() rx = -(weight_v[0] * 0.5) ry = -(weight_v[1]) #new_rec = QRectF(rx , ry, weight_v[0], 2 * weight_v[1]) new_rec = QRectF(center_of_rec_x - 10, center_of_rec_y - 10, 15, 15).normalized() return new_rec
def __init__(self, location, directionVector, source, power=1, breaksConcrete=False): super().__init__() self.direction = self.getDirectionFromVector(directionVector) self.image = self.getImageBasedOnDirection() self.setSize(Vector(self.image.get_width(), self.image.get_height())) self.halfSize = math.ceil(self.size.x / 2) self.setLocation(location) self.directionVector = directionVector self.source = source self.power = power self.breaksConcrete = breaksConcrete self.lastMoveTime = pygame.time.get_ticks() tileBlockedFunction = lambda tile: not tile is None and tile.blocksProjectiles self.movementHandler = MovementHandler( self, tileBlockedFunction, entityIgnoreFunction=self.collisionIgnoreFunction)
def handleRightCollisions(self): collision = self.checkRightCollisions() if not collision is None: self.entity.setLocation(Vector(collision.location[0] - self.entity.size.x, self.entity.location.y)) return collision else: return None
def __init__(self, dimentions, position, spacing): self.move_rate = 10.5 self.enemies = [] for i in range(dimentions[0]): for j in range(dimentions[1]): x = position.x + spacing.x * i y = position.y + spacing.y * j # enemy = Jockey(position=Vector(x, y)) enemy = None for special in [Jockey, Hunter, Smoker, Boomer, Tank, Witch]: if random.random() < special.probability: enemy = special(position=Vector(x, y)) break if enemy == None: enemy = Hoard(position=Vector(x, y)) self.enemies.append(enemy)
def handleTopCollisions(self): collision = self.checkTopCollisions() if not collision is None: self.entity.setLocation(Vector(self.entity.location.x, collision.location[1] + collision.size[1])) return collision else: return None
def __init__(self, image, location, duration): super().__init__() self.image = image self.setSize(Vector(self.image.get_width(), self.image.get_height())) self.centerOn(location) self.creationTime = pygame.time.get_ticks() self.duration = duration
def total_angle(self): """ The total angle in radians from start_point to end_point """ if self._total_angle is None: self._total_angle = Vector.angle_between(self(0), self(1)) return self._total_angle
def __init__(self, position, damage): self.image = pygame.image.load('data/bullet.png') self.width = self.image.get_rect()[2] self.hieght = self.image.get_rect()[3] self.position = position self.velocity = Vector(0, -200) self.damage = damage
def handleBottomCollisions(self): collision = self.checkBottomCollisions() if not collision is None: self.entity.setLocation(Vector(self.entity.location.x, collision.location[1] - self.entity.size.y)) return collision else: return None
def handleLeftCollisions(self): collision = self.checkLeftCollisions() if not collision is None: self.entity.setLocation(Vector(collision.location[0] + collision.size[0], self.entity.location.y)) return collision else: return None
def __init__(self, position, damage, color): self.width = 10 self.hieght = self.width self.rect = pygame.Rect(0, 0, self.width, self.hieght) self.position = position self.velocity = Vector(0, 350) self.damage = damage self.color = color
def add_point_load(self, loaded_joint: Point, load_force: float): """ Joint load must be applied between two supports """ external_forces_y_pos = None for support in self.supports: external_forces_y_pos = support.y break if external_forces_y_pos != loaded_joint.y: raise Exception("Joint load is not horizontally inline with supports.") supports_x_pos = sorted([support.x for support in self.supports]) for i, x_pos in enumerate(supports_x_pos): left_neighbour = None if i == 0 else supports_x_pos[i - 1] right_neighbour = None if i == len(supports_x_pos) - 1 else supports_x_pos[i + 1] # If outside of neighbours, no weight on me if left_neighbour is not None and loaded_joint.x <= left_neighbour: continue if right_neighbour is not None and loaded_joint.x >= right_neighbour: continue # Between current joint and right joint if loaded_joint.x > x_pos: if right_neighbour is None: raise Exception( "Joint load seems to be applied to the right of all supports. Must be between supports") reaction_force = load_force * (loaded_joint.x - x_pos) / (right_neighbour - x_pos) self.bridge.joints[Point(x_pos, loaded_joint.y)].external_force = Vector(0 * kN, reaction_force) # Between current joint and right joint elif loaded_joint.x < x_pos: if left_neighbour is None: raise Exception( "Joint load seems to be applied to the left of all supports. Must be between supports.") reaction_force = load_force * (x_pos - loaded_joint.x) / (x_pos - left_neighbour) self.bridge.joints[Point(x_pos, loaded_joint.y)].external_force = Vector(0 * kN, reaction_force) else: self.bridge.joints[Point(x_pos, loaded_joint.y)].external_force = Vector(0 * kN, load_force) self.bridge.joints[loaded_joint].external_force = Vector(0 * kN, -load_force)
def __init__( self, initial_coordinate: ArrayLike, final_coordinate: ArrayLike, atmosphere_params: ArrayLike, operating_frequency: float, point_number: Optional[int] = None, use_high_ray: Optional[bool] = True, ): """ supply initial and final points, atmosphere parameters (f_0, r_m, y_m) and operating_frequency (f) :param initial_coordinate : array_like, shape (3,) the cartesian coordinates of the path start :param final_coordinate : array_like, shape (3,) the cartesian coordinates of the path end :param atmosphere_params : Tuple, shape (3,) the atmosphere parameters as a tuple of (max_plasma_frequency (f_0), height_of_max_plasma_frequency(r_m), layer_semi_width(y_m)) :param operating_frequency: float The operating frequency of the ray :param point_number : int The number of points to interpolate between in the final path :param use_high_ray : bool Whether or not to use high ray """ super().__init__() # Initial and final points are normalized, but poly_fit(0) and poly_fit(1) will return the radial component # for the initial and final point initial_rad, final_rad = linalg.norm(initial_coordinate), linalg.norm(final_coordinate) self.initial_point = initial_coordinate / linalg.norm(initial_coordinate) self.final_point = final_coordinate / linalg.norm(final_coordinate) self.normal_vec = np.cross(self.initial_point, self.final_point) self.normal_vec = self.normal_vec / linalg.norm(self.normal_vec) angle_between = Vector.angle_between(initial_coordinate, final_coordinate) # Parameters for quasi-parabolic path only depend on atmospheric model and ignore magnetic field self._parameters = self.calculate_parameters(atmosphere_params, operating_frequency) # Point number is the number of points to calculate. All points in between are interpolated from PC spline if point_number is not None: self.point_number = point_number else: self.point_number = int(angle_between * EARTH_RADIUS) # Each point is evenly spaced along the great circle path connecting initial and final coordinates # Each point is a 2-vector holding its angular value in radians (along great circle path) # and its radial value at each point (in km) self.points = np.zeros((self.point_number, 2)) self.points[:, 0] = np.linspace(0, angle_between, self.point_number) self.points[:, 1] = np.linspace(initial_rad, final_rad, self.point_number) # Real representation of the line will be a poly fit of radius vs angle along great circle self._poly_fit = None self._total_angle = None self.using_high_ray = use_high_ray
def createRandomPowerupAtRandomLocation(self): location = self.getRandomPowerupLocation() if location == None: return None else: powerup = self.createRandomPowerup() powerup.setLocation( Vector(location[0] * playfield.blockSize, location[1] * playfield.blockSize)) return powerup
def __init__(self, resolution): self.state = States.MAIN self.resolution = resolution self.walls = 0.02 self.count = 100 self.boids = [] for _ in range(self.count): position = Vector(np.random.random()*resolution[0]*0.80 + resolution[0]*0.10, np.random.random()*resolution[1]*0.80 + resolution[1]*0.10) angle = np.random.random()*360 self.boids.append(entities.Boid(position, angle))
def add_uniformly_distributed_load(self, load_per_unit_length): external_forces_y_pos = None for support in self.supports: external_forces_y_pos = support.y break load_bearing_joints_x_pos = [] for joint in self.bridge.joints: if joint.y == external_forces_y_pos: load_bearing_joints_x_pos.append(joint.x) load_bearing_joints_x_pos = sorted(load_bearing_joints_x_pos) supports_x_pos = sorted([support.x for support in self.supports]) # Loop from left to right throughout the joints for i, x_pos in enumerate(load_bearing_joints_x_pos): if i == 0: dist_to_neighbouring_joints = (load_bearing_joints_x_pos[i + 1] - x_pos) elif i < len(load_bearing_joints_x_pos) - 1: dist_to_neighbouring_joints = (load_bearing_joints_x_pos[i + 1] - load_bearing_joints_x_pos[i - 1]) else: dist_to_neighbouring_joints = (x_pos - load_bearing_joints_x_pos[i - 1]) self.bridge.joints[ Point(x_pos, external_forces_y_pos)].external_force = Vector(0 * pq.N, dist_to_neighbouring_joints / -2 * load_per_unit_length) for i, x_pos in enumerate(supports_x_pos): if i == 0: dist_to_neighbouring_joints = (supports_x_pos[i + 1] - x_pos) elif i < len(supports_x_pos) - 1: dist_to_neighbouring_joints = (supports_x_pos[i + 1] - supports_x_pos[i - 1]) else: dist_to_neighbouring_joints = (x_pos - supports_x_pos[i - 1]) self.bridge.joints[Point(x_pos, external_forces_y_pos)] \ .external_force += Vector(0 * pq.N, dist_to_neighbouring_joints / 2 * load_per_unit_length)