dcearth/cities.lua

87 lines
2.1 KiB
Lua
Raw Normal View History

2023-04-28 17:35:52 +00:00
--Load and save the fixed width plaintext data used by DEFCON.
2023-07-28 05:42:16 +00:00
local t = { visible = true, active = false}
2023-04-28 17:35:52 +00:00
local io = io
local math = math
2023-04-28 17:35:52 +00:00
local table = table
local tonumber = tonumber
local lfs = love.filesystem
local lg = love.graphics
local locationQuery = require 'locationQuery'
2023-04-28 17:35:52 +00:00
local cities
local points = {}
local caps = {}
t.selectedCity = nil
2023-04-28 17:35:52 +00:00
function t.draw()
2023-07-28 05:42:16 +00:00
if t.visible then lg.points( points ) end
2023-04-28 17:35:52 +00:00
end
function t.drawSelected( r )
2023-07-28 05:42:16 +00:00
if not t.visible then return end
local c = t.selectedCity
if not c then return end
lg.circle( "fill", c.x, c.y, r )
end
2023-04-28 17:35:52 +00:00
function t.drawCapitals()
2023-07-28 05:42:16 +00:00
if t.visible then lg.points( caps ) end
2023-04-28 17:35:52 +00:00
end
function t.selectNearestCity(x, y)
t.selectedCity = cities:getClosestPoint(x, y)
if t.selectedCity then
local city = t.selectedCity
print( "SELECTED CITY", city.x, city.y, city.name, city.pop, city.capital)
else
print( "NO SELECTED CITY" )
end
end
2023-04-28 17:35:52 +00:00
function t.load( filename )
cities = {}
local n = 1
2023-04-28 17:35:52 +00:00
local idxPts = 1
local idxCaps = 1
for line in assert( lfs.lines( filename ), "Error: could not open cities.dat" ) do
2023-04-28 17:35:52 +00:00
local _, _, x, y, pop, capital = line:sub( 83 ):find( "(%g+)%s+(%g+)%s+(%g+)%s+(%g+)" )
x, y, pop, capital = tonumber( x ), tonumber( y ), tonumber( pop ), ( tonumber( capital ) > 0)
local city = {
name = line:sub( 1, 39 ):gsub("%s+$",""),
country = line:sub( 42, 82 ):gsub("%s+$",""),
x = x, y = y, pop = pop, capital = capital
}
cities[n] = city
n = n + 1
2023-04-28 17:35:52 +00:00
points[idxPts], points[idxPts + 1] = x, y
idxPts = idxPts + 2
if capital then
caps[idxCaps], caps[idxCaps + 1] = x, y
idxCaps = idxCaps + 2
end
end
--Multiple inheritance.
cities = locationQuery.New( cities )
setmetatable( getmetatable( cities ).__index, {__index = t } )
2023-04-28 17:35:52 +00:00
print( "LOADED", filename, n )
return cities
2023-04-28 17:35:52 +00:00
end
function t.save( cities, filename )
local str = {}
for n, city in ipairs( cities ) do
str[n] = ("%-40s%-40s%f %f %d %d"):format( city.name, city.country, city.x, city.y, city.pop, city.capital and 1 or 0 )
end
assert( lfs.write( filename, table.concat( str, "\n" ) ) )
print( "Saved", filename )
end
return t