Minimum of a group
okay, so i am trying to make a tower defense game and I am pretty sure I can do most of the stuff I have planned, I just need a way to figure out the smallest number of a group so that I can make the towers decide which enemy is closest. I couldn't find anything in documentation as the min(a,b) function only applies to two numbers, and I need to be able to compare a lot.
Is there any way for me to do so?
https://microstudio.dev/i/KingLauri200/collections/
https://microstudio.dev/i/Lunaryss/listlibrary/
You can extend the List
/ Array
class.
Or create your own class that inherits from List / Array and add methods there.
Here are examples using JavaScript
.
I think you can do the same in MicroScript
(you add a method to the List class).
Here is sample code with a new class that has a list as a field and a method to find the closest point.
You call it by passing the class
/ object
with fields x
and y
.
After executing the method, the distance to the closest object on the list is returned, as well as this object.
Only place objects / classes on the list that have fields x
and y
.
ExtList = class
constructor = function()
this.list = []
end
findMin = function( point )
local m = 9999999999
local obj = this.list[0]
for e in this.list
local dist_x = e.x - point.x
local dist_y = e.y - point.y
local dist = ( dist_x * dist_x ) + ( dist_y * dist_y )
if dist < m then
m = dist
o = e
end
end
return (object
dist = m
obj = o
end)
end
end
init = function()
extList = new ExtList()
for i = 1 to 10
extList.list.push( object x = random.next( 100 ) y = random.next(100) end )
end
m = extList.findMin( object x = 0 y = 0 end )
print( "min dist = " + m.dist )
end
Or, for just a function:
distance = function(a, b)
return sqrt((a[0] - b[0]) ^ 2 + (a[1] - b[1]) ^ 2)
end
min_distance = function(target, coords)
local min_dist = distance(target, coords[0])
result = coords[0][2] or 0
for coord in coords.slice(1)
local dist = distance(target, coord)
if dist < min_dist then
min_dist = dist
result = coord[2] or coords.indexOf(coord)
end
end
return result
end
min_distance
takes a target coordinate (the position of the tower) and a list of coordinates (the positions of the enemies). If the closest coordinate has a third element, it returns it, otherwise it returns the index of the closest coordinate.
> min_distance([0, 0], [[20, 0], [10, 0], [10, 10]])
1
> min_distance([0, 0], [[20, 0, "enemy1"], [10, 0, "enemy2"], [10, 10, "enemy3"]])
"enemy2"