Avoid sqrt for euclideanDist function (#395)

## Description:

In most cases we do not need to solve for the hypotenuse length and can
do math directly on the square of the hypotenuse. For example, the
common use case for calculating euclidean distance is to check if two
points are within a certain distance of each other. In this case,
`Math.sqrt(x*x + y*y) < d` can be rewritten as `x*x + y*y < d*d`.

## Please complete the following:

- [x] I have added screenshots for all UI updates
- [x] I confirm I have thoroughly tested these changes and take full
responsibility for any bugs introduced
- [x] I understand that submitting code with bugs that could have been
caught through manual testing blocks releases and new features for all
contributors

## Please put your Discord username so you can be contacted if a bug or
regression is found:

fake.neo

---------

Co-authored-by: Scott Anderson <662325+scottanderson@users.noreply.github.com>
This commit is contained in:
Scott Anderson
2025-04-05 10:17:29 -07:00
committed by GitHub
co-authored by Scott Anderson
parent 25c18cdae2
commit 729920bdca
6 changed files with 23 additions and 31 deletions
+2 -1
View File
@@ -156,6 +156,7 @@ export class MirvExecution implements Execution {
randomLand(ref: TileRef, taken: TileRef[]): TileRef | null {
let tries = 0;
const mirvRange2 = this.mirvRange * this.mirvRange;
while (tries < 100) {
tries++;
const x = this.random.nextInt(
@@ -174,7 +175,7 @@ export class MirvExecution implements Execution {
if (!this.mg.isLand(tile)) {
continue;
}
if (this.mg.euclideanDist(tile, ref) > this.mirvRange) {
if (this.mg.euclideanDistSquared(tile, ref) > mirvRange2) {
continue;
}
if (this.mg.owner(tile) != this.targetPlayer) {
+6 -6
View File
@@ -52,12 +52,11 @@ export class NukeExecution implements Execution {
private tilesToDestroy(): Set<TileRef> {
const magnitude = this.mg.config().nukeMagnitudes(this.nuke.type());
const rand = new PseudoRandom(this.mg.ticks());
const inner2 = magnitude.inner * magnitude.inner;
const outer2 = magnitude.outer * magnitude.outer;
return this.mg.bfs(this.dst, (_, n: TileRef) => {
const d = this.mg.euclideanDist(this.dst, n);
if (d > magnitude.outer) {
return false;
}
return d <= magnitude.inner || rand.chance(2);
const d2 = this.mg.euclideanDistSquared(this.dst, n);
return d2 <= outer2 && (d2 <= inner2 || rand.chance(2));
});
}
@@ -232,6 +231,7 @@ export class NukeExecution implements Execution {
}
}
const outer2 = magnitude.outer * magnitude.outer;
for (const unit of this.mg.units()) {
if (
unit.type() != UnitType.AtomBomb &&
@@ -239,7 +239,7 @@ export class NukeExecution implements Execution {
unit.type() != UnitType.MIRVWarhead &&
unit.type() != UnitType.MIRV
) {
if (this.mg.euclideanDist(this.dst, unit.tile()) < magnitude.outer) {
if (this.mg.euclideanDistSquared(this.dst, unit.tile()) < outer2) {
unit.delete();
}
}