Vicevirtuoso
The Modetta Man
So, I stitched together this code, which is passed a unit pointer and returns the pointer of the City-State which is closest to that unit on the map.
The code works, but it looks hideous and I'm sure there's a much simpler, cleaner, and faster way of doing it. The way I had to make math.min() work makes me cringe, since it doesn't work with sparse arrays.
Any folks who actually know how to write clean code have any tips?
Code:
function GetCityStateNearestToUnit(unit)
local tCityStatePlots = {};
local tPlotDistances = {};
local iKey;
local iShortestDistance;
local pNearestCS;
for i, pCityState in pairs(Players) do
if pCityState:IsMinorCiv() then
for pCSCity in pCityState:Cities() do
tCityStatePlots[i] = pCSCity:Plot();
print("Added plot of " ..pCityState:GetCivilizationShortDescription().. " to tCityStatePlots")
end
end
end
for i=0, GameDefines.MAX_CIV_PLAYERS do
if tCityStatePlots[i] then
tPlotDistances[i] = Map.PlotDistance(tCityStatePlots[i]:GetX(), tCityStatePlots[i]:GetY(), unit:GetX(), unit:GetY());
print("Plot distance between player " ..i.. " and Incubator is " ..tPlotDistances[i])
else
tPlotDistances[i] = 999999
end
end
iShortestDistance = math.min(unpack(tPlotDistances));
print("Shortest distance determined to be " ..iShortestDistance)
iKey = GetKeyForTableValue(tPlotDistances, iShortestDistance);
print("Key value for table which corresponds with that distance is " ..iKey)
pNearestCS = Players[tCityStatePlots[iKey]:GetOwner()]
print("Determined that the closest City-State is " ..pNearestCS:GetCivilizationShortDescription())
return pNearestCS
end
function GetKeyForTableValue(t, value)
for k,v in pairs(t) do
if v==value then
return k
end
end
end
The code works, but it looks hideous and I'm sure there's a much simpler, cleaner, and faster way of doing it. The way I had to make math.min() work makes me cringe, since it doesn't work with sparse arrays.
Any folks who actually know how to write clean code have any tips?