Dentosal / python-sc2

A StarCraft II bot api client library for Python 3
MIT License
586 stars 182 forks source link

Fixes position.Point2.closest method #217

Closed Lambdanaut closed 5 years ago

Lambdanaut commented 5 years ago

I found myself needing to get the closest element in a list of points set at Point2(math.inf, math.inf). This was failing with the following exception

Traceback (most recent call last):
  File "/Users/jthomas/.pyenv/versions/3.6.5/lib/python3.6/site-packages/sc2/main.py", line 127, in _play_game_ai
    await ai.on_step(iteration)
  File "/Users/jthomas/git/lambdanaut-sc2/lambdanaut/bot.py", line 3112, in on_step
    await self.micro_manager.run()
  File "/Users/jthomas/git/lambdanaut-sc2/lambdanaut/bot.py", line 3021, in run
    await self.do_combat()
  File "/Users/jthomas/git/lambdanaut-sc2/lambdanaut/bot.py", line 2989, in do_combat
    nearest_enemy_cluster = army_center.closest(self.bot.enemy_clusters)
  File "/Users/jthomas/.pyenv/versions/3.6.5/lib/python3.6/site-packages/sc2/position.py", line 63, in closest
    return closest_element
UnboundLocalError: local variable 'closest_element' referenced before assignment

This sets the closest element to be the first one before continuing onwards to the next elements, and also fixes my problem.

tweakimp commented 5 years ago

Why would you create a list of Point2(math.inf, math.inf) ?

Lambdanaut commented 5 years ago

I'm doing some stuff with k-means where a cluster with 0 data points has a centroid of Math.inf. Sometimes, especially early in the game, none of my clusters have any data points, so it's a list of Math.inf.

Lambdanaut commented 5 years ago

If you think this is superfluous, then I'm okay with it not being merged.

I think it makes the function "safer" though

tweakimp commented 5 years ago

Its not up to me to decide. I just thought its a very rare case. We could also change if distance < closest_distance_squared: to if distance <= closest_distance_squared:

I think that would be a "cleaner" fix.

tweakimp commented 5 years ago

I merged master into develop to start working on the dev branch. I fixed this issue while updating :) Develop branch should include a fix for your problem now.