Commits

Benoit Boissinot  committed f5d59af

better random

  • Participants
  • Parent commits 0bd31e4

Comments (0)

Files changed (2)

 # manually, move them above the marker line.  The index.yaml file is
 # automatically uploaded to the admin console when you next deploy
 # your application using appcfg.py.
-
-- kind: Tile
-  properties:
-  - name: __key__
-    direction: desc
     x = db.IntegerProperty(required=True)
     y = db.IntegerProperty(required=True)
     content = db.ByteStringProperty(required=True)
+    rand = db.FloatProperty()
+
+    def put(self, *args, **kwargs):
+        self.rand = random.random()
+        super(Tile, self).put(*args, **kwargs)
 
 def split32(s):
     for i in range(0, tilelength, 32):
     return q.filter('x =', x).filter('y =', y).get()
 
 def get_random_tile():
-    q = db.Query(Tile, keys_only=True)
-    q.order('-__key__')
-    rows = q.fetch(300)
-    if not rows:
+    r = random.random()
+    t1 = Tile.all().filter('rand >= ', r).order('rand').get()
+    t2 = Tile.all().filter('rand < ', r).order('-rand').get()
+
+    tt = [t for t in (t1, t2) if t is not None]
+    if not tt:
         return 0, 0, None
-    t = Tile.get_by_id(random.choice(rows).id())
+    tt.sort(key=lambda x: abs(r-x.rand))
+    t = tt[0]
     return t.x, t.y, zlib.decompress(t.content)
 
 def get_tile_content(x, y):
             x, y = 0, 0
         elif len(args) == 1 and args[0] == 'random':
             x, y, content = get_random_tile()
+        elif len(args) == 1 and args[0] == 'rerandom':
+            for t in Tile.all():
+                t.put()
+            x, y, content = get_random_tile()
         elif len(args) == 2:
             x = long(args[0]) % maxrange
             y = long(args[1]) % maxrange
 application = webapp.WSGIApplication(
                                      [(r'/tiles/(\d+)x(\d+)', Tiles),
                                       (r'/tiles/(random/?)', Tiles),
+                                      (r'/tiles/(rerandom/?)', Tiles),
                                       (r'/tiles/?', Tiles)],
                                      debug=True)