]> git.cworth.org Git - lmno.games/commitdiff
anagrams: Try a little to avoid placing a tile on top of others
authorCarl Worth <cworth@cworth.org>
Sun, 8 Mar 2026 13:23:38 +0000 (09:23 -0400)
committerCarl Worth <cworth@cworth.org>
Sun, 8 Mar 2026 13:23:38 +0000 (09:23 -0400)
This just tries 10 different random positions and picks the one that
is the furthest from existing tiles.

anagrams/anagrams.jsx

index 14b4d054f0cebbea3f0302cdc23970c66e651894..a5e520a681fa77d92296120bb3c171759d65eb0d 100644 (file)
@@ -509,12 +509,29 @@ class Game extends React.Component {
    *****************************************************/
 
   _random_position() {
-    /* Returns {x, y} as percentages within the center pool,
-     * keeping tiles away from edges. */
-    return {
-      x: 5 + Math.random() * 80,
-      y: 5 + Math.random() * 75
-    };
+    /* Pick the best of several random candidates by choosing the
+     * one with the most distance from existing tiles. */
+    const positions = this.state.tile_positions;
+    const existing = Object.values(positions);
+    let best = null, best_dist = -1;
+
+    for (let i = 0; i < 10; i++) {
+      const candidate = {
+        x: 5 + Math.random() * 80,
+        y: 5 + Math.random() * 75
+      };
+      let min_dist = Infinity;
+      for (const pos of existing) {
+        const dx = candidate.x - pos.x;
+        const dy = candidate.y - pos.y;
+        min_dist = Math.min(min_dist, dx * dx + dy * dy);
+      }
+      if (min_dist > best_dist) {
+        best = candidate;
+        best_dist = min_dist;
+      }
+    }
+    return best || { x: 5 + Math.random() * 80, y: 5 + Math.random() * 75 };
   }
 
   /*****************************************************