Programming robots
Starting with release 011, server admins will be able to program their own robots in addition to designing their own levels. Robots will be coded in Lua, and will will have a number of special functions available to them.
Robot coding is still fluid, and everything is subject to change, but here is a list of commands being implemented for the next alpha release (see forums for the URL):
How to read the function notation:
returnType funtionName( argType1, argType2 ) - Description of function
Return types:
Unlike most languages, Lua does not differentiate between integers and floating point numbers. Instead, everything is simply a number.
Points to remember in Lua:
- Lua arrays are 1-based: the first index is 1 rather than 0 as is the case in most programming languages
Contents
number getTime() - Returns time for this frame, in ms.
number getCPUTime() - Returns number representing the CPU time in ms. Can be used to time events
Example:
lastTime = thisTime thisTime = bot:getCPUTime() bot:logprint(thisTime - lastTime.." ms have elapsed since we were last here.")
getZoneCenter( x, y ) - Return point representing center of zone containing point x,y
getGatewayFromZoneToZone( a, b ) - Return point representing fastest way from zone a to zone b. If zones a & b are not neighbors, returns nil
number getZoneCount() - Return number of zones
number getCurrentZone() - Return current zone that robot is in
number getAngle() - Return angle robot is currently facing
Point getLoc() - Return point representing location of robot
Example:
-- This code in getMove() loc = bot:getLoc() -- Get robot's location once items = bot:findItems( AsteroidType ) -- Get list of all asteroids -- Now find the closest one minDist = 99999999; asteroid = nil; for indx, item in ipairs( items ) do -- Iterate over our list -- Use distSquared because it is less computationally expensive -- and works great for comparing distances d = loc:distSquared( item:getLoc() ) -- Dist btwn robot and asteroid if( d < minDist ) then -- Is it the closest yet? asteroid = item minDist = d end end if( asteroid == nil ) then -- Make sure we found one return end
void setAngle( ang ) - Point robot at angle
void setAngleXY( x, y ) - Point robot towards point x,y
number getAngleXY( x, y ) - Compute angle to point x, y
boolean hasLosXY( x, y ) - Return whether or not robot can see point x, y
number getFiringSolution (item ) - Calculate angle at which robot needs to fire to hit moving or stationary object. Will return nil if the item is out of range, behind an obstacle, or firing will hit a friendly ship. Always check the return value for nil!
Example:
loc = bot:getLoc() -- Our current location items = bot:findGlobalItems( SoccerBallItemType ) -- Find a soccer ball -- Now loop through all returned items and find the closest minDist = 99999999; ball = nil; for indx, sb in ipairs( items ) do l = sb:getLoc() -- Ball's location -- Distance from ship to ball (use distSquared because -- it is easy to compute and good for comparison) d = loc:distSquared(l) if( d < minDist ) then ball = sb minDist = d end end -- Check to make sure we found a soccer ball... could be out of view if(sb == nil) then return end ang = bot:getFiringSolution( sb ) -- Get shooting angle to hit moving ball -- Always check for nil: could happen if ball -- were behind a wall or friendly ship if( ang == nil ) then return end bot:setAngle( ang ) -- Ready... aim... bot:fire() -- ..fire!
number getTeamIndx() - Return index of team this robot is on
boolean hasFlag() - Return whether or not robot currently has the flag
WeaponType getActiveWeapon() - Return currently selected weapon
Example:
weap = bot:getActiveWeapon() -- Get info about our currently active weapon weapInfo = WeaponInfo( weap ) -- Get information about it bot:logprint( weapInfo:getName().." has a range of "..weapInfo:getRange() )
Modules are automatically disabled at the end of each game cycle. Therefore, if you want to keep a module on for a sustained period of time, you must activate it each time getMove() is called. To activate a module, use one of the activateModule() commands.
void activateModule(ModuleType) - Activate module, specified by ModuleType. If specified module is not included in the current loadout, this command will have no effect. Example:
-- Note that this line will do nothing if we don't have shields bot:activateModule( ModuleShield ) -- Shields up!
void activateModuleIndex(indx) - Activate module, specified by its index (1 or 2)
Example:
-- Must specify an index, currently either 1 or 2 bot:activateModuleIndex( 1 ) -- Activate first module, whatever it is
void setReqLoadout(Loadout) - Set the requested loadout to Loadout
Loadout getCurrLoadout() - Returns current loadout
Example:
loadout = bot:getCurrLoadout() -- Retrieve current bot configuration weapType1 = loadout:getWeapon(1) -- Get the first weapon weapType2 = loadout:getWeapon(2) -- Get the second weapon weapType3 = loadout:getWeapon(3) -- Get the third weapon -- Check to see if the first weapon is a phaser if ( weapType1 == WeaponPhaser ) then bot:logprint("First weapon is a phaser!") end -- Print a list of our three current weapons bot:logprint( "My three weapons are: "..WeaponInfo(weapType1):getName()..", " ..WeaponInfo(weapType2):getName()..", and " ..WeaponInfo(weapType3):getName() )
Loadout getReqLoadout() - Returns requested loadout
Navigation
[Item list]findItems(ObjectType, ...) - Return a list of items of the specified type or types that are within the robot's viewable area
[Item list]findItems(ObjectType, ...) - Return a list of items of the specified type or types that are anywhere in the game. Note that items that would ordinarily be out of scope will not be included in this list!
Example:
-- Find all resource items in the normal viewport items = bot:findItems( ResourceItemType ) -- You can specify multiple item types if you want -- Get a list of all TestItems or Asteroids that are visible anywhere -- (note that items that are out-of-scope will be omitted) items = bot:findGlobalItems( TestItemType, AsteroidType ) -- Now iterate over the list... there are many examples in the documentation! for indx, item in ipairs( items ) do -- Do something with item... perhaps figure out which is closest, -- which is heading towards us, etc. end
getWaypoint(x, y)
Ship control
void setThrust( vel, angle ) - Set robot's velocity to vel (0-1), at angle
void setThrustXY( vel, x, y ) - Set robot's velocity to vel (0-1), toward coordinates x, y
void fire() - Fires active weapon
void setWeaponIndex( index ) - Activates weapon with index (1, 2, 3)
void setWeapon( WeaponType ) - Activates weapon type specified (does nothing if WeaponType is not in current loadout)
boolean hasWeapon (WeaponType ) - Does current configuation have specified weapon
Example:
if ( bot:hasWeapon( WeaponMine ) ) then bot:setWeapon( WeaponMine ) -- Make mine layer active, if it's -- part of our current loadout bot:fire() -- Lay a mine end
void globalMsg( msg ) - Send a message to all players
void teamMsg( msg ) - Send a message to players on the same team
void logprint(msg) - Print msg to game logfile
GameItems
The Lua object structure generally follows that used by Bitfighter. The GameItems group conisists of Ships, Robots, RepairItems, Asteroids, ResourceItems, SoccerBallItems, Flags, NexusFlags, and TestItems. These all share similar properties, and have similar methods. All of these implement the getLoc(), getVel(), and getRad() methods for querying location, velocity, and radius respectively. Some items have additional methods that apply only to them. See below for details on these additional methods.
Ships & Robots
Point getLoc() - Center of item
number getRad() - Radius of item
Point getVel() - Speed of item
number getTeamIndx() - Index of the team this ship/robot is on
boolean isModuleActive( ModuleType ) - Returns true if specified module is active
TestItems, ResourceItems, and SoccerBallItems
These items all have the same methods and behave in a very similar manner.
Category: GameItem
Point getLoc() - Center of item
number getRad() - Radius of item
Point getVel() - Speed of item
Example:
items = bot:findItems( TestItemType ) -- Get a list of all TestItems in view -- Now cycle through all returned items and find the fastest one maxSpeed = -1 fastest = nil for indx, ti in ipairs( items ) do -- getVel() returns a point representing the x and y components of -- the velocity. Need to use len() to get actual speed. Or, in this -- case, since actual speed isn't important, we can use lenSquared() -- which is less computationally intensive, and will yield perfectly -- good results for comparison purposes (such as finding the fastest). spd = ti:getVel():lenSquared() if( spd > maxSpeed ) then fastest = ti maxSpeed = spd end end -- Better check to make sure fastest isn't nil before using it! -- Could be nil if there are no TestItems in view if( fastest != nil ) then -- Do something end
Asteroids
Category: GameItem
Point getLoc() - Center of asteroid
number getRad() - Radius of asteroid
Point getVel() - Speed of asteroid
number getSize() - Index of current asteroid size (0 = initial size, 1 = next smaller, 2 = ...)
number getSizeCount() - Number of indexes of size we can have
Example:
asteroid = bot:findAsteroid() -- Function likely to change target = asteroid:getLoc()
RepairItems
Category: GameItem
Point getLoc() - Center of RepairItem
number getRad() - Radius of RepairItem
Point getVel() - Speed of RepairItem (usually 0,0)
boolean isVis() - Is repair item currently visible?
Example:
ri = bot:findRepairItem() -- Function likely to change vel = ri:getVel()
Flags
Category: GameItem
Point getLoc() - Center of Flag
number getRad() - Radius of Flag
Point getVel() - Speed of Flag (usually 0,0)
number getTeamIndx() - Get index of owning team (-1 for neutral flag)
boolean inInitLoc() - Is flag in it's initial location?
boolean inCaptureZone() - Is flag in a team's capture zone?
boolean isOnShip() - Is flag being carried by a ship?
NexusFlags
Category: GameItem
Note: Only appears in Nexus games.
Point getLoc() - Center of NexusFlag
number getRad() - Radius of NexusFlag
Point getVel() - Speed of NexusFlag
Turrets and ForceFieldProjectors
Point getLoc() - Center of NexusFlag
number getRad() - Radius of NexusFlag
Point getVel() - Speed of NexusFlag
number getTeamIndx() - Get index of owning team (or -1 for neutral, -2 for hostile)
number getHealth() - Get health of item (1 = full heath, 0 = totally dead)
boolean isActive() - True if item is active, false otherwise
Weapon Information
All the WeaponInfo data will remain constant throughout the game. Therefore, if you need some information about a weapon, it might make sense to retrieve it in the bot's header and store it in a local variable rather than instantiating a new WeaponInfo object during every loop of the robot's getMove() method.
Example:
weap = bot:getActiveWeapon() -- Get bot's currently active weapon bot:logprint( weap:getName().." has a range of "..weap:getRange() )
weap = WeaponInfo( WeaponTurret ) -- Get info about those infernal turrets bot:logprint( weap:getName().." shoots with a speed of "..weap:getProjVel() )
string getName() - Name of weapon ("Phaser", "Triple", etc.)
WeaponType getID() - ID of module (WeaponPhaser, WeaponTriple, etc.)
number getRange() - Get range of weapon (units)
number getFireDelay() - Delay between shots in ms
number getMinEnergy() - Minimum energy needed to use
number getEnergyDrain() - Amount of energy weapon consumes
number getProjVel() - Speed of projectile (units/sec)
number getProjLife() - Time projectile will live (ms) -1 == live forever)
number getDamage() - Damage projectile does (0-1, where 1 = total destruction)
boolean getCanDamageSelf() - Will weapon damage self?
boolean getCanDamageTeammate() - Will weapon damage teammates?
WeaponType constants
WeaponPhaser | WeaponBounce |
WeaponTriple | WeaponBurst |
WeaponMine | WeaponSpyBug |
WeaponTurret |
Module Information
Example:
mod = ModuleInfo( ModuleBoost ) bot:logprint( "This is a lame example!" )
string getName() - Name of module ("Shield", "Turbo", etc.)
ModuleType getID() - ID of module (ModuleShield, ModuleBoost, etc.)
ModuleType constants
ModuleShield | ModuleBoost |
ModuleSensor | ModuleRepair |
ModuleCloak | ModuleEngineer (maybe someday) |
Loadouts
void setWeapon(index, WeaponType) - Set weapon at index
void setModule(index, ModuleType) - Set module at index
WeaponType getWeapon(index) - return weapon at index
ModuleType getModule(index) - return module at index
Example:
-- Get a new loadout (comes pre-filled with default values) loadout = Loadout() -- Configure the loadout to suit our needs loadout:setWeapon( 1, WeaponPhaser ) loadout:setWeapon( 2, WeaponBurst ) loadout:setWeapon( 3, WeaponMine ) loadout:setModule( 1, ModuleShield ) loadout:setModule( 2, ModuleCloak ) -- Set the loadout, will become active when bot hits loadout zone -- or spawns, depending on game bot:setReqLoadout( loadout ) if( loadout:getWeapon(1) == WeaponPhaser) then bot:logprintf( "This line always gets printed!" ) end
boolean isValid() - Is loadout config valid?
boolean equals(Loadout) - is loadout the same as Loadout?
GameInfo
You can get information about the current game with the GameInfo object. You only need get this object once, then you can use it as often as you like. It will always reflect the latest data.
Example:
game = GameInfo() -- Create the GameInfo object gameType = game:getGameType() if( gameType == SoccerGame ) then bot:logprint("This bot is not very good at soccer!") else gameTypeName = game:getGameTypeName() bot:logprintf("I just love playing "..gameTypeName.."!") end
Example:
-- Create the GameInfo object in header: game = GameInfo() ... -- Even though we only create our GameInfo once, it is always current ... -- Later, in getMove(): remTime = game:getGameTimeReamaining() totTime = game:getGameTimeTotal() percent = ( totTime - remTime ) / remTime bot:logprint( "Game is "..percent.."% over )
GameType getGameType() - Return current game typet)
string getGameTypeName() - Return current game type
number getFlagCount() - Return the number of flags in the game
number getWinningScore() - Returns the score required to win the level
number getGameTimeTotal() - Returns the time (in seconds) that the level will be played for
number getGameTimeRemaining() - Returns the time remaining (in seconds) for this level
number getLeadingScore() - Gets score of the leading team
number getLeadingTeam() - Gets index of leading team
number getTeamCount() - Return number of teams
Example:
-- Create the GameInfo object in header: game = GameInfo() ... -- Then later... ... leadingTeam = game:getLeadingTeam() team = TeamInfo( leadingTeam ) bot:teamMsg( "Hurry up! Team "..team:getName().." is winning!" )
string getLevelName() - Gets the level's name
number getGridSize() - Gets the level's gridSize parameter
boolean getIsTeamGame() - Is this a team game?
getEventScore(ScoringEvent)
GameType constants
BitmatchGame | CTFGame |
HTFGame | NexusGame |
RabbitGame | RetrieveGame |
SoccerGame | ZoneControlGame |
ScoringEvent constants
KillEnemy | KillSelf |
KillTeammate | KillEnemyTurret |
KillOwnTurret | CaptureFlag |
CaptureZone | UncaptureZone |
HoldFlagInZone | RemoveFlagFromEnemyZone |
RabbitHoldsFlag | RabbitKilled |
RabbitKills | ReturnFlagsToNexus |
ReturnFlagToZone | LostFlag |
ReturnTeamFlag | ScoreGoalEnemyTeam |
ScoreGoalHostileTeam | ScoreGoalOwnTeam |
TeamInfo
string getName() - return team name
number getIndex() - return team's index, index of first team is 1
number getPlayerCount() - return player count
number getScore() - return team score
Example:
gameInfo = GameInfo() teams = gameInfo:getTeamCount() -- Note that while the number of teams will not change throughout the game, -- the number of players on each team might. Also, the robot may be initialized -- before the players have been added, so if you run this code in the bot header, -- it may report some teams having 0 players. for i = 1, teams do -- First team has an index of 1 team = TeamInfo( i ) bot:logprint( "Team "..i.." is called "..team:getName().. " and has "..team:getPlayerCount().." players" ) end
Timers
Timer is a utility class that makes it easier to manage timing periodic or delayed events.
void reset() - Reset the timer.
number getTime() - Returns time left on the timer (in ms)
number getFraction() - Returns the fraction of the timer left (1 = all time left, 0 = no time left)
void setPeriod( time ) - Set the time on the timer, and resets it.
boolean update( time ) - Update the timer by the specified amount of time (in ms), and return true if timer has gone off. Use bot:getTime() as the time parameter.
Example:
-- In header: timer = Timer( 1000 ) -- Set timer that will go off every second ... -- Then later, in getMove() ... if( timer:update( bot:getTime() ) ) then -- Always update with bot:getTime() bot:logprint("1 sec has elapsed!") -- Msg will get printed every second timer:reset() -- Start timer over end
Points
Point is a utility class to make handling coordinates or vectors simpler. You can create your own point objects using the constructor, or you can get them as return values from many functions.
Point Point( x, y ) - Create a new Point object with coordinates x, y. You do not need to use setxy() unless you want to change the coords later.
number x() - Return x value
number y() - Return y value
setxy( x, y ) - Update coordinates of point
setx( x ) - Update x coordinate of point
sety( y ) - Update y coordinate of point
number len() - Returns the length of the point, useful if point represents a velocity or other vector
number lenSquared() - Returns the length squared of the point, useful if point represents a velocity or other vector, and you want a less computationally expensive representation of length that will work for comparative purposes
boolean equals( Point ) - Returns true if the point is the same as Point
void normalize( length ) - If Point represents a vector, set its length to length
number distanceTo( Point ) - Returns distance from point to Point
number distSquared( Point ) - Returns distance squared from point to Point (less computationally intensive, good for comparison)
number angleTo( Point ) - Returns angle from point to Point
Example:
point = Point( 0, 0 ) -- Create a new point if( point:equals( Point( 1, 1 ) ) then bot:logprint( "This never gets printed" ) end if( point:distanceTo( Point( 1, 1 ) < 5 ) then bot:logprint( "This always gets printed" ) end -- Here we'll use a point to represent a velocity, which has x & y components xspeed = 10 yspeed = 15 velocity = Point( xspeed, yspeed ) bot:logprint( "Speed = "..velocity:len() )
ItemTypes
ShipType
BarrierType
MoveableType
BulletType
ForceFieldType
LoadoutZoneType
MineType
NexusFlagType
TurretTargetType
SlipZoneType
HeatSeekerType
SpyBugType
NexusType
BotNavMeshZoneType
RobotType
TeleportType
implemented
ResourceItemType
GoalZoneType
AsteroidType
TurretType
ForceFieldProjectorType
TestItemType
FlagType
SoccerBallItemType