Tuesday, March 26, 2013

'RTanque' Part 3: Basic Targeting


This guide covers how to make a simple targeting tank bot with 'RTanque'.

 (1) Making a basic 'RTanque' tank bot.


Now that you all have seen how to build a basic tank in part 1, and how to clone multiple bots in part 2, we are now going to show you how to make a simple bot that knows how to target other tanks.


 
class BasicBot < RTanque::Bot::Brain
 Getting Started With 'RTanque' Part:1 of 4

class BasicBot < RTanque::Bot::Brain
  NAME = 'basic_bot'
  include RTanque::Bot::BrainHelper
  def tick!
    ## main logic goes here
    # use self.sensors to detect things
    # use self.command to control tank
    # self.arena contains the dimensions of the arena
    self.make_circles
    self.command.fire(0.25)
  end
  def make_circles
  command.speed = MAX_BOT_SPEED # takes a value between -5 to 5 
  command.heading = sensors.heading + 0.01
  end
end  

(2) Now we add the targeting code to the BasicBot.

class BasicTargetingBot < RTanque::Bot::Brain
  NAME = 'basic_targeting_bot'
  include RTanque::Bot::BrainHelper

  TURRET_FIRE_RANGE = RTanque::Heading::ONE_DEGREE * 1.5

# This is a constant, we don't want it to change,
# we use this constant in pointing_at_target? method,
#to make sure our tank's barrel is pointing at the target.

  def tick!
    ## main logic goes here
    # use self.sensors to detect things
    # use self.command to control tank
    # self.arena contains the dimensions of the arena

    self.make_circles
    if we_have_target
      target = we_have_target
      track_target(target)
      aim_at_target(target)
      fire_at_target(target)
    else
      self.scan_with_radar
    end
     
 # self.command.fire(0.25) replaced fire_at_target
  end

  def make_circles
    command.speed = 5 #MAX_BOT_SPEED # takes a value between -5 to 5 
    command.heading = sensors.heading +  MAX_BOT_ROTATION # or you can do something like 0.01 instead of MAX_BOT_ROTATION
  end

  def we_have_target
    self.nearest_target
  end

  def nearest_target
    self.sensors.radar.min { |a,b| a.distance <=> b.distance }
  end

  def track_target(target)
    self.command.radar_heading = target.heading
  end

  def aim_at_target(target)
    self.command.turret_heading = target.heading
  end
  def fire_at_target(target)
    if self.pointing_at_target?(target)
      command.fire(MAX_FIRE_POWER)
    end
  end

  def pointing_at_target?(target)
    (target.heading.delta(sensors.turret_heading)).abs < TURRET_FIRE_RANGE 
  end

  def scan_with_radar
    self.command.radar_heading = self.sensors.radar_heading + MAX_RADAR_ROTATION
  end
end
  
 This is an basic, easy guide to making an 'RTanque' a targeting tank bot. Next up part 4: "Making an "invincible" 'RTanque' tank bot.

 This is Part 3 of a 4 part series on 'RTanque' tank bot making. Cody Kemp @codesterkemp and myself Joshua Kemp @joshuakemp1 will be joint authors during this series.