ship.rb 2.01 KB
class Ship < Movable

  SHIPS = {
    glider: { power: 50, shield: 20, speed: 2.5, weapons: [:laser],
      image: { image: "ship.png", zoom: 0.5 }},
    drone: { power: 75, shield: 50, speed: 2, weapons: [:missile],
      image: { image: "ship.png", zoom: 0.7 }},
    fighter: { power: 100, shield: 100, speed: 1, weapons: [
        :laser, :torpedo, :missile ],
      image: { image: "ship.png", zoom: 1.0 }},
    spinner: { power: 50, shield: 50, speed: 2, rot: 0.1, weapons: [:laser],
      image: { image: "ship2.png", zoom: 0.3 }},
  }

  attr_accessor :power, :image, :type, :debug
  def initialize game, options
    @params = SHIPS[options[:type]]
    options.merge!(m: 1000.0, ctype: :ship, v_limit: 3.0)
    image = @params[:image]
    image[:rot] = is_a?(Enemy) ? 0.0 : 180.0
    super game, options.merge(image)
    @max_power = @params[:power] * 2
    @power = @params[:power]
    @weapons = @params[:weapons].map {|w| Weapon.new(self, w) }
  end

  def draw *a
    p, v = pos, vel
    p[0], v[0] = 0, 0 if p[0] < 0
    p[1], v[1] = 0, 0 if p[1] < 0
    p[0], v[0] = screen.size[0], 0 if p[0] > screen.size[0]
    p[1], v[1] = screen.size[1], 0 if p[1] > screen.size[1]
    if pos != p
      @body.p = CP::Vec2.new(*p)
    end
    @body.w = @params[:rot]  if @params[:rot]
    super *a
  end

  def fire
    @weapons.each(&:fire)
  end

  def take_damage damage
    @power -= damage
    if @power <= 0
      @power = 1
      destroy
    end
    @debug = nil
  end

  def size
    [@surface.size[0] - 10, @surface.size[1] - 10]
  end

  def hit other, damage
    @power += damage / 5
    @power = @max_power  if @power > @max_power
  end

  def destroy
    return  unless @alive
    @game.enemies.delete(self)
    Explosion.new(@game, p: pos, image: "explosion.png",
      zoom: options[:zoom] * 1.25, volume: options[:zoom]) { hide }.show
    @alive = false
  end

  def debug
    text = "[ #{@type}: #{@power}, v: #{@body.v}, a: #{@body.a}, m: #{@body.m} ]"
    @debug = @game.font("FreeSans").render(text, false, :white).to_display
  end

end