Lonely Lion

Chris McAvoy likes kites

Pyglet Great, Math Hard

with 2 comments

I’ve blogged about my random obsession with bees in the past. The release of Pyglet encouraged me to pick it up again and try to make a bee-system associated with coordinates rather than with abstract “locations.”

Over the weekend, I started to write a trig library that could compute angles and distances, so I could move my bees around a grid. It turns out, I’m pretty bad at math. Brant Harris sat down and explained Vectors to me in about 15 minutes. I immediately ditched my trig library, and built a basic Vector bee demo in a half hour or so last night. The code for it is in my expansive public-works repository. In that same module is trig.py, which is the start of the trig library I ended up ditching. The Vector work was already written in PyEuclid, the very excellent Euclidian Geometry library written especially for Pygame development.

The code, suitable for cutting and pasting, is as follows:

[source:python]
#!/usr/bin/env python
# notes on how to use vectors to move the bees around in pyglet
from euclid import Vector2 as v
from pyglet import window
from pyglet import font
from random import randint

b = v(1,1) # bee at 1,1
h = v(150,150) # hive at 4,4

def in_range(b, h):
# return true if magnitude (distance) is less than 1
return (b – h).magnitude() < 1

# move the bee one tick towards the hive
def move_towards_hive(b,h):
return b + ( h – b ).normalized()

def move_random(b):
return b + (v(randint(0,100), randint(0,100)) – b).normalized() * 5

win = window.Window()
ft = font.load(‘Arial’, 18)

while not win.has_exit:
win.dispatch_events()
while not in_range(b,h):
b = move_random(b)
print “b: %s h: %s” % (b, h)
win.clear()
b_text = font.Text(ft, ‘b’, x=b.x, y=b.y).draw()
h_text = font.Text(ft, ‘h’, x=h.x, y=h.y).draw()
win.flip()
[/source]

Written by Chris

November 14th, 2007 at 3:00 pm

Posted in BeeSim,Blog,Python

  • http://pedicel.tumblr.com Thomas

    So, of course the first question that pops into *my* head when I hear about this PyEuclid, is, “does the existence of a python euclidean geometry module suggest the existence of a python non-euclidean geometry module?” The answer, I am happy to report, appears to be yes, at least one: http://pygeo.sourceforge.net/

    Awesome!

  • http://bulkanix.blogspot.com bulkanix

    The title is misleading, i had the impression before reading the post that Pyglet was bad at handling ‘math’ where as it’s you that sucks at math (which i do too!).

Switch to our mobile site