OSDN Git Service

変愚の mysqrt() を参考に整数平方根処理を実装。 / Implement mysqrt() follow Hengband's example.
[deeangband/Deeangband-new.git] / Deeangband / Coordinates.cpp
index ea8496d..6ba82e6 100644 (file)
@@ -70,14 +70,50 @@ namespace Deeangband
                return (this->fx == plus.fx && this->fy == plus.fy);
        }
 
+       static int mysqrt(int n)
+       {
+               int tmp = n >> 1;
+               int plus = 10;
+               int solve = 1;
+
+               if(n < 1) return 0;
+               if(n < 4) return 1;
+
+               while(tmp)
+               {
+                       if ((n / tmp) < tmp)
+                       {
+                               tmp >>= 1;
+                       }
+                       else break;
+               }
+
+               solve = tmp;
+
+               while(plus)
+               {
+                       if ((n / tmp) < tmp)
+                       {
+                               plus--;
+                               tmp = solve;
+                       }
+                       else
+                       {
+                               solve = tmp;
+                               tmp += plus;
+                       }
+               }
+               return solve;
+       }
+
        int Coordinates::Distance(Coordinates a, Coordinates b)
        {
-               return (int)sqrt((double)((a.GetX() - b.GetX()) * (a.GetX() - b.GetX()) + (a.GetY() - b.GetY()) * (a.GetY() - b.GetY())) - 0.5f);
+               return mysqrt((a.GetX() - b.GetX()) * (a.GetX() - b.GetX()) + (a.GetY() - b.GetY()) * (a.GetY() - b.GetY()));
        }
 
        int Coordinates::Distance(int x1, int y1, int x2, int y2)
        {
-               return (int)sqrt((double)((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) - 0.5f);
+               return mysqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
        }
 
        int Coordinates::Distance(Coordinates a)