RE: [pygame] 2D vector class
Thanks for all the feedback, everyone. It's gonna take me a bit to pour over all the details. Very helpful! And, Brian, thanks for posting your vector class to the Cookbook! Much appreciated! -Scott
Re: [pygame] 2D vector class
Richard Jones wrote: Any chance of this getting into the cookbook? :) If you mean the actual code I used, it's currently embedded in a rather haphazard collection of vector algebra code that I grew for that particular game. I could look into whether it can be pulled out and made useable on its own. -- Greg
Re: [pygame] Game libraries list moved from PyWeek rules
Nice one Richard. On 8/11/06, Richard Jones <[EMAIL PROTECTED]> wrote: I've (finally) moved the libraries list from the PyWeek rules: http://wiki.python.org/moin/PythonGameLibraries Richard
Re: [pygame] 2D vector class
On Sunday 13 August 2006 11:49, Greg Ewing wrote: > I used something like this very effectively in a > recent project where I wanted to find the intersection > of a ray with a terrain mesh. First I worked out how > to use Numeric to test the ray against just one > triangle. Then it was almost (although not quite) > trivial to extend that to handle an array of triangles. > > Presto - I could then do a hit test against my whole > terrain of hundreds of triangles almost instantaneously! Any chance of this getting into the cookbook? :) Richard
Re: [pygame] 2D vector class
Ethan Glasser-Camp wrote: It certainly isn't clear how best to take advantage of this speedup without going crazy from pos_x and pos_y variables all over the place. Doing vector operations one at a time in Python is always going to be either slow or very slow, no matter how you go about it. IMO, the best way to make this sort of thing fast is to arrange things so that you can use Numeric to operate on multiple vectors at once. For instance, store all your object positions in one array and all the velocities in another, and then just add the two arrays together. You could wrap these arrays up in custom PointArray and VectorArray classes with suitable operators, and the overhead of method calls would be far less of a problem, since you only incur it once for the whole array rather than once per vector. I used something like this very effectively in a recent project where I wanted to find the intersection of a ray with a terrain mesh. First I worked out how to use Numeric to test the ray against just one triangle. Then it was almost (although not quite) trivial to extend that to handle an array of triangles. Presto - I could then do a hit test against my whole terrain of hundreds of triangles almost instantaneously! -- Greg
Re: [pygame] BUG: display.init() confuses key mods
I think maybe 512 is pygame.KMOD_ALT? it's what I use on python 2.3 for detecting alt-enter, and it works flawlessly: if event.key == pygame.K_RETURN and event.mod & pygame.KMOD_ALT: On 8/12/06, René Dudfield <[EMAIL PROTECTED]> wrote: weirdness... This is from my full screen code... mods = event.mod # right alt modifier doesn't work it seems. # So I use 512 as a constant... seems to work. if (mods & K_LALT) or (mods & K_RALT) or (mods & 512): Does that help? On 8/13/06, Phil Hassey <[EMAIL PROTECTED]> wrote: > Well, after adding my small fix to the toggle_fullscreen function, it won't > just go out of fullscreen if the user presses enter again, however it won't > go out of full screen if the user presses alt-enter. They have to do it > twice then it goes out. > > Not too big of a deal, but something still seems to be wrong... > > Phil > > > Phil Hassey <[EMAIL PROTECTED]> wrote: > get_pressed also reports the incorrect value. I think this is either a > pygame or SDL issue. > > However, I found that if I use pygame.key.set_mods(0) > to reset the keyboard mods, that appears to fix the issue for the most part. > Kind of a hack though... > > Phil > > Luke Paireepinart <[EMAIL PROTECTED]> wrote: > Phil Hassey wrote: > > Hi, > > > > I noticed that when I used the sample: > > > > > http://www.pygame.org/wiki/toggle_fullscreen?parent=CookBook > > > > To control my fullscreen toggling, after I went into full screen, I > > could often just press enter (without the ALT) to get back to windowed > > mode. After some playing around, it appears that either pygame or SDL > > misses the ALT key-up event while switching into fullscreen mode... I > > was able to reproduce this issue on both a linux and win32 system. > > > > Any suggestions? Am I doing something wrong in my toggle_fullscreen code? > if you're using a separate variable to hold the state of the ALT key, > you could just > reset it to false whenever someone goes fullscreen, > and then do a get_pressed or whatever to find out if alt actually still > is pressed > once you're fullscreened. > > > > Thanks! > > Phil > > > > > > > Do you Yahoo!? > > Everyone is raving about the all-new Yahoo! Mail Beta. > > > > > > > Get your email and more, right on the new Yahoo.com > > > > How low will we go? Check out Yahoo! Messenger�s low PC-to-Phone call rates. > >
Re: [pygame] BUG: display.init() confuses key mods
weirdness... This is from my full screen code... mods = event.mod # right alt modifier doesn't work it seems. # So I use 512 as a constant... seems to work. if (mods & K_LALT) or (mods & K_RALT) or (mods & 512): Does that help? On 8/13/06, Phil Hassey <[EMAIL PROTECTED]> wrote: Well, after adding my small fix to the toggle_fullscreen function, it won't just go out of fullscreen if the user presses enter again, however it won't go out of full screen if the user presses alt-enter. They have to do it twice then it goes out. Not too big of a deal, but something still seems to be wrong... Phil Phil Hassey <[EMAIL PROTECTED]> wrote: get_pressed also reports the incorrect value. I think this is either a pygame or SDL issue. However, I found that if I use pygame.key.set_mods(0) to reset the keyboard mods, that appears to fix the issue for the most part. Kind of a hack though... Phil Luke Paireepinart <[EMAIL PROTECTED]> wrote: Phil Hassey wrote: > Hi, > > I noticed that when I used the sample: > > http://www.pygame.org/wiki/toggle_fullscreen?parent=CookBook > > To control my fullscreen toggling, after I went into full screen, I > could often just press enter (without the ALT) to get back to windowed > mode. After some playing around, it appears that either pygame or SDL > misses the ALT key-up event while switching into fullscreen mode... I > was able to reproduce this issue on both a linux and win32 system. > > Any suggestions? Am I doing something wrong in my toggle_fullscreen code? if you're using a separate variable to hold the state of the ALT key, you could just reset it to false whenever someone goes fullscreen, and then do a get_pressed or whatever to find out if alt actually still is pressed once you're fullscreened. > > Thanks! > Phil > > > Do you Yahoo!? > Everyone is raving about the all-new Yahoo! Mail Beta. > Get your email and more, right on the new Yahoo.com How low will we go? Check out Yahoo! Messenger�s low PC-to-Phone call rates.
Re: [pygame] IDLE crashes on error?
James Hofmann wrote: This option is the -n flag. It's saved me a lot of trouble with IDLE. >From the help: Running without a subprocess: If IDLE is started with the -n command line switch it will run in a single process and will not create the subprocess which runs the RPC Python execution server. >This can be useful if Python cannot create the >subprocess or the RPC socket interface on your platform. However, in this mode user code is not isolated from IDLE itself. Also, the environment is not restarted when Run/Run Module (F5) is selected. If your code has been modified, you must reload() the affected modules and re-import any specific items (e.g. from foo import baz) if the changes are to take effect. For these reasons, it is preferable to run IDLE with the default subprocess if at all possible. Man, did that cause me trouble. I made a 'config' module that I put variables I wanted to be global for my program, so I could just say 'config.varname' to reference them, but whenever I changed the 'config.py' module I had really weird behaviour, like I hadn't even made changes. Now I know it's because 'config.py' had already been imported and I had to restart IDLE every time I changed it. What a hassle. This sounds like it does the opposite of what we want...merges the processes instead of completely seperating them. It does :) I tried running IDLE with it and then forcing my pygame code to crash. IDLE will normally zombify(unresponsive) if I do that and make me kill it manually; but with -n it completely blew up and gave me a MSVC crash box. So my conjectures are: we are not running the same program and -n is doing something completely different for you guys, the OS running this is a factor, or I'm doing a better job at making crashy code. Nice conjectures, but I think the confusion is from David's response. I think he meant to say '[turning on this subprocess] option is [removing] the -n flag' The -n command is on by default on windows boxen (at least mine was.) As per someone else's instructions (I can't remember who, sorry) Open Windows Explorer Tools Menu > Folder Options File Types tab select 'py' and hit advanced select 'Edit with Idle' and hit Edit under 'Application used to perform action:' get rid of the -n argument that it passes. You should probably do this with .pyw files also. I can't imagine why giving it more than one -n would make a difference, or how you added -n to the argument list, but anyway, this should do what you want. I just tried it and it is very helpful. I used to create .bat files for all my programs that would run my programs and then pause, so if there were error messages I could see them, since pygame apps would give me IDLE problems, but I just wrote a pygame app and it worked fine once I removed the -n flag. Hope that helps :D -Luke __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com
Re: [pygame] IDLE crashes on error?
> This option is the -n flag. It's saved me a lot > of trouble with IDLE. >From the help: >Running without a subprocess: > >If IDLE is started with the -n command line switch it >will run in a single process and will not create the >subprocess which runs the RPC Python execution server. >This can be useful if Python cannot create the >subprocess or the RPC socket interface on your >platform. However, in this mode user code is not >isolated from IDLE itself. Also, the environment is >not restarted when Run/Run Module (F5) is selected. If >your code has been modified, you must reload() the >affected modules and re-import any specific items >(e.g. from foo import baz) if the changes are to take >effect. For these reasons, it is preferable to run >IDLE with the default subprocess if at all possible. This sounds like it does the opposite of what we want...merges the processes instead of completely seperating them. I tried running IDLE with it and then forcing my pygame code to crash. IDLE will normally zombify(unresponsive) if I do that and make me kill it manually; but with -n it completely blew up and gave me a MSVC crash box. So my conjectures are: we are not running the same program and -n is doing something completely different for you guys, the OS running this is a factor, or I'm doing a better job at making crashy code. __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com
Re: [pygame] IDLE crashes on error?
On 8/11/06, Bob Ippolito <[EMAIL PROTECTED]> wrote: On Aug 11, 2006, at 3:38 PM, James Hofmann wrote:> --- [EMAIL PROTECTED] wrote:>>> Hi folks, Python/Pygame newbie here. Really liking it so far, >> but I've resorted to>> using Notepad. It seems like any time I execute code>> with errors in it -->> simple syntax errors, not endless while loops or>> anything -- IDLE freezes. >> Also, and I don't know if this is related, but>> sys.exit() doesn't actually>> close my windows when I'm running things from IDLE.>> They just freeze. IDLE version 1.1.3, Python version 2.4.3, any>> help/advice appreciated.>> IDLE runs your code in the same operating system> process, which means that anything that crashes your> code may crash IDLE, too, and also changes the > behavior of your code as with sys.exit(). You can use> it as the editor or for tests in the console, but run> pygame code elsewhere.IDLE definitely has an option to use a subprocess for interpreters. Turn it on, then this problem goes away.-bobThis option is the -n flag. It's saved me a lot of trouble with IDLE.
Re: [pygame] 2D vector class
Brian Fisher wrote: > so I wrote test functions to take a 2d position, subtract another > position from it then multiply the result by a scalar (basically pan > and zoom a position). One version uses the 2d vector with operator > overloading, so it will allocate 2 vec2d's, each with a list member. > Another version does explicit math operations on variables, so no > allocations happen. I also tried converting the vec2d class to be > inherited from tuple, thinking that maybe you could save the list > member allocations by being a tuple to start with... When I said "explicitly storing two variables", I meant doing more like the following: class Vector2D(object): def __init__(self, dx, dy): object.__init__(self) self.dx = dx self.dy = dy def __sub__(self, v2): return Vector(self.dx - v2.dx, self.dy - v2.dy) def __add__(self, v2): return Vector(self.dx + v2.dx, self.dy + v2.dy) def __iadd__(self, v2): self.dx = self.dx + v2.dx self.dy = self.dy + v2.dy return self def __isub__(self, v2): self.dx = self.dx - v2.dx self.dy = self.dy - v2.dy return self This is the Vector class I use. I did tests with this approach and, as you might expect, it's also much slower than just using two variables outside of a class. I'm attaching the modified benchmarking script. > like a 48:1 performance diff. Also the tuple inherited version was > slower. This is good information but really astonishing. The next step would probably be benchmarking just to confirm that the large number of calls to __init__ and __new__ are what are causing the slowdown. It could also be that method calls are much slower than no function calls. It certainly isn't clear how best to take advantage of this speedup without going crazy from pos_x and pos_y variables all over the place. Maybe unpacking the vectors in certain parts of the code would be sufficient to speed things up, or maybe converting certain operations to in-place vector modifications would be good enough. Ethan """ 2D Vector Math Class (with operator overload goodness) (C) Copyright 2005 James Paige and Hamster Republic Productions """ import operator import math class vec2d(object): def __init__(self, x_or_pair, y = None): if y == None: try: self.vec = [x_or_pair[0],x_or_pair[1]] except TypeError: raise TypeError("vec2d constructor requires a tuple or two arguments") else: self.vec = [x_or_pair,y] def get_x(self): return self.vec[0] def set_x(self, value): self.vec[0] = value x = property(get_x, set_x) def get_y(self): return self.vec[1] def set_y(self, value): self.vec[1] = value y = property(get_y, set_y) def set(self, x, y): self.vec[0] = x self.vec[1] = y # String representaion (for debugging) def __repr__(self): return 'vec2d(%s, %s)' % (self.x, self.y) # Array-style access def __len__(self): return 2 def __getitem__(self, key): return self.vec[key] def __setitem__(self, key, value): self.vec[key] = value # Comparison def __eq__(self, other): return self.vec[0] == other[0] and self.vec[1] == other[1] def __ne__(self, other): return self.vec[0] != other[0] or self.vec[1] != other[1] def __nonzero__(self): return self.vec[0] or self.vec[1] # Generic operator handlers def _o2(self, other, f): "Any two-operator operation where the left operand is a vec2d" try: return vec2d(f(self.vec[0], other[0]), f(self.vec[1], other[1])) except TypeError: return vec2d(f(self.vec[0], other), f(self.vec[1], other)) def _r_o2(self, other, f): "Any two-operator operation where the right operand is a vec2d" try: return vec2d(f(other[0], self.vec[0]), f(other[1], self.vec[1])) except TypeError: return vec2d(f(other, self.vec[0]), f(other, self.vec[1])) def _o1(self, f): "Any unary operation on a vec2d" return vec2d(f(self.vec[0]), f(self.vec[1])) # Addition def __add__(self, other): return self._o2(other, operator.add) __radd__ = __add__ # Subtraction def __sub__(self, other): return self._o2(other, operator.sub) def __rsub__(self, other): return self._r_o2(other, operator.sub) # Multiplication def __mul__(self, other): return self._o2(other, operator.mul) __rmul__ = __mul__ # Division def __div__(self, other): return self._o2(other, operator.div) d
Re: [pygame] BUG: display.init() confuses key mods
Well, after adding my small fix to the toggle_fullscreen function, it won't just go out of fullscreen if the user presses enter again, however it won't go out of full screen if the user presses alt-enter. They have to do it twice then it goes out. Not too big of a deal, but something still seems to be wrong... PhilPhil Hassey <[EMAIL PROTECTED]> wrote: get_pressed also reports the incorrect value. I think this is either a pygame or SDL issue. However, I found that if I use pygame.key.set_mods(0)to reset the keyboard mods, that appears to fix the issue for the most part. Kind of a hack though... Phil Luke Paireepinart <[EMAIL PROTECTED]> wrote: Phil Hassey wrote:> Hi,>> I noticed that when I used the sample:>> http://www.pygame.org/wiki/toggle_fullscreen?parent=CookBook>> To control my fullscreen toggling, after I went into full screen, I > could often just press enter (without the ALT) to get back to windowed > mode. After some playing around, it appears that either pygame or SDL > misses the ALT key-up event while switching into fullscreen mode... I > was able to reproduce this issue on both a linux and win32 system.>> Any suggestions? Am I doing something wrong in my toggle_fullscreen code?if you're using a separate variable to hold the state of the ALT key, you could justreset it to false whenever someone goes fullscreen,and then do a get_pressed or whatever to find out if alt actually still is pressedonce you're fullscreened.>> Thanks!> Phil>> > Do you Yahoo!?> Everyone is raving about the all-new Yahoo! Mail Beta. > Get your email and more, right on the new Yahoo.com How low will we go? Check out Yahoo! Messengers low PC-to-Phone call rates.
Re: [pygame] 2D vector class
On Fri, Aug 11, 2006 at 01:38:06PM -0500, Nelson, Scott wrote: > I've got 2 simple games roughed out (about 600 lines each) with about > 2000 lines worth of shared modules I've written. I have a somewhat full > featured 2D vector class (supports adding, subtracting, scaling, > rotation, normalizing, angle between, etc. that I use in both heavily to > represent points, velocities, etc. After using it for awhile, I've > wondered how others have approached creating a 2D vector class. Here's > my "philosophical" questions, as the class I have works well, but I want > to know how to make it better. My main goals are to keep it simple, let > it interface cleanly with Pygame's use of tuples of 2 ints for 2D > points, not be specifically tied to Pygame, and have it not be a > performance hog. > > So, here's the issues that I'd love to hear feedback on: > > #1 - Do you store the vector components internally as self.x and self.y > or as a tuple? Or subclass the vector class from a tuple? If you use > self.x and self.y, what is an efficient way to pass this as a tuple to > pygame functions? I chose to subclass tuple in pyspacewar, but I forgot why. > #2 - Do you store the values as ints (making it easier to pass to > Pygame) or floats (more accurate vector math, but need to cast to int > before passing to pygame functions that require a tuple of ints?). Or > do you not even care and just let duck-typing do it stuff? I needed floats, because I wanted the world to be scaled arbitrarily for display, and besides that I needed the accuracy for gravity calculations. You can find my Vector class here: http://mg.pov.lt/pyspacewar/trac/browser/trunk/src/pyspacewar/world.py It has unit tests, and is somewhat optimized (only those bits that showed up when profiling). Marius Gedminas -- C is for Cookies. Perl is even better for Cookies. signature.asc Description: Digital signature
Re: [pygame] 2D vector class
On 8/12/06, Alex Holkner <[EMAIL PROTECTED]> wrote: You won't be able to meaningfully overload operators if you subclass tuple (vector + tuple will not equal tuple + vector). In the code I emailed, there is a unit test for exactly that problem with a tuple inherited vector class, it works just fine. The issue of right side or left side operators has nothing to do with whether you overload tuple or not. You could overload object, and still need to support both vector + tuple and tuple + vector. In addition, Python can handle that just fine. There are seperate operators to overload for when the object is on each side (they just add r in front of the name for the right side one, so __add__ and __radd__) Finally, python seems to know to let your user classes operators win over all built in operators on either side of the operator (I don't know how it would decide what to do when two user classes overload, maybe that's where left side wins... anybody?)
Re: [pygame] 2D vector class
After reading Ethan's email, I decided to play more with the vec2d class I posted, specifically to try to understand how bad the allocations due to operator overloading really are - in that I want to put it in a real context (like say how many particle positions you could translate and still get 60 fps)... cause it doesn't matter if you make the thing that takes 1% of your time go 1000% faster... so I wrote test functions to take a 2d position, subtract another position from it then multiply the result by a scalar (basically pan and zoom a position). One version uses the 2d vector with operator overloading, so it will allocate 2 vec2d's, each with a list member. Another version does explicit math operations on variables, so no allocations happen. I also tried converting the vec2d class to be inherited from tuple, thinking that maybe you could save the list member allocations by being a tuple to start with... Then for performance, I ran the script in Python 2.3 on my 800Mhz p3 laptop plugged into the wall (what I consider my min spec) then checked how many times it could do the translations a second. Basically, using the operator overloading cut the performance by about a factor of 18 . Also, when running psycho, the func doing math on variables was able to run about 3x faster, but the operator overloading routines weren't able to go significantly faster (makes sense cause psycho doesn't help with allocation issues) making it more like a 48:1 performance diff. Also the tuple inherited version was slower. So then using the loops/sec to try and figure out some context for the perf difference, I computed how many times you could run the loop if you had a 5% budget of cpu time for a game that ran at 60fps on my min-spec machine - and that figure was 15/280 without psycho, or 16/760 with it. only moving around 15 objects a frame on my laptop before dropping frames does strike me as very bad... especially when I'd probably be pretty happy with 280 objects... but I'll still probably keep using vec2d as a rule (although I do know where to look first when performance drags now...) I'm attaching the adapted code, if anyone is curious (it will run the perf tests and print out stats) """ 2D Vector Math Class (with operator overload goodness) (C) Copyright 2005 James Paige and Hamster Republic Productions """ import operator import math class vec2d(object): def __init__(self, x_or_pair, y = None): if y == None: try: self.vec = [x_or_pair[0],x_or_pair[1]] except TypeError: raise TypeError("vec2d constructor requires a tuple or two arguments") else: self.vec = [x_or_pair,y] def get_x(self): return self.vec[0] def set_x(self, value): self.vec[0] = value x = property(get_x, set_x) def get_y(self): return self.vec[1] def set_y(self, value): self.vec[1] = value y = property(get_y, set_y) def set(self, x, y): self.vec[0] = x self.vec[1] = y # String representaion (for debugging) def __repr__(self): return 'vec2d(%s, %s)' % (self.x, self.y) # Array-style access def __len__(self): return 2 def __getitem__(self, key): return self.vec[key] def __setitem__(self, key, value): self.vec[key] = value # Comparison def __eq__(self, other): return self.vec[0] == other[0] and self.vec[1] == other[1] def __ne__(self, other): return self.vec[0] != other[0] or self.vec[1] != other[1] def __nonzero__(self): return self.vec[0] or self.vec[1] # Generic operator handlers def _o2(self, other, f): "Any two-operator operation where the left operand is a vec2d" try: return vec2d(f(self.vec[0], other[0]), f(self.vec[1], other[1])) except TypeError: return vec2d(f(self.vec[0], other), f(self.vec[1], other)) def _r_o2(self, other, f): "Any two-operator operation where the right operand is a vec2d" try: return vec2d(f(other[0], self.vec[0]), f(other[1], self.vec[1])) except TypeError: return vec2d(f(other, self.vec[0]), f(other, self.vec[1])) def _o1(self, f): "Any unary operation on a vec2d" return vec2d(f(self.vec[0]), f(self.vec[1])) # Addition def __add__(self, other): return self._o2(other, operator.add) __radd__ = __add__ # Subtraction def __sub__(self, other): return self._o2(other, operator.sub) def __rsub__(self, other): return self._r_o2(other, operator.sub) # Multiplication def __mul__(self, other): return self._o2(oth
Re: [pygame] 2D vector class
...As far as subclassing from a tuple, I don't think I really looked into that, might be a great way to go... the idea of the vector object being immutable is probably actually a good idea - just because you may pass a vector in as a function argument and not want it to change... that way the vector is more like passing in two args, in that you can't change the callee's data You won't be able to meaningfully overload operators if you subclass tuple (vector + tuple will not equal tuple + vector). Alex.