enemy.rb 1.01 KB
class Enemy < Ship

  def initialize game, options
    super game, options

    @pos = [rand(game.screen.size[0] - size[0]), 0 - size[1]]
    @body.p = CP::Vec2.new(*@pos)
    @body.v += CP::Vec2.new(0.0, @params[:speed] / 10.0)
    @thread = Thread.start do
      loop do
        break  unless @visible
        begin
          fire
        rescue
          p $!
          puts *$@
          end
        sleep rand(2)
      end
    end
  end

  def draw screen
    return passed  if pos[1] > @game.screen.size[1]
    super screen
  end

  def passed
    hide
    @game.enemies.delete(self)
    return  unless @game.state == :running
    @game.player.score -= @power * @game.level
    @game.flash_hud :red
    @game.player.destroy  if @game.player.score < 0
    @thread.kill
  end

  def destroy
    super
    @game.player.score += @params[:power]
    @game.flash_hud :green
    @thread.kill
  end

  def self.generate game
    e = new(game, p: [0, 0], type: [:glider, :drone, :fighter].sample)
    e.show
    game.enemies << e
  end

end