--Prevent standalone execution: if not TRAINSPORTED then print("To prevent players from harm, this file may only be executed by the trAInsported game.") return end --AI by xnor: -- trAInsported AI "Derplord Prime" -- version 0.1 -- buy a train and place it at a random location function newTrain() xPos = random(globalMap.width) yPos = random(globalMap.height) buyTrain(xPos, yPos) end function ai.init(map) globalMap = map globalDebug = false newTrain() end function debug(string) if globalDebgug == true then print(string) end end function ai.enoughMoney() if globalDebug == false then newTrain() end end -- calculate the distance between points (x1, y1) and (x2, y2) function distance(x1, y1, x2, y2) return sqrt((x1 - x2)^2 + (y1 - y2)^2) end -- pick the passenger who's destination is closest function ai.foundPassengers(train, passengers) pass = nil dist = 100 i = 1 while i <= #passengers do d = distance(train.x, train.y, passengers[i].destX, passengers[i].destY) if d < dist then dist = d pass = passengers[i] end i = i + 1 end return pass end -- if we have a passenger, choose the direction towards our destination, -- else go to a random direction function ai.chooseDirection(train, directions) dirList = {} for k, v in pairs(directions) do if v == true then table.insert(dirList, k) end end if train.passenger == nil then return dirList[random(#dirList)] else destX = train.passenger.destX destY = train.passenger.destY -- try to go straight up or down if (train.x == destX) then if train.y > destY and train.dir == "N" then if directions["N"] == true then debug(train.name .. " ^^") return "N" end elseif train.y < destY and train.dir == "S" then if directions["S"] == true then debug(train.name .. " vv") return "S" end end end -- try to go straight left or right if (train.y == destY) then if train.x < destX and train.dir == "E" then if directions["E"] == true then debug(train.name .. " >>") return "E" end elseif train.x > destX and train.dir == "W" then if directions["W"] == true then debug(train.name .. " <<") return "W" end end end -- try to go diagonal if (train.x < destX) and (directions["E"] == true) then debug(train.name .. " >") return "E" elseif (train.x > destX) and (directions["W"] == true) then debug(train.name .. " <") return "W" elseif (train.y < destY) and (directions["S"] == true) then debug(train.name .. " v") return "S" elseif (train.y > destY) and (directions["N"] == true) then debug(train.name .. " ^") return "N" end -- fallback: choose a random direction debug(train.name .. " ?") return dirList[random(#dirList)] end end -- drop passengers at their destination function ai.foundDestination(train) dropPassenger(train) end