Re: [pygame] Newbie performance question

2018-07-17 Thread Christopher Night
It runs fine for me. What sort of framerate are you getting
(self.clock.get_fps())? If it really is significantly less than 60, my only
suggestion would be to try running it in windowed mode instead of
fullscreen and see if that makes any difference.

On Tue, Jul 17, 2018 at 2:53 PM Andreas Zielke 
wrote:

> Hi all,
>
> I've dabbled with pygame and wrote a Pong-like game (code see below).
>
> I've tried to follow the advice in the tips/tutorial section and also
> tried out the dirty-rect strategy described in
>
> https://www.pygame.org/docs/ref/sprite.html#comment_pygame_sprite_RenderUpdates
>
> This did not seem to make any difference, so I reverted back to the
> original code.
>
> The performance is still much less than I expecte - with a lot of
> stuttering on my (not so old) Windows PC, so I guess I must be making some
> silly mistake.
>
> It would be very kind, if someone could give me a heads-up.
>
> Cheers
> Andreas
>
> P.S. I'd be happy to supply additional information, if that would help.
>
> ---8< SNIP 8<---
>
> import pygame
> import random
> import math
>
>
> class MovingRectSprite(pygame.sprite.Sprite):
> def __init__(self, width, height, screen_width, screen_height, color,
> center_x=0, center_y=0):
> super().__init__()
> self.image = pygame.Surface((width, height)).convert()
> self.image.fill(color)
> self.rect = self.image.get_rect()
> self.rect.center = (center_x, center_y)
> self.screen_width = screen_width
> self.screen_height = screen_height
> self.x_speed = 0
> self.y_speed = 0
>
>
> def update(self):
> self.rect.x += self.x_speed
> self.rect.y += self.y_speed
>
>
>
> class Paddle(MovingRectSprite):
> SPEED = 10
>
> def __init__(self, width, height, screen_width, screen_height, color,
> center_x, center_y):
> super().__init__(width, height, screen_width, screen_height,
> color, center_x, center_y)
> self.acceleration = 0
> self.go_up = False
> self.go_down = False
>
>
> def update(self):
> super().update()
>
> if self.rect.top < 0:
> self.rect.top = 0
> self.y_speed = 0
> elif self.rect.bottom >= self.screen_height:
> self.rect.bottom = self.screen_height - 1
> self.y_speed = 0
>
>
> def key_down(self, is_up_key):
> if is_up_key:
> self.go_up = True
> self.y_speed = -self.SPEED
> else:
> self.go_down = True
> self.y_speed = self.SPEED
>
>
> def key_up(self, is_up_key):
> if is_up_key:
> self.go_up = False
> if self.go_down:
> self.y_speed = self.SPEED
> else:
> self.y_speed = 0
> else:
> self.go_down = False
> if self.go_up:
> self.y_speed = -self.SPEED
> else:
> self.y_speed = 0
>
>
>
> class Pong(object):
> def __init__(self):
> pygame.init()
> self.fps = 60
> self.background = (0, 0, 0)
> self.clock = pygame.time.Clock()
> self.running = False
> self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN |
> pygame.DOUBLEBUF)
>
> self.sprites = pygame.sprite.Group()
>
> paddle_width = self.screen.get_width() / 50
> paddle_height = self.screen.get_height() / 10
> self.paddles = pygame.sprite.Group()
>
> self.paddle_left = Paddle(paddle_width, paddle_height,
> self.screen.get_width(), self.screen.get_height(), (192, 0, 0),
> paddle_width / 2, self.screen.get_height() / 2)
> self.sprites.add(self.paddle_left)
> self.paddles.add(self.paddle_left)
>
> self.paddle_right = Paddle(paddle_width, paddle_height,
> self.screen.get_width(), self.screen.get_height(), (0, 0, 192),
> self.screen.get_width() - paddle_width / 2, self.screen.get_height() / 2)
> self.sprites.add(self.paddle_right)
> self.paddles.add(self.paddle_right)
>
> self.ball = MovingRectSprite(self.screen.get_width() / 100,
> self.screen.get_width() / 100, self.screen.get_width(),
> self.screen.get_height(), (255, 255, 0), self.screen.get_width() / 2,
> self.screen.get_height() / 2)
> self.sprites.add(self.ball)
>
> self.score_left = 0
> self.score_right = 0
>
> self.init_ball()
>
>
> def init_ball(self):
> self.ball.rect.center = (self.screen.get_width() / 2,
> self.screen.get_height() / 2)
> self.ball.x_speed = random.choice([-1, 1]) * 5
> self.ball.y_speed = random.randint(-5, 5)
>
>
> def on_key_up(self, event):
> if event.key in [pygame.K_s, pygame.K_x]:
> self.paddle_left.key_up(event.key == pygame.K_s)
> elif event.key in[pygame.K_UP, pygame.K_DOWN]:
> self.paddle_right.key_up(event.key == pygame.K_UP)
>
>
>

Re: [pygame] Re: Some way to pickle or otherwise save a pygame.mixer.Sound object?

2018-06-09 Thread Christopher Night
Just to be clear, you need to play two different multi-minute sounds at
once?

Because your example has one 13-minute track and one 3-second track. If
those are the sounds you need to play at the same time, why don't you just
preload the 3-second one into a pygame.mixer.Sound object and play it
whenever you need it, and play the 13-minute one with pygame.mixer.music?

On Fri, Jun 8, 2018 at 7:48 PM Alec Bennett  wrote:

> I see that pygame.mixer.Sound supports OGG, I guess I should try that.
>> I've never used OGG before, and I wonder if it supports OGG if MP3 would be
>> an easy addition?
>>
>
> Well so much for using OGG (and probably MP3) to speed up preloading. With
> my 13 minute mono soundfiles, it takes 7.3 seconds to preload the wav file
> (44.1hz, 16 bit, mono) and 43.6 seconds to preload the OGG file... I have a
> feeling it's uncompressing it during preload.
>
>>
> My project needs polyphony, but really only the ability to play two sounds
> at once. I'm currently using this method because it supports that:
>
>>
> channel = 1 # or 2
>
>> sound_obj = pygame.mixer.Sound("whatever.wav") # long preload at this step
>
>> channel = pygame.mixer.Channel(channel)
>
>> channel.play(sound_obj)
>
>>
> This method of playing MP3 works beautifully without preloading, but can
> only play one sound at a time:
>
>>
> pygame.mixer.init()
>
>> pygame.mixer.music.load("whatever.mp3")
>
>> pygame.mixer.music.play()
>
>> pygame.event.wait()
>
>>
> I don't imagine anyone knows of a way to play two sound files
> simultaneously using  pygame.mixer.music? Or some other solution in Python
> under Linux that would do it reliably? I suppose I could slave two
> instances of mplayer, but I'd of course prefer to not be forking out
> processes.
>
> If anyone's curious about the files I'm trying to load, I posted some test
> files here:
>
> sinkingsensation.com/dropbox/icecream.zip
>
>
>
>
> On Thu, Jun 7, 2018 at 2:30 PM, Alec Bennett  wrote:
>
>>
>>
>> On Thu, Jun 7, 2018 at 7:59 AM, Christopher Night > > wrote:
>>
>>> I recommend saving the sound as a raw buffer. First in a separate script:
>>>
>>> sound = pygame.mixer.Sound("music1.wav")
>>> open("music1.buf", "wb").write(sound.get_raw())
>>>
>>> Then in your game:
>>> sound = pygame.mixer.Sound(buffer=open("music1.buf", "rb").read())
>>>
>>> I found about 4x speedup of reading a large file on my desktop using
>>> this method. That may or may not be enough for you, especially if you
>>> combine with other tips in this thread.
>>>
>>
>>
>> Very interesting. Will try this when I'm working on this tonight.
>>
>>
>>
>>
>>
>


Re: [pygame] Re: Some way to pickle or otherwise save a pygame.mixer.Sound object?

2018-06-07 Thread Christopher Night
I recommend saving the sound as a raw buffer. First in a separate script:

sound = pygame.mixer.Sound("music1.wav")
open("music1.buf", "wb").write(sound.get_raw())

Then in your game:
sound = pygame.mixer.Sound(buffer=open("music1.buf", "rb").read())

I found about 4x speedup of reading a large file on my desktop using this
method. That may or may not be enough for you, especially if you combine
with other tips in this thread.

On Thu, Jun 7, 2018 at 10:08 AM Daniel Foerster  wrote:

> It looks like you may have missed the alternative solution in my email.
>
> On Thu, Jun 7, 2018, 01:04 Alec Bennett  wrote:
>
>> > I think the answer that sticks out to me is that if these are musical
>> horn sounds, you might consider using pygame.mixer.music, which will stream
>> the sounds as needed.
>>
>> A very good idea, and the route I originally took, but as far as I can
>> tell pygame.mixer.music doesn't support polyphony, and I occasionally need
>> to play multiple sounds at once.
>>
>>
>>
>>
>>
>> On Wed, Jun 6, 2018 at 10:59 PM, Daniel Foerster 
>> wrote:
>>
>>> I think the answer that sticks out to me is that if these are musical
>>> horn sounds, you might consider using pygame.mixer.music, which will stream
>>> the sounds as needed. However, this won't work if you have other music
>>> playing or if you want multiple horns to be able to play at the same time.
>>>
>>> A second solution is to load the sounds in the background of the game,
>>> especially if you're going to launch on a menu where the sounds won't be
>>> needed. You can pre-populate a dictionary with dummy sounds and use a
>>> thread to go through and load each sound into the dictionary while the user
>>> interacts with the menu.
>>>
>>> SOUND_PATH_MAPPING = {'horn_funny': 'horn_funny.ogg', 'horn_sad': 
>>> 'extra_sounds/horn_sad.wav'}
>>>
>>> SOUNDS = {name: None for name in SOUND_PATH_MAPPING}
>>>
>>> def load_sounds():
>>>
>>> for name, path in SOUND_PATH_MAPPING:
>>>
>>> SOUNDS[name] = pygame.mixer.Sound(path)
>>>
>>>
>>> def load_sounds_background():
>>>
>>> thread.start_new_thread(load_sounds, ())
>>>
>>>
>>> If there's a legitimate chance that the player might try to use the horn
>>> sounds before they've finished loading, just have the horn logic check for
>>> Nones before trying to play or have a dummy sound object with a play method
>>> that does nothing.
>>>
>>> A full example of how you might do this with a class:
>>> https://gist.github.com/pydsigner/231c0812f9f91050dd83c744d6d5dc4b
>>>
>>> On Thu, Jun 7, 2018 at 12:31 AM, Alec Bennett 
>>> wrote:
>>>
 Sorry, I left out the line where I try to save the file:

 > pickle.dump( sound_obj, open( "sound.pickled", "wb" ) )



 On Wed, Jun 6, 2018 at 10:29 PM, Alec Bennett 
 wrote:

> I'm building a musical horn for my car with PyGame, and it works
> perfectly, but since it needs to load each of the 20 sounds on startup it
> takes about 30 seconds to load. I'm running it on a Raspberry Pi, which
> doesn't help of course.
>
> I thought I'd simply save the Sound objects as pickle objects, but
> that produces an error:
>
> > sound_obj = pygame.mixer.Sound("whatever.wav")
>
> > can't pickle Sound objects
>
> I also tried the dill module (https://github.com/uqfoundation/dill)
> but with similar results:
>
> > sound_obj = pygame.mixer.Sound("whatever.wav")
>
> > Can't pickle : it's not found as __builtin__.Sound
>
> I don't imagine can think of some clever way to save the preloaded
> Sounds, or otherwise speed up the load times?
>
>
>
>
>

>>>
>>


Re: [pygame] pygame awesome libraries?

2018-04-10 Thread Christopher Night
For what it's worth, I did finally get around to removing the numpy
dependency from ptext after your feedback. As far as I know, the current
version doesn't require numpy, but let me know if you find that's not the
case. (Of course, if you prefer your version, that's perfectly fine too.)

On Tue, Apr 10, 2018 at 11:42 AM DR0ID  wrote:

> Hi
>
> Gummbum and I didn't like the numpy dependency of ptext, therefore we
> wrote a pygame only version: pygametext.py
>
> It does the same as ptext but using only pygame as dependency. If you want
> to be sure, there is also a comparer script that renders the output of both
> so it can be  compared.
>
>
> https://bitbucket.org/dr0id/pyknic/src/f8bee5c15ec7c7399f15fc3b2e1424793c63c3b2/pyknic-lib/experimental/textrendering/?at=default
>
>
>
> On 07.04.2018 10:33, Daniel Pope wrote:
>
> ptext is very good:
>
> https://github.com/cosmologicon/pygame-text
>
> On Thu, 5 Apr 2018, 11:11 René Dudfield,  wrote:
>
>> What are some awesome libraries for pygame?
>>
>>- available via pip
>>- documented (with examples, and API docs)
>>- generally awesome for some reason (even if not perfect, maybe it
>>has potential)
>>
>> I'll start with a few...
>>
>>- pyscroll . Scrolling maps. Fast
>>scrolling images easy.
>>- pyTMX . Reads Tiled Map Editors
>>TMX maps. Can use a Map editor easily.
>>- pyinstaller . Make installers for
>>different platforms. Very easy to use to make installers.
>>- pymunk . 2d physics library. Lots
>>of examples, very well maintained.
>>
>>
>>
>> What's awesome or almost awesome?
>>
>>
>>
>> ps. I also asked over on the reddit.
>> https://www.reddit.com/r/pygame/comments/89ygm7/pygame_awesome_libraries/
>>
>
>


Re: [pygame] Color shift when blitting

2017-11-05 Thread Christopher Night
In the past I've found this to be an issue with PNGs on Mac. The PNG
specification apparently allows for color correction on image load, based
on your display settings, which means it's going to be very inconsistent
between platforms (although it should look more consistent to the eye). If
you require pixel values to be exact, I recommend trying BMP instead and
seeing if you still see the issue.

On Sun, Nov 5, 2017 at 2:45 PM dejohnso  wrote:

> Hi,
>
> I am loading a background map and blitting it to the screen. Once I have
> done this, I am getting color values under the mouse cursor.
>
> However, I am seeing small color shifts between the image and the blitted
> image. For example,
>
> from the screen with the background image: (103, 255, 103, 255)
> directly from the image: (102, 255, 102, 255)
>
> This is also inconsistent. Sometimes, the colors are the same - even for
> the color shown above - so sometimes it gets shifted and sometimes not.
>
> Does anyone know why this is happening? The inconsistency is particularly
> strange to me, as it implies the same start color is inconsistently blitted
> to the screen.
>
> I am also seeing an overall color shift. The colors I am displaying from
> the screen or image are off by a few percent compared to the colors I see
> using a color picker in an image editing program.
>
> The relevant code is
>
> map = pygame.image.load("AvoiderMap.png")
> ...
> while is_alive:
> # Check events by looping over the list of events
> for event in pygame.event.get():
> ….
>
> screen.blit(map, map_rect)
>
> pos = pygame.mouse.get_pos()
> cursor_color = screen.get_at(pos)
> img_color = map.get_at(pos)
> print(cursor_color, img_color)
>
> Thanks,
> David


Re: [pygame] blit-add to white bug?

2015-08-05 Thread Christopher Night
Pretty sure that's the expected/desired behavior. When you do this, for
each pixel, any of the rgb channels that's 0 will remain at 0, and any
that's nonzero will get maxed out to 255. The orange starts at r,g,b =
255,102,0. When you blit it over itself 255 times, the green channel gets
maxed out to 255, so you wind up with 255, 255, 0, which is yellow. You'd
get something similar for pixels with a color that had a 0 value in the red
or green channels. You've got some blue color in the rainbow wheel, but
none of the blue pixels actually have 0 values in red and green.

Same thing with the tomato. In addition to black and white pixels, you're
seeing red, cyan, or yellow, depending on which values were exactly 0 in
the original image.

On Wed, Aug 5, 2015 at 2:19 PM DR0ID dr...@bluewin.ch wrote:

 Hello

 I have been experimenting with the blit method and its blend options. I
 think I have stumbled over a bug either in pygame or SDL (I can't tell).
 Its when adding a surface with itself. When adding it 255 times all
 color values that were  0 will be maxed out to 255. It works most of
 the time. But surprisingly  for colors in the orange tones do not work.
 At least it looks like that, but I can't tell the exact conditions when
 it will  behave strange.

 To demonstrate the strange behavior I have written a small demo. It can
 be downloaded here:

 https://bitbucket.org/dr0id/pyknic/downloads/2015-08-05-blit_to_white.zip

 There are two images displayed: the one on the left if the original, the
 one on the right is the blitted to white image. The only parts that
 don't get white are the ones that were either black or transparent (in
 both cases the values were  (0, 0, 0, a) or (r, g, b, 0)). That is
 expected. The orange colored regions should be white on the right images.

 Can someone explain what is going on? I could not find any clue in the
 pygame C-blitting code.

 Maybe this has already been reported, but I could not find any matching
 entries on the pygame issue tracker on bitbucket.

 Thanks.

 ~DR0ID



[pygame] Module I made for drawing text with pygame

2015-03-16 Thread Christopher Night
Please let me know if you have any feedback or criticism on the module I
have written here:
https://github.com/cosmologicon/pygame-text

This module provides what is, for me, a more convenient interface to
drawing text with pygame.font. It also provides a few effects, such as
outlines and drop shadows. I plan to use this module in future PyWeeks.

Thanks,
Christopher


Re: [pygame] immutable vectors in math package

2014-10-29 Thread Christopher Night
I have not used either the original API nor yours, so this suggestion may
be off base, but if they're going to be immutable, why not subclass
collections.namedtuple(Vector2, x y), and get a few handy methods
defined for free?

-Christopher

On Wed Oct 29 2014 at 7:41:54 PM Greg Ewing greg.ew...@canterbury.ac.nz
wrote:

 Lorenz Quack wrote:

   * you cannot access the components x/y/z directly...
   use ... new accessor methods x()/y()/z()

 Is this change really necessary? It will be a big backward
 step for code readability.

 There shouldn't be any reason you can't provide read-only
 access using attribute notation.

 --
 Greg



Re: [pygame] Pygame surface

2014-09-10 Thread Christopher Night
For reference, here's the discussion from the last time Diliup asked this
same question, a month ago:
https://groups.google.com/forum/#!topic/pygame-mirror-on-google-groups/WIuIlmXvqow


On Tue, Sep 9, 2014 at 7:57 AM, diliup gabadamudalige dili...@gmail.com
wrote:

 How can a Pygame surface be converted to an image file say a jpeg or a png
 WITHOUT writing the file to disk? Say after a screen grab?



Re: [pygame] Pygame surface

2014-09-10 Thread Christopher Night
No, in pygame, both screenshots and images loaded from files are simply
Surface objects. In this case, this fact is documented in the description
for pygame.image.load. Hopefully that makes it clear that it returns a
Surface:
http://www.pygame.org/docs/ref/image.html#pygame.image.load

Good luck!


On Wed, Sep 10, 2014 at 11:54 AM, diliup gabadamudalige dili...@gmail.com
wrote:

 I am asking how to save a SURFACE and NOT an image that was loaded. Aren't
 those two different things?

 Pardon my ignorance but some of the Pygame documentation is not very clear
 to me. Also none of the suggested methods delivered results that were fast
 enough to be used in a practical situation.
 The fastest so far is the normal save to disk and reload as jpeg and then
 the rest.

 Also PIL does not compile well with py2exe.
 Not all packages and modules do.

 Hence the question.
 So looks like my best option is the save to disk and load which is also
 the fastest.

 Thanks to everyone  all for the support which is invaluable.



 --


 On Wed, Sep 10, 2014 at 9:11 PM, Christopher Night cosmologi...@gmail.com
  wrote:

 For reference, here's the discussion from the last time Diliup asked this
 same question, a month ago:

 https://groups.google.com/forum/#!topic/pygame-mirror-on-google-groups/WIuIlmXvqow


 On Tue, Sep 9, 2014 at 7:57 AM, diliup gabadamudalige dili...@gmail.com
 wrote:

 How can a Pygame surface be converted to an image file say a jpeg or a
 png WITHOUT writing the file to disk? Say after a screen grab?





 --
 Diliup Gabadamudalige

 http://www.diliupg.com
 http://soft.diliupg.com/


 **
 This e-mail is confidential. It may also be legally privileged. If you are
 not the intended recipient or have received it in error, please delete it
 and all copies from your system and notify the sender immediately by return
 e-mail. Any unauthorized reading, reproducing, printing or further
 dissemination of this e-mail or its contents is strictly prohibited and may
 be unlawful. Internet communications cannot be guaranteed to be timely,
 secure, error or virus-free. The sender does not accept liability for any
 errors or omissions.

 **




Re: [pygame] image conversion in memory

2014-08-08 Thread Christopher Night
It depends on what precisely you mean when you say that a python variable
is a jpeg image. Do you mean that it's a string containing the contents of
a jpeg image file? So if you wrote it to disk you'd get a jpeg image file?

If that's what you mean, you can do it with PIL and StringIO. (There might
be an easier way.)

import pygame
from PIL import Image
from cStringIO import StringIO

# create an example pygame image
img = pygame.Surface((100, 100))
pygame.draw.circle(img, (255, 0, 0), (50, 50), 40)
# convert to PIL format
imgstr = pygame.image.tostring(img, RGB, False)
pimg = Image.fromstring(RGB, img.get_size(), imgstr)
# save to string
s = StringIO()
pimg.save(s, JPEG)
r = s.getvalue()
s.close()

# r is a string with the contents of a jpeg file. to confirm:
open(img.jpg, wb).write(r)

However, this doesn't seem like a very useful thing to have (and if I
needed it so badly I would just write it to disk and read it back) so I may
be misunderstanding you.


On Fri, Aug 8, 2014 at 5:16 AM, diliup gabadamudalige dili...@gmail.com
wrote:

 Hi all!

 Is there a way to convert a pygame surface to a png or jpeg IN MEMORY
 instead of saving to disk and loading again?
 something like
 get_screen = SCREEN.subsurface(0, 0, SCREENW, SCREENH) # grab the screen

 my_image = get_screen.convert(jpeg) # now convert the image to jpeg

 and now my_image is a jpeg image of get_screen

 I searched the net but couldn't find any other way other than save to disk
 as jpeg and reload.

 Any positive OR negative help is very much appreciated.

 Thanks in advance
 Diliup Gabadamudalige

 http://www.diliupg.com
 http://soft.diliupg.com/


 **
 This e-mail is confidential. It may also be legally privileged. If you are
 not the intended recipient or have received it in error, please delete it
 and all copies from your system and notify the sender immediately by return
 e-mail. Any unauthorized reading, reproducing, printing or further
 dissemination of this e-mail or its contents is strictly prohibited and may
 be unlawful. Internet communications cannot be guaranteed to be timely,
 secure, error or virus-free. The sender does not accept liability for any
 errors or omissions.

 **




[pygame] help subscribing to pygame-users

2014-01-27 Thread Christopher Night
Hi, I'm talking with someone on the /r/pygame subreddit who's having
trouble signing up for this mailing list
(linkhttp://www.reddit.com/r/pygame/comments/1w1y20/unable_to_make_an_account_on_your_website/).
They say they followed the subscribe process but their emails are still not
showing up on the list. Who should I direct them to?

Thanks,
Christopher


Re: [pygame] Python3 version packaged?

2013-12-31 Thread Christopher Night
That's all well and good for development, but if I want to distribute my
game to other Ubuntu users I'm not going to tell players they have to
comment out part of the setup file for one of my dependencies and install
it from source.

I'm not complaining or anything. Set whatever priorities you think are
appropriate. I'm just adding another data point: this is blocking me from
transitioning to Python3.

-Christopher


On Tue, Dec 31, 2013 at 5:47 PM, Lenard Lindstrom le...@telus.net wrote:

 Hi,

 On Gnu/Linux it is simpler to just build Pygame from source. The
 dependencies are libsdl-mixer, libsdl-image, libsdl-ttf, and libportmidi0.
 Installing these libraries, and their header file dev packages should force
 the installation of all Pygame dependencies, such as SDL and freetype2.
 Also be sure to include the Python3 dev package. Since I do most of my
 Pygame development on Linux Mint, there should be no compatibility issues
 on Ubuntu, except with libportmidi0. So I suggest commenting out the Pygame
 midi module entry in the Setup file.

 Lenard Lindstrom


 On 13-12-31 09:36 AM, Sam Bull wrote:

 Can we get a working Python3 version of Pygame packaged either in the
 Ubuntu repositories or in pip3?

 This would be really helpful in allowing us to transition to Python3 for
 our projects.





Re: [pygame] Using pygame.transform.rotozoom()

2013-06-14 Thread Christopher Night
I don't know how to fix your problem, but it seems to me that using an
alpha channel instead of a colorkey would be one solution. It might be
easier than blitting the surface twice, anyway.


On Fri, Jun 14, 2013 at 6:09 AM, Aikiman j...@diadem.co.nz wrote:

 Well Im close but still no cigar on this issue and its been there from
 around
 half way through developing my game. Im trying to achieve a rotating image
 that scales at the same time with a colorkey. Problem is I can get colorkey
 to work. Heres the code...

 self.imagePuff = pygame.image.load(Images/puff.tga).convert()
 self.imagePuff.set_colorkey((0,0,255))
 self.imageMaster = self.imagePuff
 self.rect = self.imageMaster.get_rect()
 self.image = pygame.transform.rotozoom(self.imageMaster, self.angle,
 self.scale/300+0.2)
 self.image.set_colorkey((0,0,0))
 self.rect = self.image.get_rect()
 self.rect.center = oldCenter

 After the rotozoom I end up with the original colorkey failing
 colorkey((0,0,255)) AND with an extra black box around the animation. So
 I
 added the second colorkey colorkey((0,0,0))  which succeeds in ridding
 the
 black box but with the blue background color persisting. Is there a
 workaround I havent tried yet like bringing the image in with transparency
 already - if so how to do? Or do I have to structure my code differently to
 compensate for the double transform like blitting onto a second temp
 surface
 or something fancy like that?

 Thanks in advance



 --
 View this message in context:
 http://pygame-users.25799.x6.nabble.com/Using-pygame-transform-rotozoom-tp744.html
 Sent from the pygame-users mailing list archive at Nabble.com.



Re: [pygame] Fonts

2013-02-24 Thread Christopher Night
Do os.path.exists(filename) to make sure the file exists. It could be your
working directory is wrong, or the capitalization doesn't match.

-Christopher


On Sun, Feb 24, 2013 at 2:45 PM, myles broomes
mylesbroo...@hotmail.co.ukwrote:

  Hi,
 I loaded a .ttf file into the pygame folder but I can't use it in pygame.
 The font is 'baroquescript' and the error I get is as follows: 'IOError:
 unable to read font file 'baroquescript.ttf'. As far as I know, I've put
 the file in the right place but what am I doing wrong?

 Thanks in advance,
 Myles Broomes




Re: [pygame] Professional games made with Pygame?

2013-02-16 Thread Christopher Night
There are a number of PyWeek games made with pygame that I would consider
at least as polished as Nelly's Rooftop Garden. Looking down the list
of highest-rated
games http://www.pyweek.org/all_games/, I notice that Which Way is Up,
Sudo Science, Walkway, Trip on the Funny Boat, 20,000 Light Years into
Space, Robot Toast, Topologiquill, and Stringrolled were all made with
pygame, as far as I know. I'm not sure what the criterion is for
professional-quality, though.

-Christopher


On Sat, Feb 16, 2013 at 9:18 PM, James Paige b...@hamsterrepublic.comwrote:

 I thought that Nelly's Rooftop Garden felt rather polished and
 professional. I think that was a pyweek game.

 ---
 James Paige


 On Sat, Feb 16, 2013 at 02:35:24PM -0800, Al Sweigart wrote:
 Hi everyone, I'm compiling a list of professional-quality games made
 using
 Pygame. These don't necessarily have to be commercial games, but games
 that have a professional level of quality.
 
 So far, I have:
 
 * Dangerous High School Girls in Trouble
 * Frets on Fire
 * Metin2
 * Galcon
 * PyDance
 * SolarWolf
 * Division Especial de Detectives
 Are there any others? Or have I added some games to this list
 erroneously?
 
 -Al



Re: [pygame] Merge: rect optimisation

2012-10-17 Thread Christopher Night
Yeah your new test is correct. I'm surprised it wasn't done that way to
begin with, actually. The inequality comparisons you have are correct for
pygame's definition of a rectangle.

FWIW, I would swap the ordering of the 2nd and 3rd test as you have them.
From a probabilistic argument, this will tend to get you earlier
short-circuiting, though the difference here is going to be very small.

-Christopher

On Wed, Oct 17, 2012 at 10:06 AM, Sam Bull sam.hack...@sent.com wrote:

 Can somebody check the code I've proposed for a merge, I believe it is a
 more efficient method for checking rect intersection:


 https://bitbucket.org/pygame/pygame/pull-request/11/optimise-rect-intersection/diff

 The theory is that if (A.topleft  B.bottomright and A.bottomright 
 B.topleft) then they must be overlapping. This needs about half the
 tests from the current version.

 I also wasn't sure where to put = instead of  to ensure perfect
 backwards compatibility, so it would be great if anybody could point
 that out too.

 Thanks,
 Sam Bull



Re: [pygame] rotate around point

2012-08-20 Thread Christopher Night
Right, but note that performing step 2 with pygame.transform.rotate is not
trivial, since it doesn't rotate about the origin, or any particular point
for that matter: the fixed point of rotation depends on the surface
dimensions and the rotation angle. So your step 2 is itself 3 steps.

For this reason, I generally anchor all my blits to the surface's center.
In this case I would make it easy on myself by adding some margin to the
image so that the desired rotation point is at the center of the image. I
know not everyone likes to do it that way, though.

-Christopher
On Aug 20, 2012 4:32 PM, Mark Wexler mark.wex...@gmail.com wrote:

 To rotate around an arbitrary point,
 1. subtract (vectorially) the center of rotation;
 2. perform rotation (as if about the origin);
 3. add the center of rotation.

 Mark


 On Mon, Aug 20, 2012 at 10:10 PM, Ricardo Franco
 ricardo.kr...@gmail.com wrote:
  Hi, I need to rotate around a specific point.
  It's a person animation. So the arms should rotate over the shoulders'
  point.
  How to do that?
 
  --
  Ricardo Franco Andrade @ricardokrieg
 
  ( Game | Desktop | Web ) Developer
 
  email: ricardo.kr...@gmail.com
  contact: +55 (86) 9958 9725
   +55 (86) 9436 0830
  twitter: twitter.com/ricardokrieg
  facebooK: https://www.facebook.com/krieg.ricardo
  github: https://github.com/ricardokrieg
 



 --
 Mark Wexler
 Laboratoire Psychologie de la Perception
 CNRS - Université Paris Descartes
 45, rue des Saints-Pères
 75006 Paris, France
 http://wexler.free.fr



Re: [pygame] Red-to-violet color palette

2012-07-13 Thread Christopher Night
According to Wikipedia, violet is (127, 0, 255), so this should work:

tuple((255-(i+1)//2, 0, i) for i in range(256))

-Christopher

On Fri, Jul 13, 2012 at 12:20 PM, Ricardo Franco ricardo.kr...@gmail.comwrote:

 I would like to know how to build a specifc color palette, its the
 red-to-violet color palette.
 To build the grayscale color palette I use:

 grayscale_palette = tuple([(i, i, i) for i in range(256)])

 How do to get the red-to-violet color palette?

 --
 Ricardo Franco Andrade @ricardokrieg

 ( Game | Desktop | Web ) Developer

 email: ricardo.kr...@gmail.com
 contact: +55 (86) 9958 9725
  +55 (86) 9436 0830
 twitter: twitter.com/ricardokrieg
 facebooK: https://www.facebook.com/krieg.ricardo
 github: https://github.com/ricardokrieg




Re: [pygame] Improved Sprites System - Call for Suggestions

2012-06-02 Thread Christopher Night
On Fri, Jun 1, 2012 at 2:29 PM, DR0ID dr...@bluewin.ch wrote:

 On 01.06.2012 15:29, Sagie Maoz wrote:

 2. Setting a sprite's anchor points for handling in movement, animation,
 collision etc.
 5. New visual attributes for sprites:
- Rotation angle
- Scale

 2. the sprites anchor point should be just an offset, not limited to
 'topleft', 'midtop', 'topright',... and the other rect attributes


I want to be able to specify center or midbottom for the sprite anchor
without knowing the image's dimensions. And I want that anchor point to
remain in the appropriate place even if the image is rotated, scaled, or
flipped. I'm not sure that an offset would accomplish this, but if so, then
that's okay.

-Christopher


Re: [pygame] Improved Sprites System - Call for Suggestions

2012-06-02 Thread Christopher Night
On Sat, Jun 2, 2012 at 1:50 PM, DR0ID dr...@bluewin.ch wrote:

  On 02.06.2012 16:46, Christopher Night wrote:

 On Fri, Jun 1, 2012 at 2:29 PM, DR0ID dr...@bluewin.ch wrote:

 On 01.06.2012 15:29, Sagie Maoz wrote:

 2. Setting a sprite's anchor points for handling in movement, animation,
 collision etc.
 5. New visual attributes for sprites:
- Rotation angle
- Scale

  2. the sprites anchor point should be just an offset, not limited to
 'topleft', 'midtop', 'topright',... and the other rect attributes


  I want to be able to specify center or midbottom for the sprite
 anchor without knowing the image's dimensions. And I want that anchor point
 to remain in the appropriate place even if the image is rotated, scaled, or
 flipped. I'm not sure that an offset would accomplish this, but if so, then
 that's okay.

  -Christopher


 Hi

 I agree, what I suggested is that both things should be possible: a
 general offset and/or specifying 'center' or 'midbottom' or

 I'm not sure right now how the math to maintain the point at the
 appropriate place. Maybe this needs some more specification for the
 different transformations (rotation, flip, scale).


Well the desired behavior is pretty straightforward to me. Say I specify a
sprite's anchor as midbottom, and the sprite's image has a single orange
pixel at its mid-bottom. Then if I ask to draw the sprite at (200, 100),
then that orange pixel should wind up at (200, 100) no matter how the
sprite is transformed (maybe one pixel off because of rounding). The math
shouldn't be too hard to work out from that.

-Christopher


Re: [pygame] Best practices for creating multiple resolution 2D pixel-art games?

2012-04-05 Thread Christopher Night
On Thu, Apr 5, 2012 at 12:24 PM, Santiago Romero srom...@sromero.orgwrote:


 - Game graphics (pixel-art, not vector or 3d graphics): What's the best
 way to create the graphics? Do them high-res, try to ask always for the
 highest resolution and downscale if not (losing quality)? Do them mid-res
 and upscale / downscale depending on the resolution? Create them in 2 or 3
 different sizes to minimize quality losing in scaling?


Depends on your exact art style. I always hand-draw my graphics at a very
high resolution (5-10x how they appear in the game) and downsample when the
graphics are loaded. My graphics actually look bad at full resolution but
improve when downsampled, because I don't avoid aliasing because I know
it'll be smoothed over when it's shrunk. This lets me change the game
resolution pretty easily, and ideally I let the player zoom in and out and
pick arbitrary resolutions. Basically if your graphics start at a large
enough resolution, you can treat them like you would vector graphics. I
think it works great.

This technique fails, however, if you're doing the distinctive retro art
style commonly called pixel art. In that case, you don't want to avoid
aliasing - you want to control each pixel very exactly. I've never worked
with that kind of art, but I know what I would do. I would draw my graphics
assuming a certain resolution for the game, say 400x300, and allow people
to scale to any integer multiple of this, such as 800x600 or 1200x900. In
fact I'd draw the whole thing to a 400x300 Surface and then just scale it
up. Should look good while maintaining that distinctive style.


 - Game engine: when creating the scoreboard, menues, inventories, position
 items in the screen, define sprite-speeds ... should I use percentages
 instead of pixels? ( % ). Should I, instead, work in a base resolution
 (640x480) and scale all (pixel-speed for sprites, on-screen text and
 scoreboards positions, etc) according to the relation base-resolution /
 real-resolution? And what about the ratio (16:9 - 4:3) change (it's not
 just an scaling problem)?


This is a very nontrivial series of questions. If you allow arbitrary
resolutions without doing something cheap like letterboxing, you're going
to have to put in significant effort. But one question you asked has a
clear answer: objects in the game world should definitely not know anything
about pixels. All game mechanics should use world coordinates and world
units, and only your drawing routines should translate these into actual
pixels. Unless you're absolutely positive that you'll never want to change
resolutions (eg developing for a game console), sprite positions should not
be in terms of pixels.

-Christopher


Re: [pygame] Best practices for creating multiple resolution 2D pixel-art games?

2012-04-05 Thread Christopher Night
On Thu, Apr 5, 2012 at 5:36 PM, Santiago Romero srom...@sromero.org wrote:


  I just was hoping that everybody would already faced this problem before
 me with alternatives different to:

 a.- Render the display with OpenGL.
 b.- Force fullscreen fixed resolution.
 c.- Force windowed fixed resolution.
 d.- Support a couple of concrete resolutions.


Well, not to say that my way is the best way or anything, but again, my
standard method of doing things does not use any of those four options.

1.- I don't have the resources to do precious hi-res aliased cartooned or
 cell-shaded graphics like those that can be seen in recent Android, iOS or
 PC games. Surely, even in low-res modes you need an army of artists to
 create such graphics


Yeah, basically, there's no way for someone (like me) with limited artistic
talent to make good-looking games without either a *lot* of effort, or
gameplay that's amenable to procedural graphics. I use procedural graphics
as much as possible, but when I need something drawn, I can spend hours on
a single frame of a character animation, and I don't see any way around
that, regardless of your resolution. If you're working with an artist, you
need to consult with them to determine what's going to look best. If you're
doing it yourself, I recommend downsampling huge sprites unless you're
specifically going for that retro look.

There seems to be some idea that it's easier to make a 64x64 sprite that
looks good than to make a 640x640 sprite that looks good when it's
downsampled to 64x64. I don't find that to be the case. Even if I wanted to
make a 64x64 sprite I would start by drawing it at higher resolution and
downsampling anyway, so it doesn't really matter if you do it in your
drawing program or in the game. It is more processor and memory intensive,
but that's a very minor consideration on a modern desktop unless you have
thousands of frames worth of graphical assets.


 2.- For the Widescreen vs 4:3 problem, with my retro-graphics games, I
 think the best option is to find the nearest videomode to 800x600 in
 widescreen and center the game area in the screen.


That's probably best. One thing I would keep in mind is that a 4:3 setting
like 800x600 may not have a 1:1 aspect ratio on widescreen displays. I like
to ask pygame for the highest possible resolution and then choose from the
resolutions with that same aspect ratio.

On the other hand, retro graphics tend to look fine even if the aspect
ratio is off, especially after you've played for a few minutes and you've
gotten used to it.

Good luck!

-Christopher


[pygame] Anyone want to critique my platform game prototype?

2012-04-01 Thread Christopher Night
I made a pygame prototype for a platforming game I'm planning. As we all
know, platform games require meticulously tuned mechanics. I finally got it
to where I like it, but that probably means it's still pretty terrible. If
anyone wants to try it out and offer suggestions, I'd be very interested.

https://unifac.googlecode.com/hg/UFX/prototype/platformer-2.py

You control with the arrow keys (up to jump). You have four special
abilities:

   - sprint (tap forward and then hold forward)
   - flip (jump immediately after turning, lets you reach higher platforms)
   - wall jump (can't do it off most platforms, only the semi-transparent
   blocks with vertical walls)
   - hang off ledges (can only do it on red and green platforms with balls
   on the ends)

You can also go into slow-motion by holding Shift, or toggle slow-mo with
Caps Lock. Ctrl is fast-forward, but I don't recommend it. Esc to quit.

If you try it, let me know if you have trouble executing these abilities,
or if you accidentally execute them when you don't mean to. The placement
of the platforms in the demo is totally procedural, so you may find
yourself stuck, but you should be able to get pretty high.

I'd also be interested in any recommendations for well-made platform games
written in pygame with really tight controls, if you have any.

Thanks!
-Christopher


Re: [pygame] Anyone want to critique my platform game prototype?

2012-04-01 Thread Christopher Night
On Sun, Apr 1, 2012 at 12:32 PM, Ian Mallett geometr...@gmail.com wrote:

 On Sun, Apr 1, 2012 at 1:48 AM, Christopher Night 
 cosmologi...@gmail.comwrote:

 I made a pygame prototype for a platforming game I'm planning. As we all
 know, platform games require meticulously tuned mechanics. I finally got it
 to where I like it, but that probably means it's still pretty terrible. If
 anyone wants to try it out and offer suggestions, I'd be very interested.

 https://unifac.googlecode.com/hg/UFX/prototype/platformer-2.py

 You control with the arrow keys (up to jump). You have four special
 abilities:

- sprint (tap forward and then hold forward)
- flip (jump immediately after turning, lets you reach higher
platforms)
- wall jump (can't do it off most platforms, only the
semi-transparent blocks with vertical walls)
- hang off ledges (can only do it on red and green platforms with
balls on the ends)

 You can also go into slow-motion by holding Shift, or toggle slow-mo with
 Caps Lock. Ctrl is fast-forward, but I don't recommend it. Esc to quit.

 If you try it, let me know if you have trouble executing these abilities,

 Flipping is a little too hard.

 or if you accidentally execute them when you don't mean to.

 Sprinting.  I ended up running off the edge and falling all the way back
 to the ground.



Thanks very much for trying it! If you get a chance, I'd be very interested
in how it feels to you after tweaking the keypress time intervals. The time
to execute the flip is 0.25, on lines 159 and 161. Maybe increase it 0.35.
The time to execute the sprite is 0.4, on lines 166 and 169. Maybe reduce
it to 0.3.

-Christopher


Re: [pygame] Anyone want to critique my platform game prototype?

2012-04-01 Thread Christopher Night
On Sun, Apr 1, 2012 at 7:47 PM, Ian Mallett geometr...@gmail.com wrote:

 On Sun, Apr 1, 2012 at 10:46 AM, Christopher Night cosmologi...@gmail.com
  wrote:

 Thanks very much for trying it! If you get a chance, I'd be very
 interested in how it feels to you after tweaking the keypress time
 intervals. The time to execute the flip is 0.25, on lines 159 and 161.
 Maybe increase it 0.35. The time to execute the sprite is 0.4, on lines 166
 and 169. Maybe reduce it to 0.3.

 Yeah.  That makes it easier.  Got to around 19.


Wow, you must have really got the hang of it, the farthest I ever got was
15. If you still have it, I would be very interested in getting the
playback file that should have been made when you played through that long.

Thanks again for trying!

-Christopher


Re: [pygame] Making Games with Python Pygame free book

2012-03-20 Thread Christopher Night
On Tue, Mar 20, 2012 at 12:57 AM, Greg Ewing greg.ew...@canterbury.ac.nzwrote:

 Christopher Night wrote:

 The idea is that if we could independently stimulate each of the three
 colors receptors (cones) in our eyes, then we could reproduce any visual
 sensation and thereby any color. The problem is ... there's no such thing
 as a wavelength of light that stimulates the middle (green) cones without
 also stimulating either of the outer two.


 But that means we never experience the sensation of
 having just the green cones stimulated, so there is
 no need to reproduce it.

 Unfortunately that's not the case. Here's a simplified example to show the
problem. Consider four variables red, yellow, green and blue, representing
the intensity of four different wavelengths of monochromatic light. Any of
them can have any positive value. Say the amount of stimulation each cone
receives is:

LOW = 1 x red + 0.5 x yellow + 0.2 x green
MEDIUM = 0.2 x red + 0.5 x yellow + 1 x green + 0.2 x blue
HIGH = 0.2 x green + 1 x blue

Now, the question is, how can you reproduce the response you get with
yellow light, with just red, green, and blue? Yellow stimulates the low and
medium cones with equal intensity, and the high cone not at all. So if
(red, yellow, green, blue) = (0, 1, 0, 0), then (LOW, MEDIUM, HIGH) = (0.5,
0.5, 0). Using only red, green, and blue, the only way to get LOW = MEDIUM
is to use equal parts red and green. But if green  0, then HIGH  0.

Of course you might say, maybe a different set of three wavelengths would
be able to produce the same response as any monochromatic light. And some
sets do better than others. But as I understand it, no set of three is
perfect. (Also, these are obviously completely made-up numbers.)

-Christopher


Re: [pygame] Making Games with Python Pygame free book

2012-03-19 Thread Christopher Night
It's complicated, but red, yellow, and blue are a good enough set of
primary colors that they were used for a long time. CMYK is superior, but
neither of them can reproduce every color that the human eye can see.
Neither can RGB light, for that matter.

http://en.wikipedia.org/wiki/RYB_color_model

-Christopher

On Mon, Mar 19, 2012 at 3:02 PM, Russell Jones russell.jo...@gmail.comwrote:

 I'm pretty sure that's not the whole story as pigments are subtractive
 whilst light is additive. One can't take red, green and blue paint and make
 any colour. IIRC.

 Russell


 On 19 March 2012 16:10, Ian Mallett geometr...@gmail.com wrote:

 On Mon, Mar 19, 2012 at 9:49 AM, Russell Jones 
 russell.jo...@gmail.comwrote:

 Great news :) I liked IYOCGwP and have mentioned it here before now.

 BTW, on page 34 of the new book you write (Red, blue, and yellow are
 the primary colors for paints and pigments, but the computer monitor uses
 light, not paint.)

 The primary colours for pigment and paint are cyan, yellow and magenta,
 no?

 Russell

 There is a color space that defines all possible colors.  Primary
 colors are the colors we choose as basis vectors.  Both red-blue-yellow
 and cyan-magenta-yellow are valid basis vectors; the former more often used
 in painting, the latter more often used in printing.
  Ian





Re: [pygame] Making Games with Python Pygame free book

2012-03-19 Thread Christopher Night
On Mon, Mar 19, 2012 at 5:05 PM, Miriam English m...@miriam-english.orgwrote:

 Because we only have 3 color detector cells in our eyes we can imitate any
 color with various combinations of red, green, and blue lights mixed
 together in varying amounts.


Unfortunately it's not that simple. The idea is that if we could
independently stimulate each of the three colors receptors (cones) in our
eyes, then we could reproduce any visual sensation and thereby any color.
The problem is that this is impossible. There's no such thing as a
wavelength of light that stimulates the middle (green) cones without also
stimulating either of the outer two. There's significant overlap in their
spectral response.

http://upload.wikimedia.org/wikipedia/commons/1/1e/Cones_SMJ2_E.svg

-Christopher


Re: [pygame] Declaring variables in function as if at code's line-level

2012-03-12 Thread Christopher Night
On Mon, Mar 12, 2012 at 3:27 PM, Brian Brown bro...@gmail.com wrote:

 Thanks for the replies everyone.
 I guess Python just doesn't have a
 declare-variable-as-global-for-whole-module feature.

 (I don't generally have problems with variable overlap because I'm very
 careful with naming my global variables.)

 (I just remembered though-- for some reason,
 list-type variables' individual values/items  can be easily accessed
 throughout the whole module even if:  it was just globaled once inside
 the function it was created.)

 But I just wish I could create variables (of ANY TYPE) which are
 universally acknowledged by the WHOLE module.

 Many of my variables' names are re-stating the exact value they hold, so I
 rarely have any confliction with names:

 filename_of_current_level = 'desert.txt''
 Font__New_Times_Roman_size_20 = ...
 pi_divided_by_180 = math.pi() / 180

 etc.
 The names are just according to what values they hold which-- are all
 unique anyways!
 And when the number of variables start reaching the hundreds, it just gets
 really crazy with global this global that ALL OVER my code, again and
 again . . .
 : (
 I have to keep remembering to global every other variable in any function
 that uses my main game variables.


Listen carefully (I say that because this has already been explained to you
multiple times). You don't need to use the global keyword to access a
global variable in a function if you don't assign to that variable within
the function. Two of your three examples (Font__New_Times_Roman_size_20 and
pi_divided_by_180) are extremely likely to fall into this category every
time they appear in a function. I think if you looked through your code
carefully, you'd see that you need far fewer global keywords than you
actually think you do.

-Christopher


Re: [pygame] Declaring variables in function as if at code's line-level

2012-03-10 Thread Christopher Night
It's not clear at all what you mean by line-level. It sounds like you
mean variables that are at the global scope, ie, you want to declare global
variables. The answer is you use the global keyword within the function.
Sorry if this seems like a lot of extra work, but I doubt you'll find much
sympathy, since what you're doing is discouraged by most python users.

One other possibility that I doubt you'll prefer is declaring a global
object, and every time you want to declare a variable on the global scope,
you set it to a member of that object. To wit:

class globalstuff: pass

def function1():
globalstuff.x = 100

def function2():
print globalstuff.x

Don't freak out at the fact that I used the class keyword. globalstuff is
not what you normally think of as a class. That's just how you declare a
namespace in python.

If line-level means something other than global variables, please explain
in more detail.

-Christopher

On Sat, Mar 10, 2012 at 3:39 PM, Brian Brown bro...@gmail.com wrote:

 My plan is to make my program function-oriented.
 (Much less complicated than creating unnecessary classes and modules
 (each with more functions) for something as simple as a small game
 with just integer variables and string variables.)
 Only using line-level and function-level with global variables
 makes everything simple and easy. I don't understand why there's so
 much hype about creating a new class or module whenever possible--
 as if it will somehow magically make a program execute with more
 satisfactory results.

 Thank you Ciro, but yes, I think you didn't answer my question.


 On 3/10/12, Ciro Duran ciro.du...@gmail.com wrote:
  You can just declare your variables inside a function and their scope
 will
  only reach inside that function.
 
  If you declare module variables (or global variables, if you fancy that
  name more) you can refer them inside functions without adding anything.
 But
  if you want to assig something to the variable (eg. Create an object) you
  must specify the global keyword at the beginning of the function.
 
  Sorry if I didn't get the point of your question.
 
  Ciro
 
  El sábado 10 de marzo de 2012, Brian Brown bro...@gmail.com escribió:
  Hi pygame users, just a simple question-- How can one cause variables
  at function-level to behave like variables at line-level? (With
  basic python code) I just want to avoid using global over and over
  again (in many different functions) while I want to declare, use, and
  delete all my game's variables inside functions.Thanks.
  Matt
 
 



Re: [pygame] Declaring variables in function as if at code's line-level

2012-03-10 Thread Christopher Night
Yeah, okay. Just to be clear, you're no longer asking for advice at this
point, you're just giving your opinion of flaws that python has, right?
You understand the situation, right?

-Christopher

On Sat, Mar 10, 2012 at 4:58 PM, Brian Brown bro...@gmail.com wrote:

 #example 1:

 variable_declared_at_line_level1 = 1
 variable_declared_at_line_level2 = 2

 def a():
  print variable_declared_at_line_level1
  print variable_declared_at_line_level2

 def b():
  print variable_declared_at_line_level1
  print variable_declared_at_line_level2

 a()
 b()
  1
  2
  1
  2

 #example 2:

 def init_game_variables():
  global variable_declared_in_function1
  global variable_declared_in_function2
  variable_declared_in_function1 = 1
  variable_declared_in_function2 = 2

 def a():
  global variable_declared_in_function1
  global variable_declared_in_function2
  print variable_declared_at_line_level1
  print variable_declared_at_line_level2

 def b():
  global variable_declared_in_function1
  global variable_declared_in_function2
  print variable_declared_at_line_level1
  print variable_declared_at_line_level2

 init_game_variables()
 a()
 b()
  1
  2
  1
  2

 # It's such a simple concept. I don't know why python doesn't have a
 declare-global-for-all-functions. I hate to have to type
 game.player or game.badguy for every other thing too. It doesn't
 make any sense. A variable should be able to be accessed with minimal
 effort. Because that's what the whole program is about. Accessing
 variables and displaying them.

 DO:
 * Access variables.
   (Move game according to current-variable-status and player-input)

 * Output to graphics and sound card.
   (Display game according to current-variable-status.)
 LOOP

 That's really all we need.

 And the more straight-forward it is, the less harder you make it for
 yourself.

 Chart out the variables. Don't group any unnecessarily.
 Chart out the functions. Don't put any functions inside of others
 unnecessarily.
 Simplify everything. Don't give unnecessary fancy names to anything
 that shouldn't even be there in the first place.
 Give everything sensible and technically accurate names.

 And your program should be so easy . . .
 It saves hours of pointless conventional debugging and hair pulling
 frustration.
 I guess Python still has many flaws.

 On 3/10/12, Christopher Night cosmologi...@gmail.com wrote:
  It's not clear at all what you mean by line-level. It sounds like you
  mean variables that are at the global scope, ie, you want to declare
 global
  variables. The answer is you use the global keyword within the
 function.
  Sorry if this seems like a lot of extra work, but I doubt you'll find
 much
  sympathy, since what you're doing is discouraged by most python users.
 
  One other possibility that I doubt you'll prefer is declaring a global
  object, and every time you want to declare a variable on the global
 scope,
  you set it to a member of that object. To wit:
 
  class globalstuff: pass
 
  def function1():
  globalstuff.x = 100
 
  def function2():
  print globalstuff.x
 
  Don't freak out at the fact that I used the class keyword. globalstuff
 is
  not what you normally think of as a class. That's just how you declare a
  namespace in python.
 
  If line-level means something other than global variables, please
 explain
  in more detail.
 
  -Christopher
 
  On Sat, Mar 10, 2012 at 3:39 PM, Brian Brown bro...@gmail.com wrote:
 
  My plan is to make my program function-oriented.
  (Much less complicated than creating unnecessary classes and modules
  (each with more functions) for something as simple as a small game
  with just integer variables and string variables.)
  Only using line-level and function-level with global variables
  makes everything simple and easy. I don't understand why there's so
  much hype about creating a new class or module whenever possible--
  as if it will somehow magically make a program execute with more
  satisfactory results.
 
  Thank you Ciro, but yes, I think you didn't answer my question.
 
 
  On 3/10/12, Ciro Duran ciro.du...@gmail.com wrote:
   You can just declare your variables inside a function and their scope
  will
   only reach inside that function.
  
   If you declare module variables (or global variables, if you fancy
 that
   name more) you can refer them inside functions without adding
 anything.
  But
   if you want to assig something to the variable (eg. Create an object)
   you
   must specify the global keyword at the beginning of the function.
  
   Sorry if I didn't get the point of your question.
  
   Ciro
  
   El sábado 10 de marzo de 2012, Brian Brown bro...@gmail.com
 escribió:
   Hi pygame users, just a simple question-- How can one cause variables
   at function-level to behave like variables at line-level? (With
   basic python code) I just want to avoid using global over and over
   again (in many different functions

Re: [pygame] Declaring variables in function as if at code's line-level

2012-03-10 Thread Christopher Night
On Sat, Mar 10, 2012 at 6:30 PM, Brian Brown bro...@gmail.com wrote:

 Hi pygame users, just a simple question-- How can one cause variables
 at function-level to behave like variables at line-level? (With
 basic python code) I just want to avoid using global over and over
 again (in many different functions) while I want to declare, use, and
 delete all my game's variables inside functions.Thanks.

 It should make my program very simple and straight-forward if I could
 do this. (As I have explained in the previous replies to this thread)
 I would like to know how it can be done-- without immature,
 unproductive statements like:
 Don't freak out at the fact that I used the class keyword.
 Thank you.


Just to be clear, you decided not to believe Ciro when he answered your
question by saying that you need the global keyword? And you decided not to
believe me when I answered your question by saying the same thing? And you
decided not to rephrase your question after Ciro said it was difficult to
understand, and I suggested you clarify what you mean by the term
line-level that you seem to have made up?

And now you're hoping that someone else will take the time to respond to
you, despite your apparent disregard for correct answers and suggestions?

Just being clear. Good luck with that.

-Christopher


Re: [pygame] Re: Pygame, pyglet, 2d, 3d, and performance (reflexions/discussion)

2012-02-13 Thread Christopher Night
On Mon, Feb 13, 2012 at 6:04 AM, Santiago Romero srom...@sromero.orgwrote:


  Some do have used OpenGL with Pygame for ever, with PyOpenGL etc. I
 think ..

 Can pygame (event system, game loop, etc) can be used among with
 PyOpenGl, using the last one just for the blitting?

 I mean: can an already working pygame game be modified only in the
 blitting part to render the sprites with OpenGL (modifying only the
 blit()?


Yeah that's pretty much how it works. It's the same as you would do for an
SDL/OpenGL game, if I understand correctly.

But I don't think anyone's gotten PyOpenGL working on Android, so if you
need to deploy to mobile devices, that would seem to be a dealbreaker.

I have to say, performance seems to be a really high priority for you,
compared with most people on this list. If you're always going to want
great performance from the weakest devices available, python and Pygame are
clearly at a disadvantage.

Incidentally, I'd love to see the SDL game you ported to HTML5 if you feel
like sharing!

-Christopher


Re: [pygame] Substantial Lag

2012-02-12 Thread Christopher Night
You're only updating 5 frames a second, so yu should expect delays of up to
0.2s, and if you tap the key fast enough it won't register. Why not change
the 5 to 50 or something?

-Christopher
On Feb 12, 2012 8:02 PM, Ryan Strunk ryan.str...@gmail.com wrote:

 Hi everyone,
 I apologize in advance for posting 43 lines of code, but I can't figure out
 where on Earth the trouble is coming from.
 When I run this code, the keys do exactly what I'd like, but I'm noticing a
 delay of a few tenths of a second between when I press the key and when the
 sound of the step is played. Further, sometimes when I tap an arrow key
 quickly, the player won't even take a step.
 Can anyone please tell me what I'm doing wrong? This looks sound to me.

 import time
 import pygame
 from sound_lib.stream import FileStream
 from sound_lib.output import Output

 class Player(object):

def __init__(self):
self.x = 10
self.step = FileStream(file=sounds/step.ogg)
self.step.pan = 0
self.step_time = 0.25
self.last_step_time = 0.0

def move(self, dir):
if time.time() - self.last_step_time = self.step_time:
return
if self.x + dir  1 or self.x + dir  20:
return
self.x += dir
if dir  0:
self.step.pan += 0.1
else:
self.step.pan -= 0.1
self.step.play(True)
self.last_step_time = time.time()

 def main():
clock = pygame.time.Clock()
o = Output()
guy = Player()
screen = pygame.display.set_mode((640, 400))
while(True):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
guy.move(-1)
if keys[pygame.K_RIGHT]:
guy.move(1)
for event in pygame.event.get(): pass
clock.tick(5)

 if __name__ == '__main__':
main()

 Thanks much,
 Ryan




Re: [pygame] Antialiased circle

2012-01-18 Thread Christopher Night
On Wed, Jan 18, 2012 at 4:49 AM, Florian Krause siebenhundertz...@gmail.com
 wrote:

 Maybe someone could translate from Java?
 http://www.databasesandlife.com/anti-aliased-polygon-filling-algorithm/


If that person's solution is acceptable for us, I don't think any
translation is needed. It's pretty straightforward:

*What about anti-aliasing? (My) solution: Run the algorithm at 4x X and Y
resolution, and for each scanline of the algorithm, build up an internal
array (one entry for each horizontal screen pixel), how many of the
potential 16 subpixels should be plotted. After 4 subpixel scanlines, plot
the actual pixel scanline and clear the internal array.*


So we could do it with a call to gfxdraw.filled_polygon then a call to
transform.smoothscale. It seems sub-optimal, but maybe it's better than
nothing.

-Christopher


Re: [pygame] Capabilities of Pygame

2012-01-13 Thread Christopher Night
On Thu, Jan 12, 2012 at 9:04 PM, Ryan Strunk ryan.str...@gmail.com wrote:

  If you're working on a game that you could conceivably write by
 yourself or with a small team, python will probably be up for the job.

 That’s good to know. With as much as critics of Python harp on the speed,
 I was worried that resulting software was going to crawl along at a snail’s
 pace. Are there any situations that come to mind where Python wouldn’t work?


It's a little complicated. If you write everything in pure python only
using the pygame library, then yes I can easily think of some examples
where it wouldn't work at all, or not have good performance. However, some
(maybe all?) of these can be solved by finding another library written
specifically for that purpose to help you. And, as Sean Wolfe said, there
are people working on speeding up python, and don't forget that computers
are getting faster all the time. So it might not even be the case in a few
years. Given that, if I were making a game that relied heavily one of the
following things, I would reconsider python:

   - 3D - I've only used pyopengl and, I admit, it's kind of slow. When I
   ported a pyopengl game I wrote into C++, I got something like a 10x
   speedup. pyglet might perform better.
   - Huge numbers of sprites, like in the thousands or tens of thousands.
   - Collision detection and physics between more than ~100 objects. There
   are certainly libraries for this, but I'm not sure how they perform
   compared to their C++ counterparts.
   - Pixel-level manipulation of images, although this has gotten much
   better with the surfarray module.
   - Running on a mobile device.
   - Running in a browser.

This has some similarities with Silver's list, which is also good.

-Christopher


Re: [pygame] Capabilities of Pygame

2012-01-12 Thread Christopher Night
If you set out to remake World of Warcraft in python, then by the time you
finish in 200 years, computers will be more than fast enough that your
program will run just fine.

Seriously, what kind of game do you want to make? If you want to work on an
MMORPG, you'll have to be working for a company, in which case you don't
pick a language based on performance, you pick it based on what that
company uses. If you're working on a game that you could conceivably write
by yourself or with a small team, python will probably be up for the job.
In neither case is performance going to be the main consideration of you
personally.

So yeah, you'd run into trouble writing WoW in python, but that's really
not the question you should be asking.

-Christopher

On Thu, Jan 12, 2012 at 8:45 PM, Ryan Strunk ryan.str...@gmail.com wrote:

 Hello everyone,

 As I embark on this journey of learning Pygame and game design, I have one
 last burning question I haven’t been able to find an answer to. I’ve heard
 that Python, as an interpreted language, isn’t as fast as languages like
 C++. It follows, then, that Pygame would suffer the same drawback in terms
 of speed. What I don’t know, though, is how much this potential limitation
 would affect game play.

 Using Pygame, is it possible to create games that would rival the scope
 and complexity of mainstream titles out there. Could you build a World the
 size of World of Warcraft and still have it be responsive to players? Could
 you build a game as fast-moving as Mortal Kombat, play it over the internet
 with a good connection, and still have it be as smooth as the Xbox?

 I want to make sure I don’t get deep into a project only to realize that
 the language was better suited to a different style of game.

 Any help anyone can provide would be greatly appreciated.

 All the best,

 Ryan



Re: [pygame] pyWeek? (Bit OT)

2012-01-11 Thread Christopher Night
On Fri, Jan 6, 2012 at 2:26 PM, Davy Mitchell daftspan...@gmail.com wrote:

 Apologies if this is a bit off topic...

 I was was wondering if the date for the next PyWeek has been announced?


No it hasn't. The latest announced competition is generally found on the
front page of pyweek.org.

The previous even-numbered competitions were 03 April, 28 March, 26 April,
and 30 March, so I would expect it some time in that range again this time.
I don't know if Richard Jones has decided when it'll be yet, though.

The last competition was announced on this mailing list about two months
beforehand, as well as python-announce-l...@python.org,
python-l...@python.org, gameco...@sykhronics.com,
pyglet-us...@googlegroups.com, and cocos-disc...@googlegroups.com. So,
check one or more of these lists I guess.

Also, if you have an account on pyweek.org, I think you'll get an email
when theme voting is open (one week before the competition).

-Christopher


Re: [pygame] New way for drawing an arc

2012-01-05 Thread Christopher Night
Cool! When I needed to draw an arc more than a couple of pixels wide, I
approximated it with a polygon. I think it gave pretty good results. I'm
not sure how it would compare performance-wise, but it should involve a lot
fewer trig function calls. Have you tried this method?

-Christopher

On Thu, Jan 5, 2012 at 6:36 PM, Silver rockac...@gmail.com wrote:

 I recently figured out how to draw an arc in pygame without moire holes
 and allowing stuff like antialiasing. Just if any of your are interested.

 The script is a little slow.
 Also: atan issues where the arc starts out from the left instead of top.
 I can't seem to fix it.


 --Rockachu2



Re: [pygame] squeezing a little fun out of java ... meh

2012-01-03 Thread Christopher Night
On Tue, Jan 3, 2012 at 12:52 PM, Ian Mallett geometr...@gmail.com wrote:

 I suppose you could do things like:
 def my_func(in):
 if type(in) != type(): raise ValueError()
 . . . which emulate static types, but is still not a compile-time error.
  In my early Python libraries, I found I was doing something of this sort
 because I wanted it to be robust, even at the cost of performance (this is
 a case where C++ wins: C++ is plenty fast, you don't have to do this
 particular kind of error checking, and you can put #ifdef/#endif around
 error-checking sections so that the code isn't even *there* when you
 don't want it).


That's good, I recommend this simple method for small-to-medium projects.
The difference between dynamic and compile-time errors is minor when your
compile times are almost instantaneous. You can get most of the benefit you
would have gotten with static typing pretty easily with this method.

Just keep in mind that you usually *don't* want static typing. Don't go
crazy and check the type of every single argument, just things for which
only one type will do. Often numbers or Surfaces will fall into this
category. Probably the most common issue that static typing would have
helped me with when writing pygame games is simply getting the arguments to
a function call out of order.

As for performance, just make it an assert which you disable (with -O) when
you distribute the game.

-Christopher


Re: [pygame] setting + modifying a variable for use across the entire application

2011-12-17 Thread Christopher Night
On Sat, Dec 17, 2011 at 10:15 AM, Sean Wolfe ether@gmail.com wrote:

 I'll have to dig in more to see the differences between our code.
 here's what was happening though in general -- the  problem

 1. main module imports settings as blank
 2. main module imports child modules
 3. when imported, child modules import settings, also as blank
 4. main module modifies settings

 so the child modules were importing the blank version of the module
 rather than the verision modified later.


Yep, I understand. That definitely should have worked fine. main.settings
and child.settings both refer to the same object, so modifying one will be
seen on the other. Anyway, if it's not a big deal for you, you don't have
to dig into it or anything, but if you find your code getting more
complicated than it needs to be, it might be worth taking another look!

-Christopher


Re: [pygame] Help with pygame

2011-12-14 Thread Christopher Night
On Mon, Dec 12, 2011 at 6:06 PM, Christopher Night
cosmologi...@gmail.comwrote:

 Try putting this in the python interpreter and tell us what you get. (Copy
 and paste the output exactly as you get it. Don't try to summarize):

 open(images.BMP) ; import pygame ; pygame.image.get_extended() ;
 pygame.image.load(images.BMP)


On Wed, Dec 14, 2011 at 3:47 PM, Zack Baker zbaker1...@gmail.com wrote:

 BTW i think im just going to reinstall pygame
 the get extended() thing returned 0


Sigh great. Best of luck.

-Christopher


Re: [pygame] Help with pygame

2011-12-12 Thread Christopher Night
Can you please post images.BMP? You know, the image file you actually tried
to load? I think it's possible your pygame was installed without support
for file types other than uncompressed BMP. Try putting this in the python
interpreter and tell us what you get. (Copy and paste the output exactly as
you get it. Don't try to summarize):

open(images.BMP) ; import pygame ; pygame.image.get_extended() ;
pygame.image.load(images.BMP)

Just a helpful tip, but it's kind of frustrating for people to try to help
you when you keep switching it around. It's great to try to work things
out, but you need to be consistent when you ask for help. Don't say this
code snippet produces this error if the error was actually produced by a
different code snippet. You'll get much better help back. :)

-Christopher

On Mon, Dec 12, 2011 at 5:45 PM, Zack Baker zbaker1...@gmail.com wrote:

 Just because I keep switching it around and trying different images with
 different extensions. I get the same error with all though

 -Zack


 On Dec 12, 2011, at 4:40 PM, Christopher Night cosmologi...@gmail.com
 wrote:

 Okay obvious question why is your code trying to load a file
 called images.BMP if this file's name is green-car.png?

 -Christopher

 On Mon, Dec 12, 2011 at 4:25 PM, Zack Baker zbaker1...@gmail.com wrote:

 green-car.png

 On Dec 11, 2011, at 9:38 PM, Sean Wolfe wrote:

 also .. the error says windows bmp but you're on osx ... maybe we have
 a bug handling bmps in osx?

 On Sun, Dec 11, 2011 at 11:36 PM, Sean Wolfe ether@gmail.com wrote:

 is there a reason why you're loading the image in the while loop? The

 way I'm reading the code you're loading the bmp every 100ms based on

 clock.tick(10).


 How about loading the image first then running the loop.


 How big is the bmp?


 On Sun, Dec 11, 2011 at 9:44 PM, Brian Fisher br...@hamsterrepublic.com
 wrote:

 Zach, code looks fine - can you attach the image as well? The problem

 may lie with it.


 thanks


 On Sun, Dec 11, 2011 at 2:49 PM, Zack Baker zbaker1...@gmail.com wrote:

 Ok guys heres the code. Same error, better code.

 #!/usr/bin/env python


 import pygame

 pygame.init()


 #Set height and width of the screen

 size=[400,500]

 screen=pygame.display.set_mode(size)



 #Loop until user clicks the close button

 done=False

 clock=pygame.time.Clock()


 while done==False:

 #This limits the while loop to a max of 10 times per second

 clock.tick(10)


 for event in pygame.event.get():

 if event.type==pygame.QUIT:

 done=True

 car=pygame.image.load('images.BMP')

 screen.blit(car, (50, 100))

 pygame.display.flip()



 pygame.quit()








 pygame.quit()





 --

 A musician must make music, an artist must paint, a poet must write,

 if he is to be ultimately at peace with himself.

 - Abraham Maslow




 --
 A musician must make music, an artist must paint, a poet must write,
 if he is to be ultimately at peace with himself.
 - Abraham Maslow






Re: [pygame] [Pygame] Joystick Inputs

2011-12-07 Thread Christopher Night
On Thu, Dec 8, 2011 at 12:36 AM, Ian Mallett geometr...@gmail.com wrote:

 Except in the trivial case, the rotated image will still be a different
 size, of course.  Remember to offset the image correctly (I recommend
 calling .get_width() and .get_height()) and then subtracting half that from
 your player's position to get draw coordinates.


Right, you want the image to be centered on the player's position. I think
the clearest way to do it is using pygame.Rect's handy positioning:

rect = self.image.get_rect(center = (self.x, self.y))
screen.blit(self.image, rect)

-Christopher


Re: [pygame] pygame performance limits

2011-11-23 Thread Christopher Night
I don't know why you would be concerned about performance in a visual novel
game. Aren't they pretty undemanding? I haven't played these games very
much, but isn't it just a series of still images (no animations) and a
simple GUI?

You might want to look at a pyweek entry called Gregor Samsa. I know that
team put some effort into optimizing things and wound up with a respectable
framerate even on mobile devices running Android:
http://www.pyweek.org/e/tihoas/

But again, I feel like performance is the least of your concerns if that's
your kind of game. If there's some specific thing you're expecting to cause
low performance, maybe you can ask about it specifically.

Good luck!
-Christopher

On Wed, Nov 23, 2011 at 11:46 AM, Nick Arnoeyts nickarnoe...@gmail.comwrote:

 Alright. Thanks for your reply everyone.

 I'm currently still working on a Ren'py project, but I'm probably going to
 try pygame once that's finished. I'm mostly making visual novels, though,
 so it's possible that I'm staying with ren'py until I reach its limits.

 yours truly
 armornick


 2011/11/23 stabbingfinger stabbingfin...@gmail.com

 Hi, Armor Nick.

 Some common bottlenecks I've encountered:

 rendering many images per frame
 brute force collision checking
 computationally intensive logic and AI
 real-time image transformation
 heavy usage of images with SRCALPHA
 2D and 2.5D layering
 particles

 These are easy limits to hit early on especially in scrollers,
 platformers, and bullet hell type games, or when you start adding
 environment and GFX.

 But there are clever techniques that pygamers have developed to deal with
 them in the form of cookbook recipes, libraries, and modules. Many issues
 can be easily mitigated by selecting a culling technique or two to reduce
 the number of things processed each game loop.

 Some people popping into IRC lately seem easily frustrated by these
 challenges, wanting an inefficient workload to just perform well. I can
 understand the sentiment. But I personally get an immense amount of
 pleasure from conquering these challenges. :)

 When I started pygame three years ago I was told you can't do a scrolling
 action-RPG: it's too much work for the CPU. Since then, computers became a
 significantly faster and several people have produced reasonably impressive
 action-RPGs, as well as other genre.

 For some examples one only has to look among the top places at pyweek.org,
 where pygame competes with the likes of pyglet, cocos2d, and rabbyt, all of
 which have the proclaimed advantage of 3D acceleration. It's become clear
 to me that for most hobby games the only real limitation is the
 resourcefulness of the programmer.

 I personally haven't yet hit a wall with Python or pygame that forced me
 to look at another framework or a natively compiled language, and I've done
 a few relatively ambitious projects.

 That may seem like a biased representation of Python's and pygame's
 capabilities, but I assure you it's not. A few times a year my eyes wander
 to other game development libraries or engines, but I keep coming right
 back to pygame.

 Hope that perspective helps.

 Gumm


 On Wed, Nov 23, 2011 at 6:08 AM, Chris Smith maximi...@gmail.com wrote:

 You can use Renpy for graphic novels. SNES RPG's would be no problem.
 For AI and other things, python might be slow but you will probably be
 surprised how far you can go with it. It'll certainly be easier than going
 the C++ route (although I'm not a C++ fan, to be honest... I'd use Lisp if
 I needed the code to be faster).


 On 23 November 2011 21:47, Nick Arnoeyts nickarnoe...@gmail.com wrote:

 I'm actually not quite sure what I'm going to write yet. Either an RPG
 in the style of SNES-era Final Fantasy, or a visual novel (if you know
 Higurashi or Clannad). I'm not (yet) interested in 3D and I would certainly
 do something like that in C++.

 Pygame is probably fast enough for the graphics, but I was wondering
 how performance would be for AI and other calculations.

 yours truly
 armornick

 2011/11/23 Chris Smith maximi...@gmail.com

 You can't really compare the language C++ with the library Python.

 You could compare C++ / SDL with Python / Pygame, and probably C++
 would be faster (but maybe by not as much as you think)... but it would
 certainly take a lot more time to write the code.

 As to what you can do with Pygame, well it is a 2D library that I find
 fast enough for most things. In some ways I think Pygame is a little
 'old-school': Pygame does not do a lot for you, but it gets out of the 
 way,
 and perhaps most importantly, it's small enough to fit in my mind but big
 enough to do what I want.

 Unless you develop as part of a team you need 3D, you are unlikely to
 choose a project that Pygame cannot handle in some way.

 Perhaps you could tell us more about what you wanted to write... that
 would make it easier to tell you if Pygame could do this for you.

 Chris


 On 23 November 2011 21:07, Nick Arnoeyts 

Re: [pygame] pygame performance limits

2011-11-23 Thread Christopher Night
Whoever said that didn't do a good job distinguishing between casual games
and huge professional games. Presumably they would also say that Flash is
too slow for making games, but that doesn't stop people from making Flash
games.

My very rough estimate is that you can easily get Flash-level performance
from python+Pygame, and with some work you can get better-than-Flash-level
performance. You're unlikely to get C++-level performance without a lot of
work, though. Python may be too slow to write Portal 3 or something, but
I've never seen a Flash game that I thought python couldn't handle (if
someone would write a good vector graphics library for it).

-Christopher

On Wed, Nov 23, 2011 at 1:35 PM, Nick Arnoeyts nickarnoe...@gmail.comwrote:

 Yeah, I'm probably worrying prematurely.
 I'm very easily influenced by FUD and there are a lot of messages floating
 around that Python (and Ruby) are too slow for making games.

 yours truly
 armornick


 2011/11/23 Christopher Night cosmologi...@gmail.com

 I don't know why you would be concerned about performance in a visual
 novel game. Aren't they pretty undemanding? I haven't played these games
 very much, but isn't it just a series of still images (no animations) and a
 simple GUI?

 You might want to look at a pyweek entry called Gregor Samsa. I know that
 team put some effort into optimizing things and wound up with a respectable
 framerate even on mobile devices running Android:
 http://www.pyweek.org/e/tihoas/

 But again, I feel like performance is the least of your concerns if
 that's your kind of game. If there's some specific thing you're expecting
 to cause low performance, maybe you can ask about it specifically.

 Good luck!
 -Christopher


 On Wed, Nov 23, 2011 at 11:46 AM, Nick Arnoeyts 
 nickarnoe...@gmail.comwrote:

 Alright. Thanks for your reply everyone.

 I'm currently still working on a Ren'py project, but I'm probably going
 to try pygame once that's finished. I'm mostly making visual novels,
 though, so it's possible that I'm staying with ren'py until I reach its
 limits.

 yours truly
 armornick


 2011/11/23 stabbingfinger stabbingfin...@gmail.com

 Hi, Armor Nick.

 Some common bottlenecks I've encountered:

 rendering many images per frame
 brute force collision checking
 computationally intensive logic and AI
 real-time image transformation
 heavy usage of images with SRCALPHA
 2D and 2.5D layering
 particles

 These are easy limits to hit early on especially in scrollers,
 platformers, and bullet hell type games, or when you start adding
 environment and GFX.

 But there are clever techniques that pygamers have developed to deal
 with them in the form of cookbook recipes, libraries, and modules. Many
 issues can be easily mitigated by selecting a culling technique or two to
 reduce the number of things processed each game loop.

 Some people popping into IRC lately seem easily frustrated by these
 challenges, wanting an inefficient workload to just perform well. I can
 understand the sentiment. But I personally get an immense amount of
 pleasure from conquering these challenges. :)

 When I started pygame three years ago I was told you can't do a
 scrolling action-RPG: it's too much work for the CPU. Since then, computers
 became a significantly faster and several people have produced reasonably
 impressive action-RPGs, as well as other genre.

 For some examples one only has to look among the top places at
 pyweek.org, where pygame competes with the likes of pyglet, cocos2d,
 and rabbyt, all of which have the proclaimed advantage of 3D acceleration.
 It's become clear to me that for most hobby games the only real limitation
 is the resourcefulness of the programmer.

 I personally haven't yet hit a wall with Python or pygame that forced
 me to look at another framework or a natively compiled language, and I've
 done a few relatively ambitious projects.

 That may seem like a biased representation of Python's and pygame's
 capabilities, but I assure you it's not. A few times a year my eyes wander
 to other game development libraries or engines, but I keep coming right
 back to pygame.

 Hope that perspective helps.

 Gumm


 On Wed, Nov 23, 2011 at 6:08 AM, Chris Smith maximi...@gmail.comwrote:

 You can use Renpy for graphic novels. SNES RPG's would be no problem.
 For AI and other things, python might be slow but you will probably be
 surprised how far you can go with it. It'll certainly be easier than going
 the C++ route (although I'm not a C++ fan, to be honest... I'd use Lisp if
 I needed the code to be faster).


 On 23 November 2011 21:47, Nick Arnoeyts nickarnoe...@gmail.comwrote:

 I'm actually not quite sure what I'm going to write yet. Either an
 RPG in the style of SNES-era Final Fantasy, or a visual novel (if you 
 know
 Higurashi or Clannad). I'm not (yet) interested in 3D and I would 
 certainly
 do something like that in C++.

 Pygame is probably fast enough for the graphics, but I was wondering
 how performance

Re: [pygame] more basic python lists question

2011-11-17 Thread Christopher Night
This is more pythonic (also more efficient):

filenames = [f for f in filenames if f.endswith(.png)]

Your method with the loop won't work in general. Do it like this.

-Christopher

On Thu, Nov 17, 2011 at 1:24 PM, Sean Wolfe ether@gmail.com wrote:

 I find myself often iterating a list looking to remove the
 undesireable elements. I want to do this:

 for f in filenames:
if not f.endswith('.png')
f.delete()

 But I find myself having to do this:

 for i in range(len(filenames))::
if not filenames[i].endswith(.png):
del filenames[i]


 I'm wondering if there is a way to do the first option? I suppose Im
 trying to delete what I'm examining at the same time which maybe is
 why it's problematic.

 Thanks!


 --
 A musician must make music, an artist must paint, a poet must write,
 if he is to be ultimately at peace with himself.
 - Abraham Maslow



Re: [pygame] Re: more basic python lists question

2011-11-17 Thread Christopher Night
On Thu, Nov 17, 2011 at 1:32 PM, Sean Wolfe ether@gmail.com wrote:

 if not f.endswith('.png')
 for f in filenames:
 filenames.remove(f)

 Along with lots of warnings to copy from one list to another rather
 than delete on an iterating list. But really how much harm could it
 do? lol... I think.


No, it won't work. Try it with:

filenames = [a.png, b.gif, c.gif]

-Christopher


Re: [pygame] Save files

2011-11-14 Thread Christopher Night
Some of the responses so far are making things harder than they need to be.
You don't need to use encryption. Just add a secure checksum. Something
like this:

import hashlib
salt = salt used by the whole game
playersalt = salt specific to this player (optional)
def checksum(obj):
return hashlib.sha224(str((salt, playersalt, obj))).hexdigest()

Now your save and load routines would look something like this:

def savegame():
state = score, numBullets, numLives
csum = checksum(state)
pickle.dump((state, csum), savefile)

def loadgame():
state, csum = pickle.load(savefile)
assert csum == checksum(state)
score, numBullets, numLives = state

The playersalt is only necessary if you don't want saved games from one
player to work for a different player.

And of course this assumes you don't release the source code. If you
release the code, there's really no way to prevent players from generating
any saved game they want.

-Christopher

On Mon, Nov 14, 2011 at 7:43 AM, Sam Bull sam.hack...@sent.com wrote:

 I was just wondering what would be the best way to create a game's save
 file. I can save the details in a text file without a problem, but I was
 wondering how you would create the save file in a slightly more
 protected manner. If it is to be a commercial game with trophies and
 things then it would be too easy for the player to open the save file in
 a text editor and change their level or max out their stats etc.
I was just wondering if anybody had a better method of saving, does
 anybody know how the commercial PC games manage this?

 --
 Sam Bull sambull.org
 PGP: 9626CE2B




Re: [pygame] Fast method for pixellated animation

2011-10-24 Thread Christopher Night
The obvious solution is pygame.transform.scale. Whether this is the most
efficient method or not depends on how you're generating the image in the
first place. But if you've already got a 100x100 image as a pygame.Surface
object, and you want to create a 400x400 image out of it, it's clearly the
way to go.

-Christopher

On Mon, Oct 24, 2011 at 5:59 PM, John Jameson jwin...@gmail.com wrote:


 Hi,
 I would like an efficient way to generate an animated grey-scale
 pixellated image. For example, to be able to generate an image say of
 100 X 100 pixels, where I can specify the size of the image on the screen
 (which thus determines the size of the pixels). One way would be to treat
 each pixel as a filled rectangle and draw them accordingly, but this could
 be quite slow since it has to do this 10,000 times for each image. Another
 way might be to just generate the image as a 100X100 image but magnified
 and thus automatically obtaining the same result. Is this possible? If
 not, is there yet another way to do this that might be more efficient?
 thanks,
 john


Re: [pygame] Surprising result of applying pygame.sndarray.make_sound() to output of numpy.fft.rfft()

2011-10-08 Thread Christopher Night
On Sat, Oct 8, 2011 at 5:04 PM, Russell Jones russell.jo...@gmail.comwrote:

 Hello all,

 I had a look in the mailing list archives for FFT and Fourier, and couldn't
 find anything that looked relevant.

 The following code has a surprising result: it outputs sound.wav twice. I'd
 expect some random sounding noise the second time. There's nothing in the
 documentation for pygame.sndarray about make_sound understanding FFTs.
 How/why does it work this way? I've tried this with a few different sounds
 in case it was a property of the one sound.

 I'm interested in playing with real number Fourier coefficients to
 manipulate and produce sounds. However, I'm not sure what pygame is doing
 exactly, which makes it harder to work on. Perhaps it's something about FFTs
 I don't understand? Can anyone explain?  I've just noticed that the second
 playback is only on one side, whilst the first is on both.  Curiouser and
 curiouser...


It's definitely not make_sound understanding FFTs

You should make sure that the FFT you're taking actually looks like you
expect it to, because I don't think it does. Under the default mixer
settings, sndarray.sound returns a 2-dimensional array, indexed first on the
sample number and second on the channel. numpy.fft.rfft takes the
1-dimensional FFT, so when you call it on this array, you're getting the FFT
of thousands of length-2 arrays. I suspect what you really want is the FFT
of two arrays that have thousands of samples. Do you get what you want when
you take the FFT of the transpose of the sound array? Check the shapes of
all the arrays you're working with to see if they're what you expect.

You're setting channels=1 in mixer.init, but this is probably not working if
you're hearing the second playback on only one side. You should make a call
to mixer.pre_init with channels=1 if you want a single audio channel.

-Christopher


Re: [pygame] Native PyGame method for automatically scaling inputs to a surface resolution?

2011-09-30 Thread Christopher Night
On Fri, Sep 30, 2011 at 5:43 AM, Mac Ryan quasipe...@gmail.com wrote:

 On Thu, 29 Sep 2011 18:18:48 -0400
 Christopher Night cosmologi...@gmail.com wrote:

  If I have a 100x100 pixel window, and I want to put a dot at a
  position (x,x), it seems to me like the dot should appear in the
  window if 0 = x  100. You're saying it should appear in the window
  if -0.5 = x  99.5. So if I request to put a point at (-0.4, -0.4),
  it will appear in the window, but if I put one at (99.6, 99.6), it
  won't. I disagree that this is the correct behavior. Intuitively, the
  point (99.6, 99.6) should be within a 100x100 canvas.

 I have a different take on this: if you have float rectangles, you are
 effectively treating **your rectangle as part of your model, not part of
 your representation** (see my previous mail). This means that a point,
 which is a dimensionless entity, shouldn't be displayed regardless of
 it's coordinates, given that your screen' pixels have a dimension (and
 therefore are infinitely larger than a point.

 I realise that this is absolutely counter-intuitive (you would be
 obliged to draw points as circles or rectangles that scales to 1 px or
 to internally convert the calls to draw pixels to calls to draw
 rectangles), but I think that is the only mathematically correct
 solution to the ambivalence.


Well pixels are just the simplest example. The ambiguity exists for all
drawing functions, not just set_at. For instance, should a horizontal line
extending from (10, 99.6) to (90, 99.6) appear on the 100x100 screen or not?
So I don't think that forbidding set_at solves it.

If you're going to say that lines are 1-dimensional and thus infinitely
smaller than pixels, and thus we're obliged to draw a thin rectangle
whenever we want a line, then (a) I probably would not use the tool if it
doesn't even support drawing lines, and (b) consider the filled, closed
polygon from (10, 99.6) to (90, 99.6) to (50, 200). Would drawing that cause
any pixels on the 100x100 screen to be lit up or not?

-Christopher


Re: [pygame] Native PyGame method for automatically scaling inputs to a surface resolution?

2011-09-30 Thread Christopher Night
On Fri, Sep 30, 2011 at 10:38 AM, Mac Ryan quasipe...@gmail.com wrote:

  If you are going to use scaled surface you *must* specify the dimension
 of what you are drawing.


There are plenty of good reasons you might need a line that's visible
regardless of the dimensions. Here's a screenshot from a game I made where
you're able to zoom in and out:

http://media.pyweek.org/dl/13/unifac13/screenshot-20110917193243.png

You can see red lines that represent lasers, and blue circles that represent
shields. Most of the graphical elements resize when you zoom in and out, but
the thickness of the lines and the circles do not, even though the endpoints
of the lines and the center and radius of the circles scale appropriately.
This is what I wanted when I made the game. I didn't want lasers that become
invisible when you zoom out. I don't care if it's unrealistic in whatever
sense. It's more important that they be visible to the player than that they
be properly scaled in thickness.

Another example off the top of my head is pathfinding. If you give orders to
a unit to move from one point to another, and you want to highlight the path
that unit is going to take, that's not an in-game object, that's a marker
for the player, and it needs to be visible to the player even if you're
zoomed out. If you draw it with lines, you want those lines to be visible.

If you're familiar with OpenGL, which fully supports the scaling mechanism
you desire, this is exactly what you get when you call glBegin(GL_LINES):
lines of 1 pixel in thickness, regardless of your scale. When you specify
glLineWidth, you specify it in *pixels*, not in unscaled units. Similarly
with GL_POINTS: you get points of 1 pixel, regardless of scale.

 if you are going to draw something that does need not to be
 scaled, it would be a better solution (at least IMO) to simply bit a
 non-scaled image on the scaled one.


That seems like a huge pain to me for something as simple as drawing a line.



  consider the filled, closed polygon from (10, 99.6) to (90, 99.6) to (50,
  200). Would drawing that cause any pixels on the 100x100 screen to be
  lit up or not?

 About (b): maybe I am missing the point as it seems obvious to me that
 it shouldn't. Unless you want to do something like smoothscale does (and
 thus using intensity as a mean to simulate fractions of a pixel) all the
 points, once scaled, are outside the surface... did I misunderstand


You're saying that all the points, once scaled, are obviously outside the
surface. That's what I'm disagreeing with: I'm saying it's not obvious, and
asking you to justify that statement. I'm making the argument that anything
within the rectangle (0,0) to (100, 100) should scale to a point inside the
surface, including (10, 99.6). You're saying that points within the
rectangle (-0.5, -0.5) to (99.5, 99.5) should scale to points inside the
surface. Thus, for instance, you think that filling the polygon going from
(10, -0.4) to (90, -0.4) to (50, -100) *should* light up some pixels,
whereas I think it obviously shouldn't, because all those points are in the
fourth quadrant.

Not that it's the most important thing in the world, but I think that OpenGL
agrees with me. Here's a program that creates a scaled surface extending
from (0,0) to (1000, 1000), with a canvas size of 100x100 pixels (so the
scale factor is 0.1). It then draws the following horizontal lines:

Red line at y = -4 (will appear if we're rounding but not if we're
truncating)
Blue line at y = 6 (will appear)
White line a y = 500 (will appear)
Red line at y = 996 (will appear if we're truncating but not if we're
rounding)
Blue line at y = 1004 (will not appear)

When I run the script, I see a blue line at top and a red line at bottom,
which is the correct behavior if we're truncating. But feel free to tell me
if there's something wrong with this experiment.

import pygame
from pygame.locals import *
from OpenGL.GL import *

pygame.init()
screen = pygame.display.set_mode((100, 100), OPENGL | DOUBLEBUF)
glOrtho(0, 1000, 1000, 0, 0, 1)

ys = [-4, 6, 500, 996, 1004]
colors = [(1,0,0), (0,0,1), (1,1,1), (1,0,0), (0,0,1)]
for y, color in zip(ys, colors):
glColor3fv(color)
glBegin(GL_LINES)
glVertex2f(100, y)
glVertex2f(900, y)
glEnd()

pygame.display.flip()
while not any(e.type in (KEYDOWN, QUIT) for e in pygame.event.get()):
pass

-Christopher


Re: [pygame] Native PyGame method for automatically scaling inputs to a surface resolution?

2011-09-29 Thread Christopher Night
On Wed, Sep 28, 2011 at 6:26 PM, Greg Ewing greg.ew...@canterbury.ac.nzwrote:

 Lenard Lindstrom wrote:

  Would you be interested in adding a feature request for a float based rect
 class in the issue tracker?


 What *would* be useful right now is if the drawing functions would
 accept tuples of floats and round (not truncate!) them to ints.


I've been thinking about this, and even though in the past I've rounded to
int when passing coordinates to drawing functions, I actually think the
correct behavior is to truncate. This makes sense if you consider the pixel
at (0,0) to actually occupy a 1x1 rectangle, extending from (0,0) to
(1,1). So the point (0.7, 0.7) should actually be considered to be within
the pixel at (0,0).

Distances, on the other hand, such as the radius of circles, should be
rounded.

Just my opinion.

-Christopher


Re: [pygame] Native PyGame method for automatically scaling inputs to a surface resolution?

2011-09-29 Thread Christopher Night
On Thu, Sep 29, 2011 at 5:50 PM, Greg Ewing greg.ew...@canterbury.ac.nzwrote:

 Christopher Night wrote:

  I actually think the correct behavior is to truncate. This makes sense if
 you consider the pixel at (0,0) to actually occupy a 1x1 rectangle,
 extending from (0,0) to (1,1). So the point (0.7, 0.7) should actually be
 considered to be within the pixel at (0,0).


 If your intention is to draw a 1x1 rectangle at some location
 on the screen, the correct approach would be to calculate the
 transformed coordinates of all four sides of the rectangle,
 round them to ints, and then fill the resulting rect.


Okay, thanks for the response. I understand that you're saying that's
correct, but I don't understand why. If I have a 100x100 pixel window, and I
want to put a dot at a position (x,x), it seems to me like the dot should
appear in the window if 0 = x  100. You're saying it should appear in the
window if -0.5 = x  99.5. So if I request to put a point at (-0.4, -0.4),
it will appear in the window, but if I put one at (99.6, 99.6), it won't. I
disagree that this is the correct behavior. Intuitively, the point (99.6,
99.6) should be within a 100x100 canvas.

I realize that it's a matter of preference, and either way would be
logically consistent, so it's just a matter of which is more intuitive and
comfortable.


 In my experience, rounding is almost always the right thing
 to do, and if it seems not to be, then you're not thinking
 about the problem the right way.


Well, that's certainly not true. Rounding is often the correct way to get
from a float to an int, but truncation is correct at times too. I can
provide examples if you want. But even so, I think they should make this
decision based on what's the right answer for this problem, not what's the
right answer in a general sense.

-Christopher


Re: [pygame] Native PyGame method for automatically scaling inputs to a surface resolution?

2011-09-27 Thread Christopher Night
On Tue, Sep 27, 2011 at 2:13 AM, Mac Ryan quasipe...@gmail.com wrote:

 On Sun, 25 Sep 2011 11:41:19 -0400
 Christopher Night cosmologi...@gmail.com wrote:

  Suppose the current transformation is (x, y) - (0.1x, 0.1y). What
  pygame Rect will the following correspond to (after all the
  coordinates are coerced to ints)?

 Could you please articulate a bit more? I'm not sure I followed. From
 your post it seems to me that you are imagining a two-way
 transformation in which you use model-scaled data to the draw
 function (draw a 150 metres radius circle) and you also get
 model-scaled data when you query the object (what is the size of the
 bounding rect for the circle? -- 300 metres).

 What I am talking about is just a one-way transformation that convert
 the input of the drawing functions. In pseudocode:

 init_surface(scale_factor=0.1)
 draw_circle(radius=150)
 get_size_bounding_rect()
... 30x30


That's how I understood it... I'm not sure what I said that made it sound
like I was thinking of a two-way transformation Let me try rephrasing my
question using your notation. Please tell me what the following would output
(where I have question marks), and tell me if you don't understand what I
mean by the pseudocode:

 init_surface(scale_factor = 0.1)
 r1 = myrect(0, 0, 108, 10)
 r1.left = 4
 fill_rect(r1)
 get_size_bounding_rect()
??? x ???

I assume it would either be 10x1 or 11x1. Do you understand my question now?

-Christopher


Re: [pygame] Native PyGame method for automatically scaling inputs to a surface resolution?

2011-09-27 Thread Christopher Night
On Tue, Sep 27, 2011 at 11:21 AM, Mac Ryan quasipe...@gmail.com wrote:

 One thing that might have further confused the discussion is that
 somewhere in an earlier mail I mentioned rects. But all I meant was
 really just the rects returned by this kind of operations. I was not
 thinking to a new class of rects with scaling included.


How can I use your system to draw a rectangle of a solid color onto a
surface? With the regular pygame system, I would use surf.fill and pass it a
Rect. If your system doesn't recognize rectangles of any sort, how can I do
this? Feel free to show me in pseudocode how I could do it.

-Christopher


Re: [pygame] Native PyGame method for automatically scaling inputs to a surface resolution?

2011-09-27 Thread Christopher Night
On Tue, Sep 27, 2011 at 3:39 PM, Mac Ryan quasipe...@gmail.com wrote:

 On Tue, 27 Sep 2011 11:28:34 -0400
 Christopher Night cosmologi...@gmail.com wrote:

  How can I use your system to draw a rectangle of a solid color onto a
  surface? With the regular pygame system, I would use surf.fill and
  pass it a Rect. If your system doesn't recognize rectangles of any
  sort, how can I do this? Feel free to show me in pseudocode how I
  could do it.

 I suppose you mean something like:

  Surface.fill(WHITE, myrect)

 is it?

 If this is the case, the rectangle would be scaled (so a rect of
 100x200 would be scaled to a rect of 10x20 assuming scale=0.1). The
 general idea would be: any argument to a surface method whose purpose
 is to indicate a measure ((x,y) tuples, explicit width/height or tuples)
 would be scaled. Any other parameter whose purpose is not defining
 coordinates (colours, flags, surfaces...) wouldn't.


Is myrect supposed to be a regular pygame.Rect? One big problem with that is
that pygame.Rect properties are coerced to integers. This makes sense for a
rectangle that describes a set of pixels, not so much for a rectangle that's
supposed to describe a region in world coordinates.

Either way, that's fine, and not very suprising. That's exactly what I had
in mind. So I really don't see why you weren't able to answer my original
question. Let me try asking it one more time.

You say that a 100x200 rect would be scaled to 10x20 pixels. Yes, obviously,
this makes sense. What would a 104x200 rect be scaled to? 10x20 pixels? Or
11x20 pixels? Or would it depend on the position of the rect? (Remember that
in addition to height and width, rectangles also have positions, ie left and
top. You can't just say draw a 10x20 rectangle, you also have to say where
to draw it. This is relevant to the question, so try to keep it in mind.)

-Christopher


Re: [pygame] Native PyGame method for automatically scaling inputs to a surface resolution?

2011-09-25 Thread Christopher Night
On Sun, Sep 25, 2011 at 7:31 AM, Mac Ryan quasipe...@gmail.com wrote:

 On Sun, 25 Sep 2011 12:36:50 +0200
 René Dudfield ren...@gmail.com wrote:

  Maybe it would be possible to implement easily in C, without too much
  code, but maybe not.  I'm not interested in it myself, since I think
  it's not too hard to layer on top - so I won't spend any effort
  implementing it. However, if you want to submit a patch that doesn't
  make the code super ugly, and doesn't cost too much performance we
  could add it.

 I can have a go at it - without guarantees as I only occasionally code
 in C - but that won't be immediately anyhow, most likely not before
 15/10. If you have any further suggestion before I try to make my way
 through the code, I'll be happy to listen.

 I have several questions that I would want addressed before I used your
tool extensively. Should I post them to this thread or what? There's a
number having to do with tricky edge cases of the transformation. When I
write my own wrappers I know what to expect, so I would need it well
documented for yours. For example

Suppose the current transformation is (x, y) - (0.1x, 0.1y). What pygame
Rect will the following correspond to (after all the coordinates are coerced
to ints)?

rect1 = rect2 = myRect(0, 0, 108, 10)
rect1.left = 4
rect2.right = 112

Should the pygame rects produced by rect1 and rect2 be the same? Either
answer is surprising, I think. (That question assumes you're rounding down
to coerce to ints. If instead you're rounding to the nearest, consider this
example)

rect1 = rect2 = myRect(0, 0, 104, 10)
rect1.left = 4
rect2.right = 108

Anyway, that's just one question, I'd just want to make sure you'd thought
it through.

-Christopher


Re: [pygame] Native PyGame method for automatically scaling inputs to a surface resolution?

2011-09-23 Thread Christopher Night
Yeah short answer no. However, I think the answers you've gotten from
StackOverflow have not been terribly helpful. They seem to suggest don't do
scaling in pygame. This is silly, I do scaling in pygame all the time.
There's no reason you'd need to work in screen coordinates.

I use wrappers. Let me point out there's a total of 9 functions in
pygame.draw. You seem to be going to a lot of effort to avoid writing 9
one-line functions. (And I usually only ever use about 3 or 4 in any one
application.) Writing the wrappers is the best way, and I don't think you
should have dismissed it so quickly.

Since this is a very common problem, I wonder if there is an established
pattern that elegantly solves this problem that I failed to find.


I don't consider the wrappers that inelegant. However, you could also do it
pretty easily with a function decorator if that's preferable for you

I could simply decorate the existing middleware functions, but the problem
is that those functions also work with the same parameters being list or
Vector2D too, and the decorator would have no way to know which lists need
to be scaled (the radius for example) and which not (the RGB values).


With one example, everything numerical should be scaled except for RGB
values. Since these are always the second argument to the function, it
should be trivial to accept the first two arguments (surf and color) and
scale everything else as needed. The only other exception is the angles in
pygame.draw.arc. So you would have to write one special case, assuming you
actually need pygame.draw.arc.

I hope you find a solution that satisfies you. It's not that there aren't
plenty of solutions! :)

-Christopher

On Fri, Sep 23, 2011 at 4:29 AM, Mac Ryan quasipe...@gmail.com wrote:

 Hello,

back July, I posted a question on StackOverflow titled that so
 far still did not get any answer. So - although I believe the answer is
 quite simply NO - I thought to repost it here:

 

 In my program (which uses pygame to draw objects on the video) I have
 two representation of my world:

 - A physical one that I use to make all the calculations involved in the
  simulation and in which objects are located on a 1000x1000 metres
  surface.
 - A visual one which I use to draw on the screen, in which my objects
  are located in a window measuring 100x100 pixels.

 What I want to achieve is to be able to pass to my pygame drawing
 functions (which normally accept inputs in pixels) my
 physical/real-word coordinates. In other words, I would like to be able
 to say:

 Draw a 20m radius circle at coordinates (200m, 500m)
 using the precise pygame syntax:

 pygame.draw.circle(surface, (255,255,255), (200,500), 20)
 and get my circle of 2px radius at centred on pixels (20,50).

 

 If you are on SO and would like to answer there [too], I'll be happy to
 dispense upvotes! ;) http://stackoverflow.com/q/6807459/146792



Re: [pygame] Native PyGame method for automatically scaling inputs to a surface resolution?

2011-09-23 Thread Christopher Night
On Fri, Sep 23, 2011 at 7:04 PM, Greg Ewing greg.ew...@canterbury.ac.nzwrote:

 Christopher Night wrote:

  I use wrappers. Let me point out there's a total of 9 functions in
 pygame.draw. You seem to be going to a lot of effort to avoid writing 9
 one-line functions.


 Don't forget that function calls are expensive in Python, as
 is doing piecemeal arithmetic.

 Most other graphics systems these days provide a facility for
 applying a transformation to coordinates before drawing, and
 I don't think it's unreasonable to suggest that PyGame should
 do the same. Having it done for you in C would be more efficient
 than doing it in Python.


While that is roughly true, it's a very, very general statement to the point
where I would say that avoiding function calls on principle is premature
optimization. Keep in mind that the operation you're wrapping - a draw call
- is expensive in the first place. Anyway, a quick profile suggests that for
a small circle you can potentially gain a 7% speedup by avoiding this
function call, and a 14% speedup avoiding both the function and the
arithmetic:

 import timeit
 setup = import pygame
... pygame.init()
... s = pygame.display.set_mode((100, 100))
... def myCirc(surf, color, (x, y), r, width=0):
... pygame.draw.circle(surf, color, (x/10, y/10), r/10, width/10)
 timeit.timeit(myCirc(s, (255,255,255), (500, 500), 400), setup,
number=10)
4.9027900695800781
 pygame.quit()
 timeit.timeit(pygame.draw.circle(s, (255,255,255), (500/10, 500/10),
400/10), setup, number=10)
4.546515941619873
 pygame.quit()
 timeit.timeit(pygame.draw.circle(s, (255,255,255), (50, 50), 40),
setup, number=10)
4.1960330009460449
 pygame.quit()

You can decide whether that's worth it for you to avoid this function call.
For me, if my game is slow enough that I have to avoid function calls to get
reasonable performance, it means I'm doing something else wrong. :) If
performance is the goal here, I still think it's a large amount of effort
for a relatively modest gain.

For what it's worth, I would also welcome native-pygame wrappers that apply
a linear transformation. But whether pygame *should* have them wasn't the
question, as I understood it. And I can scrape by without them.

-Christopher


Re: [pygame] Memory leak in surfarray.pixels3d?

2011-09-20 Thread Christopher Night
Thanks you, Lenard! And thanks for looking into this, everyone!

-Christopher

On Wed, Sep 21, 2011 at 12:19 AM, Lenard Lindstrom le...@telus.net wrote:

 Fixed in changeset 7866ddf0ec0d.

 Lenard Lindstrom



 On Sep 20, 2011, *Lenard Lindstrom* le...@telus.net wrote:

 Hello,

 There is definitely a leak. I know the source and will commit a fix
 shortly.

 Lenard Lindstrom

 On Sep 19, 2011, *René Dudfield* ren...@gmail.com wrote:

 Hi,

 seems like it is in the development version of pygame.  It leaks on OSX too
 with the latest pygame from hg.

 There is also a leak with pixels2d.




[pygame] Memory leak in surfarray.pixels3d?

2011-09-19 Thread Christopher Night
Hi, one of the players of my pyweek game got a memory leak that seems to
depend on the pygame version. We've reduced it to this script:

import pygame
pygame.init()
x = pygame.Surface((1000, 1000), pygame.SRCALPHA)
while True:
a = pygame.surfarray.pixels3d(x)

When I run it on Ubuntu with python 2.6.5 and pygame 1.9.1release, memory
stays fairly constant. When my player runs the script on Windows with python
2.7 and pygame 1.9.2pre, memory usage climbs by about 30MB per second. I'm
trying to figure out whether anyone else can reproduce the leak, what's the
cause, and whether I can fix it or work around it.

Thanks!
-Christopher


Re: [pygame] car game mechanics

2011-09-01 Thread Christopher Night
On Tue, Aug 30, 2011 at 10:33 AM, Joe Ranalli jrana...@gmail.com wrote:

 The article that Nathan linked does provide a method for more complex
 treatment of a car.  Instead of treating the car as simply rotating about
 its center, they're accounting for the fact that a real car steers using its
 front wheels while the back wheels are fixed.  Even implementing that
 approach in python using Nathans current programming method would cause
 unrealistic behavior due to similar rounding and transformation size errors
 .


I read that article and I think I found a problem with the algorithm it
presents. If you try to implement that algorithm and it gives you bad
results, check out the comment that I left there.

-Christopher


Re: [pygame] car game mechanics

2011-08-30 Thread Christopher Night
Three things you can do to make this more realistic.

1. use self.angle as the argument to pygame.transform.rotate instead of
a_deg, as Joe suggested.

2. use separate variables to keep the car's position. Don't store it in
self.rect.center. This is because rect positions are coerced to ints, so if
your car should be moving 0.5 pixels per frame to the right, this will be
rounded down to 0.

3. update self.rect after you transform. This is because the rotated image
doesn't have the same size as the original image, so its center will be
offset. Also, your second argument to screen.blit should be self.rect, not
self.rect.center. (If you pass it a position like self.rect.center, it will
use that as the upper-left position of the blitted rect.

I modified your file to have this in your init method:

self.x, self.y = SCREEN_SIZE_X/2, SCREEN_SIZE_Y -
self.rect.height * 2

this in your update:

#rotate the car
self.sprite = pygame.transform.rotate(self.original,
self.angle * -1)
self.rect = self.sprite.get_rect(center = self.rect.center)

#move the car
self.x += speedx
self.y += speedy

self.rect = self.sprite.get_rect()
self.rect.center = self.x, self.y

and this in your draw:

screen.blit(self.sprite, self.rect)

And it looked much better to me. Let me know what you think.

-Christopher

On Tue, Aug 30, 2011 at 5:46 AM, Nathan BIAGINI nathan.o...@gmail.comwrote:

 Hi,

 i'm trying to write a car game and i have decided to start by the movement
 part. I calculate the X and Y components of the car and update his position
 by increasing the current one with the two new components. The two
 components depend of the orientation of the car, managed by the right and
 left arrow :


 speedx = math.sin(self.angle * (math.pi/180)) * SPEED
 speedy = math.cos(self.angle * (math.pi/180)) * SPEED * -1


 Where SPEED is a constant and self.angle a int representing the
 orientation. I don't know if this is the best way because, the car speed
 depends of his orientation. Increasing the self.angle value will increase
 the components, this is not suitable for a car game i think.

 I have another problem with the car movement. Each time the orientation
 change, i would like to rotate the car in the right direction. I thought to
 do something like that :

 a_rad = math.asin(speedx/SPEED)
 a_deg = math.degrees(a_rad)

 self.sprite = pygame.transform.rotate(self.original, a_deg * -1)
 self.rect = self.sprite.get_rect(center = self.rect.center)


 It does not work properly, this way, my car can't rotate over 90° because
 of the speedx values.

 Here is my code :

 http://pastebin.com/VJgQRtYq

 and the sprite i use for the car is joined.

 Thanks for reading me.



Re: [pygame] car game mechanics

2011-08-30 Thread Christopher Night
Oops. I realize I missed the line where you are updating self.rect after
calling transform. I shouldn't have put it in there again. The bit I posted
from the update method should only have read:

#move the car
self.x += speedx
self.y += speedy

#rotate the car
self.sprite = pygame.transform.rotate(self.original,
self.angle * -1)
self.rect = self.sprite.get_rect(center = (self.x, self.y))

Sorry for the confusion!

-Christopher

On Tue, Aug 30, 2011 at 10:22 AM, Christopher Night
cosmologi...@gmail.comwrote:

 Three things you can do to make this more realistic.

 1. use self.angle as the argument to pygame.transform.rotate instead of
 a_deg, as Joe suggested.

 2. use separate variables to keep the car's position. Don't store it in
 self.rect.center. This is because rect positions are coerced to ints, so if
 your car should be moving 0.5 pixels per frame to the right, this will be
 rounded down to 0.

 3. update self.rect after you transform. This is because the rotated image
 doesn't have the same size as the original image, so its center will be
 offset. Also, your second argument to screen.blit should be self.rect, not
 self.rect.center. (If you pass it a position like self.rect.center, it will
 use that as the upper-left position of the blitted rect.

 I modified your file to have this in your init method:

 self.x, self.y = SCREEN_SIZE_X/2, SCREEN_SIZE_Y -
 self.rect.height * 2

 this in your update:

 #rotate the car
 self.sprite = pygame.transform.rotate(self.original,
 self.angle * -1)
 self.rect = self.sprite.get_rect(center = self.rect.center)


 #move the car
 self.x += speedx
 self.y += speedy

 self.rect = self.sprite.get_rect()
 self.rect.center = self.x, self.y

 and this in your draw:

 screen.blit(self.sprite, self.rect)

 And it looked much better to me. Let me know what you think.

 -Christopher


 On Tue, Aug 30, 2011 at 5:46 AM, Nathan BIAGINI nathan.o...@gmail.comwrote:

 Hi,

 i'm trying to write a car game and i have decided to start by the movement
 part. I calculate the X and Y components of the car and update his position
 by increasing the current one with the two new components. The two
 components depend of the orientation of the car, managed by the right and
 left arrow :


 speedx = math.sin(self.angle * (math.pi/180)) * SPEED
 speedy = math.cos(self.angle * (math.pi/180)) * SPEED * -1


 Where SPEED is a constant and self.angle a int representing the
 orientation. I don't know if this is the best way because, the car speed
 depends of his orientation. Increasing the self.angle value will increase
 the components, this is not suitable for a car game i think.

 I have another problem with the car movement. Each time the orientation
 change, i would like to rotate the car in the right direction. I thought to
 do something like that :

 a_rad = math.asin(speedx/SPEED)
 a_deg = math.degrees(a_rad)

 self.sprite = pygame.transform.rotate(self.original, a_deg * -1)
 self.rect = self.sprite.get_rect(center = self.rect.center)


 It does not work properly, this way, my car can't rotate over 90° because
 of the speedx values.

 Here is my code :

 http://pastebin.com/VJgQRtYq

 and the sprite i use for the car is joined.

 Thanks for reading me.





Re: [pygame] very slow pygame.init() under Snow Leopard

2011-08-26 Thread Christopher Night
On Fri, Aug 26, 2011 at 2:28 PM, Lenard Lindstrom le...@telus.net wrote:

 The pygame.init('display', ...) is redundant. The exclude list would be
 useful for omitting an unused, costly, module. But in general I agree that
 calling init() only on those modules that are used is good programming
 practice. The Pygame examples should even be updated to reflect this. Using
 pygame.init() is much like from pygame import *.


I see in the documentation that someone left a comment saying that not
calling pygame.init prevents you from using pygame.time.get_ticks. Is there
a workaround for people who want to use this function but don't want to call
pygame.init? I'm also curious how it might work with lazy imports (which
sounds like a great idea).

-Christopher


Re: [pygame] FULLSCREEN or ~FULLSCREEN?

2011-07-04 Thread Christopher Night
Nope, that has not been my experience at all! I've always found that
fullscreen makes a big difference. I just tried one of my old pygame+GL test
scripts that was written to test the effect of varying the resolution.
Here's what it gave me for fullscreen modes and windowed modes:

FULLSCREEN:
1920x1080: 17.3fps
1280x720: 55.6fps
960x540: 153.7fps

~FULLSCREEN:
1920x1080: 17.5fps
1280x720: 36.2fps
960x540: 58.7fps

As you can see, the smaller the resolution, the more performance fullscreen
gives you. In my case if you're running at the maximum possible resolution,
fullscreen makes no difference, but only then.

Hope that helps!
Christopher

On Mon, Jul 4, 2011 at 3:21 PM, James Mazer james.ma...@yale.edu wrote:

 I've always been under the impression pygame+GL performance was
 substantially better when running with the FULLSCREEN flag
 set. However, recently, I started playing around with NOFRAME windows
 fit to the monitor size and found no big performance hit.

 Is this generally the experience of most people?  Is it generally safe
 with modern video cards to assume that windowed  fullscreen modes
 give you similar to performance levels for pygame+GL? This is for an
 app that uses mostly GL on top of pygame and runs with
 __GL_SYNC_TO_VBLANK set.

 Under linux, fullscreen debugging can be dangerous (it's too easy for
 a bug to lock up the machine requiring a reboot/xserver-restart), so it
 would be nice to not use it -- my app has a scripting language, so
 even with a bug-free production version a user can lock up the
 screen, so just using windowed mode for testing's not sufficient..

 Thanks,
 /jamie

 --
 James Mazer
 Department of Neurobiology
 Yale School of Medicine
 phone: 203-737-5853
 fax: 203-785-5263



Re: [SPAM: 3.000] [pygame] thinking of changing gfxdraw module...

2011-06-01 Thread Christopher Night
On Wed, Jun 1, 2011 at 2:47 AM, René Dudfield ren...@gmail.com wrote:

 On Tue, May 31, 2011 at 10:02 PM, Greg Ewing 
 greg.ew...@canterbury.ac.nzwrote:

 René Dudfield wrote:

  I'm thinking of removing the single calls, and only having multiple ones
 available - to force people into using the more efficient methods.


 -1 if this means I'd have to build a list if I just want
 to draw one item, because that introduces inefficiencies
 of its own and makes the code less clear.


 I understand the concerns about readability, and speed impacts.

 However, I'm not sure it adds much clutter visually for the single use
 case.  Just add a couple of extra brackets.

 Also, the most common use case is drawing multiple items.  I can't think of
 one real application where I've only drawn one element off the top of my
 head.


I've had applications where I want to draw a single line, and many where
I've wanted to draw a single circle, arc, or polygon.

I don't expect that performance is a big issue, but I think it makes sense
to have a version for just drawing a single item. Every graphical API that
I'm familiar with allows you to draw a single item without putting it in a
container. Is it common not to? Should pygame.draw.line be deprecated as
well?

-Christopher


Re: [pygame] Resolution for a 2d game

2011-05-16 Thread Christopher Night
On Mon, May 16, 2011 at 3:00 AM, Daniel Pope ma...@mauveweb.co.uk wrote:

 Please don't force a fullscreen resolution. It doesn't restore properly on
 dual-head setups.

 This was discussed here:

 http://www.pyweek.org/d/3953/


I asked in that thread but I never heard an answer: is there no way to fix
this? It would be nice to be able to give all your users the option of
fullscreen.

-Christopher


[pygame] OBJ loader using VBOs

2010-12-04 Thread Christopher Night
Hi, I'm working on a standalone OBJ loader based on the well-known one on
the pygame wiki:
http://www.pygame.org/wiki/OBJFileLoader

My goal is to speed up load times by making the model objects picklable, so
the OBJ file doesn't have to be read every time you start up. Here's my
current version:
http://christophernight.net/stuff/fasterobj-0.tgz

It still needs some cleaning up, but it's got almost all the functionality I
wanted. In addition to making things picklable, it has a small optimization
by combining triangles and quads when possible to reduce the number of GL
calls.

There are three classes: OBJ (using fixed function), OBJ_array (using vertex
arrays), and OBJ_vbo (using vertex buffer objects). Additionally, any of
these can be used with or without a display list. Here's the results of my
test on some model I had lying around:

   type  list? parse save load   render
1. fixed False  146   13   140.03fps
2. fixed  True  124   10  950  117.80fps
3. array False  179891.26fps
4. array  True  1747   30  121.08fps
5. vbo   False  14378   16.06fps
6. vboTrue  1428   12  112.98fps

#2 is the method in the original OBJ loader. The times listed under parse,
save, and load are times in milliseconds to read from the OBJ file and do
some preprocessing, pickle to a file, and unpickle from a file. The load
step also includes generating the display list, if necessary. Obviously
methods #1 and #3 render far too slow; they're just there for comparison.

So anyway, it looks pretty good. I think that #4 or #6 would do fine for my
purposes. However, I know that people don't like to put vertex arrays and
VBOs inside display lists, so I want to know if there's some problem with
this method. I understand that putting a VBO in a display list defeats the
whole purpose of having a VBO, since you can't update it, but I imagine
you're probably not going to be doing that with OBJ models anyway. Also,
when I asked about this a few months ago, someone said that method #5 should
outperform methods #1-4, and that doesn't seem to be the case. So I might be
misusing the VBOs.

Any other comments welcome too! If you have any OBJ files you want me to
test, just let me know.

-Christopher


Re: [pygame] OBJ loader using VBOs

2010-12-04 Thread Christopher Night
On Sat, Dec 4, 2010 at 4:05 PM, Ian Mallett geometr...@gmail.com wrote:


 On Sat, Dec 4, 2010 at 1:21 PM, Christopher Night 
 cosmologi...@gmail.comwrote:

 Hi, I'm working on a standalone OBJ loader based on the well-known one on
 the pygame wiki:
 http://www.pygame.org/wiki/OBJFileLoader

 My goal is to speed up load times by making the model objects picklable,
 so the OBJ file doesn't have to be read every time you start up. Here's my
 current version:
 http://christophernight.net/stuff/fasterobj-0.tgz

 It still needs some cleaning up, but it's got almost all the functionality
 I wanted. In addition to making things picklable, it has a small
 optimization by combining triangles and quads when possible to reduce the
 number of GL calls.

 There are three classes: OBJ (using fixed function), OBJ_array (using
 vertex arrays), and OBJ_vbo (using vertex buffer objects). Additionally, any
 of these can be used with or without a display list. Here's the results of
 my test on some model I had lying around:

type  list? parse save load   render
 1. fixed False  146   13   140.03fps
 2. fixed  True  124   10  950  117.80fps
 3. array False  179891.26fps
 4. array  True  1747   30  121.08fps
 5. vbo   False  14378   16.06fps
 6. vboTrue  1428   12  112.98fps

 #2 is the method in the original OBJ loader. The times listed under parse,
 save, and load are times in milliseconds to read from the OBJ file and do
 some preprocessing, pickle to a file, and unpickle from a file. The load
 step also includes generating the display list, if necessary.



 I completely would have expected the results in 1-4.

 However, I'm quite surprised at the vbo method 5.  It should run in speed
 between 2 and 4.  I also would have expected 4 and 6 to be much closer.

 How many VBOs are you using?  If you switch buffer bindings a lot for each
 draw (like your object has 10 different parts, each with a vertex, normal,
 and texcoord VBO) then you *might* get results like that . . .


Awesome, thanks so much for taking a look! I'm using 3 VBOs, one each for
vertex, normal, and texcoord. This is the entire rendering code for OBJ_vbo:

glEnable(GL_TEXTURE_2D)
glFrontFace(GL_CCW)
self.vbo_v.bind()
glVertexPointerf(self.vbo_v)
self.vbo_n.bind()
glNormalPointerf(self.vbo_n)
self.vbo_t.bind()
glTexCoordPointerf(self.vbo_t)
glEnableClientState(GL_VERTEX_ARRAY)
texon, normon = None, None
for material, mindices in self.indices:
self.mtl.bind(material)
 for nvs, dotex, donorm, ioffset, isize in mindices:
 if donorm != normon:
 normon = donorm
 (glEnableClientState if donorm else glDisableClientState)(GL_NORMAL_ARRAY)
 if dotex != texon:
 texon = dotex
 (glEnableClientState if dotex else
glDisableClientState)(GL_TEXTURE_COORD_ARRAY)
 shape = [GL_TRIANGLES, GL_QUADS, GL_POLYGON][nvs-3]
 glDrawArrays(shape, ioffset, isize)
glDisable(GL_TEXTURE_2D)

For this model, glEnableClientState gets called once for vertices, normals,
and texcoords. There are 5 materials, each with one glBindTexture and two
glDrawArrays (one for triangles, one for quads). So the total calls per
render is:

2 x glEnable/glDisable
1 x glFrontFace
3 x vbo.bind
3 x glEnableClientState
10 x glDrawArrays
5 x glBindTexture
4 x glColor

And I'm rendering 40 sprites, so I'm doing this 40 times per frame. I'm
assuming that in a real application, each model would have its own separate
VBOs. Is that what I'm doing wrong? Or is there something else?

The reason it takes so long to load on 2 is generating the display list.
This method was taken from the objloader on the wiki, and it involves 1646
glVertex3f calls, one for each vertex in the model, and similarly with
glNormal and glTexCoords.

Thanks again!

-Christopher


Re: [pygame] fixed the image resizing on website, and added rel=nofollow to all external links

2010-11-28 Thread Christopher Night
On Sun, Nov 28, 2010 at 9:12 AM, René Dudfield ren...@gmail.com wrote:

 I fixed the image resizing on website,


Thank you! I had no idea why my entry's image wasn't showing up!

-Christopher


[pygame] pygame2exe

2010-10-23 Thread Christopher Night
I'm completely unfamiliar with Windows, and I'm finding it so much harder to
use than Linux. I feel like a complete idiot trying to compile something to
exe. I did manage to get a Hello World script compiled okay, but I can't get
a simple test pygame script to compile. I used the pygame2exe script here:

http://www.pygame.org/wiki/Pygame2exe

I put it in a directory with my test script test.py, changed the stuff in
BuildExe.__init__, and ran it in IDLE. It seemed to work for a while, but
eventually died with this traceback:

*** finding dlls needed ***
*** create binaries ***
*** byte compile python files ***
writing byte-compilation script
'c:\users\christ~1\appdata\local\temp\tmplkizod.py'
C:\Python26\pythonw.exe -OO
c:\users\christ~1\appdata\local\temp\tmplkizod.py

Traceback (most recent call last):
  File C:/Users/christopher/Desktop/pygame-test/pygame2exe.py, line 155,
in module
BuildExe().run() #Run generation
  File C:/Users/christopher/Desktop/pygame-test/pygame2exe.py, line 146,
in run
dist_dir = self.dist_dir
  File C:\Python26\lib\distutils\core.py, line 169, in setup
raise SystemExit, error:  + str(msg)
SystemExit: error: command 'C:\Python26\pythonw.exe' failed with exit status
1

Am I even on the right track? Is py2exe the best tool to use for compiling
pygame-based programs, and if so, is this the right script to use? If so,
what's with the error I'm getting? I'm hopeless debugging anything in
Windows. When I try running that line (C:\Python26\pythonw.exe -OO
c:\users\christ~1\appdata\local\temp\tmplkizod.py), it just exits without
any output, leaving me with no clue what the problem is. Any advice at all
would be much appreciated.

Thanks!
Christopher


Re: [pygame] Faster OBJ loader

2010-09-28 Thread Christopher Night
On Tue, Sep 28, 2010 at 2:05 PM, Ian Mallett geometr...@gmail.com wrote:

 On Mon, Sep 27, 2010 at 8:05 PM, Christopher Night cosmologi...@gmail.com
  wrote:

 I was able to improve the rendering performance significantly using vertex
 arrays in the test I did a few months ago. I was still using a display list
 as well, but I greatly reduced the number of GL commands within the display
 list. The trick was to triangulate all the faces, and render all the faces
 for a given material using a single call to glDrawArrays(GL_TRIANGLES...). I
 realize this is hardware-dependent, but the speedup was dramatic on 2 out of
 2 systems that I've tried. Maybe it's not the vertex arrays that matter, and
 triangulating all the faces and using a single call to glBegin(GL_TRIANGLES)
 would yield the same speedup. Either way, it's worth looking into I
 think

 You must not be using the calls as you think you are, then.  Graphics cards
 have a graphics bus that handles data transfer to and from the card.
 Unfortunately, this graphics bus is slower than either the CPU or the GPU
 themselves.

 Fixed function (glVertex3f(...), glNormal3f(...), etc.) sends the data to
 the card on each call.  So, if you have 900 such calls, you send 900 state
 changes to OpenGL across the graphics bus each time the data is drawn.  This
 can get slow.

 Vertex arrays work similarly, except the data is stored as an array, and
 the equivalent of the 900 fixed function calls are sent across the graphics
 bus each frame.  Although this batched approach is faster than fixed
 function, all the data is still transferred to the card each time the data
 is drawn.

 Display lists work by caching operations on the graphics card.  You can
 specify nearly anything inside a display list, including fixed function
 (and I think) vertex arrays.  To use display lists, you wrap the drawing
 code in glGenLists()/glNewList() and glEndList() calls.  The code inside,
 after being transferred to the GPU, is stored for later use.  Later, you can
 call glCallLists(), with the appropriate list argument.  The list's NUMBER
 is transferred to the GPU, and the relevant set of cached operations is
 executed.  The practical upshot of all this is that each time you draw the
 object, you pass a single number to the graphics card, and the appropriate
 cached operations are executed.  This is the way the Wiki .obj loader works.


Excellent, thank you very much for the explanation. You're absolutely right
that I'm likely to not be using the calls like I think I am. :-)

I understand now that no matter what's in the display list, only a single
number is passed to the graphics card, so there can't be any optimization on
the outside. However, wouldn't it be possible for some display lists to
execute faster within the graphics card than others?

Attached below is a script that demonstrates what I'm talking about. It
should render a torus repeatedly for 60 seconds. First without vertex arrays
(the way the objloader on the wiki does it), and second with vertex arrays.
For me the output is:

Without arrays: 58.0fps
With arrays: 140.0fps

It takes several minutes to run, because the torus has a huge number of
faces it has to generate. I had to do that to get the framerate down.
Anyway, this is the kind of test that suggests to me that vertex arrays
might help. Do you see something wrong with it?

As for VBOs, I know I should learn them. If I can figure them out, and I can
get the same performance from them, that would be preferable. However,
that's just for the sake of using non-deprecated techniques: for an OBJ
loader, there wouldn't seem to be much need for dynamic data.

-Christopher


import pygame
from pygame.locals import *
from math import sin, cos, pi
from OpenGL.GL import *
from OpenGL.GLU import *

tmax = 60.  # Time to run each test for

# Generate the torus faces
nx, ny = 600, 400
xcos = [cos(x * 2 * pi / nx) for x in range(nx+1)]
xsin = [sin(x * 2 * pi / nx) for x in range(nx+1)]
ycos = [cos(y * 2 * pi / ny) for y in range(ny+1)]
ysin = [sin(y * 2 * pi / ny) for y in range(ny+1)]

def coords(x, y):
return xcos[x] * (2 + ycos[y]), ysin[y], xsin[x] * (2 + ycos[y])
def normals(x, y):
return xcos[x] * ycos[y], ysin[y], xsin[x] * ycos[y]
faces, vlist, nlist = [], [], []
for x in range(nx):
for y in range(ny):
vs = (coords(x,y), coords(x+1,y), coords(x+1,y+1), coords(x,y+1))
ns = (normals(x,y), normals(x+1,y), normals(x+1,y+1),
normals(x,y+1))
faces.append((vs, ns))
for v in vs: vlist.extend(v)
for n in ns: nlist.extend(n)

for usearray in (False, True):

# Initialize pygame and OpenGL
pygame.init()
pygame.display.set_mode((640, 480), DOUBLEBUF | OPENGL)

glLightfv(GL_LIGHT0, GL_POSITION,  (10,10,10, 0.0))
glLightfv(GL_LIGHT0, GL_DIFFUSE, (0.5, 0.5, 0.5, 1.0))
glEnable(GL_LIGHT0)
glEnable(GL_LIGHTING)
glEnable(GL_COLOR_MATERIAL)
glEnable(GL_DEPTH_TEST)
glEnableClientState(GL_VERTEX_ARRAY

Re: [pygame] Faster OBJ loader

2010-09-28 Thread Christopher Night
On Tue, Sep 28, 2010 at 3:05 PM, Devon Scott-Tunkin 
devon.scotttun...@gmail.com wrote:

 It should be noted that display lists are deprecated (but for all intents
 and purposes still there) in the anti-fixed function opengl 3.1+ (and
 perhaps completely unavailable in open gl es 2.0?). So learning vbos is
 probably a good idea...


So, dumb question are VBOs actually implemented in PyOpenGL? I've
started looking into it, and I can't find any working examples of anyone
using a VBO in python. (I've found one that looks okay, but it must be for a
previous version, because the function signatures don't even match up for
me.) I've tried to translate examples from C with no luck. As far as I can
tell, here's how you would set one up (vlist is a numpy array):

gl_buffer = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER_ARB, gl_buffer)
glBufferData(GL_ARRAY_BUFFER_ARB, vlist, GL_STATIC_DRAW)
glVertexPointerd(0)

The last line gives me an error:

TypeError: ('cannot be converted to pointer', bound method
PointerType.voidDataPointer of class
'OpenGL.arrays.arraydatatype.GLdoubleArray')

So... yeah. Any working examples?

Thanks,
Christopher


Re: [pygame] moving a filled circle from top to bottom

2010-09-27 Thread Christopher Night
It's extremely minor. Change the center of your circle from (320, 0) to (25,
25). The coordinates are with respect to self.image, not to screen.

-Christopher

On Mon, Sep 27, 2010 at 4:32 PM, kevin hayes kevino...@gmail.com wrote:

 Hi,
 This is my attempt at sending a circle(Sprite) vertically from the
 top of the screen to the bottom.  Can someone
 tell me how to change the code so it works?  Currently it is just creating
 a white screen. Thanks in advance. Kevin

 Attempt at moving a circle(Sprite) from top(of screen) to bottom

 import pygame
 pygame.init()

 screen = pygame.display.set_mode((640, 480))

 class Circle(pygame.sprite.Sprite):
 def __init__(self):
 pygame.sprite.Sprite.__init__(self)
 self.image = pygame.Surface((50, 50))
 self.image.fill((255, 255, 255))
  #fill with white to hide square???
 pygame.draw.circle(self.image, (0, 0, 255), (320, 0), 25)
 self.rect = self.image.get_rect()
 self.rect.centerx = 320
 self.rect.centery = 0

 def update(self):
 self.rect.centery += 5
 if self.rect.top  screen.get_height():
 self.rect.bottom = 0


 def main():
 pygame.display.set_caption(Verticle Circle Sprite)

 background = pygame.Surface(screen.get_size())
 background.fill((255, 255, 255))
 screen.blit(background, (0, 0))

 circle = Circle()
 allSprites = pygame.sprite.Group(circle)

 clock = pygame.time.Clock()
 keepGoing = True
 while keepGoing:
 clock.tick(30)
 for event in pygame.event.get():
 if event.type == pygame.QUIT:
 keepGoing == False

 allSprites.clear(screen, background)
 allSprites.update()
 allSprites.draw(screen)

 pygame.display.flip()

 if __name__ == __main__:
 main()

 pygame.quit()




[pygame] Faster OBJ loader

2010-09-27 Thread Christopher Night
Hi, I'm looking into modifying the well-known objloader.py on the pygame
wiki:

http://www.pygame.org/wiki/OBJFileLoader

I would modify it to use vertex arrays. I think this could improve
efficiency of loading and rendering the models, based on some tests I did a
few months ago on the pyweek message board:

http://www.pyweek.org/d/3066/

I wanted to ask if this work has already been done by anyone, or if there is
a different existing OBJ loader that could be used as a starting point. I
searched this mailing list, and it looks to me like this is the current best
OBJ loader for pygame there is.

Thanks,
Christopher


Re: [pygame] Faster OBJ loader

2010-09-27 Thread Christopher Night
On Mon, Sep 27, 2010 at 7:52 PM, Ian Mallett geometr...@gmail.com wrote:


 On Mon, Sep 27, 2010 at 4:49 PM, Christopher Night cosmologi...@gmail.com
  wrote:

 Hi, I'm looking into modifying the well-known objloader.py on the pygame
 wiki:

 http://www.pygame.org/wiki/OBJFileLoader

 I would modify it to use vertex arrays. I think this could improve
 efficiency of loading and rendering the models, based on some tests I did a
 few months ago on the pyweek message board:

 Vertex arrays would only be marginally faster than fixed functionality for
 *rendering*.  This version loads into display lists, which are about as
 fast as possible for that.  You won't be able to get better rendering
 performance.

 Thanks for the response! Assuming that rendering means what I think it
means (actually drawing the thing on the screen, right?), I was able to
improve the rendering performance significantly using vertex arrays in the
test I did a few months ago. I was still using a display list as well, but I
greatly reduced the number of GL commands within the display list. The trick
was to triangulate all the faces, and render all the faces for a given
material using a single call to glDrawArrays(GL_TRIANGLES...). I realize
this is hardware-dependent, but the speedup was dramatic on 2 out of 2
systems that I've tried. Maybe it's not the vertex arrays that matter, and
triangulating all the faces and using a single call to glBegin(GL_TRIANGLES)
would yield the same speedup. Either way, it's worth looking into I
think

Improved loading performance comes from the fact that these arrays can be
pickled, so you don't have to read them directly from the OBJ file after the
first time. You only need to distribute the pickled OBJ/MTL files with your
actual game. Psyco or C might be just as good, but this solution was pretty
simple, and reduces the (subsequent) load times to almost nothing.

I'm very interested in any more feedback you have on this! I'm a real
beginner when it comes to OpenGL stuff!


 I started with this particular loader and extensively modified it and
 improved it to support vertex arrays, vertex buffer objects, display lists,
 and fixed functionality.  It also has better support for .mtl files and
 handles file loading and texturing more elegantly.  It also calculates the
 tangent vectors for use in normalmapping and related techniques.

 It's presently integrated into glLib 
 Reloadedhttp://www.pygame.org/project-glLib+Reloaded-1326-.html,
 my project, which I humbly present.  The actual loader,
 (glLib/glLibLoadOBJ.py), is heavily tied into the rest of the library, and
 as such I can't support using it in other ways--but, you may find it useful.


Great, thank you so much! I'll definitely have a look!

-Christopher


Re: [pygame] frame independant movement

2010-08-27 Thread Christopher Night
Sure. But of course, it's extremely easy to do constant-acceleration motion
as well:

x += vx * dt + 0.5 * g * dt ** 2
vx += g * dt

These results will be exactly correct. I did run into the issue with
collision detection at one point. In my case, I needed at least, say, 10fps
for the collision detection to work, and I decided that if the computer
couldn't handle that, I would accept some slowdown so that the game at least
worked. All I had to do was:

dt = max(clock.tick() * 0.001, 0.1)

In another case, I  needed higher framerate for collision detection (say
50fps), and I was render-limited, not physics-limited. In that case I did:

dt = max(clock.tick() * 0.001, 0.1)
for j in range(5):
for sprite in sprites:
sprite.think(dt/5.)

So I only got slowdown when the framerate dropped below 10.

Anyway, it's fine to have a library to do this, but there are some simple
things that have always worked for me.

-Christopher

On Fri, Aug 27, 2010 at 11:43 AM, Brian Fisher br...@hamsterrepublic.comwrote:

 That approach is perfectly fine with linear movement - because the linear
 calculations aren't affected significantly by how large dt is (or put
 another way: x += vx*2 is nearly identical to x += vx*1, x += vx*1 on your
 computer)

 However, with any nonlinear physics (like say, gravity's relationship to
 position, or an accelerating object)  or with discrete actions that happen
 once per frame (like say the artificial intelligence for an enemy that
 decides what to do once every frame), then your game behavior can change
 quite significantly depending on what values of dt you get.

 ---
 For example, lets say you do gravity like this:
 vy = vy + gravity*dt
 y = y + vy*dt

 with a dt of 2, from vy = 0, y = 0, the result is:
 vy = vy + gravity*2 = gravity*2
 y = y + (gravity*2)*2 = gravity*4

 however if you get a dt of 1 twice, from the same starting point, the
 result is:
 vy = vy + gravity*1 = gravity
 y = y + (gravity)*1 = gravity
 ...
 vy = vy + gravity*1 = gravity + gravity = gravity*2
 y = y + (gravity*2)*1 = gravity + gravity*2 = gravity*3
 ---

 so you've only moved 3/4 of the distance (3 vs. 4 gravitys) down with a
 frame rate that is twice as fast, even though you are parameterizing
 everything on dt. Note the acceleration component (which is linear with
 time) is consistent and accurate with both timestep sizes.

 So you asked what else do you need? well the answer is if you want
 consistent non-linear physics (like say you want the players to jump the
 same all the time), then the else you need is fixed size timesteps for
 your physical simulation.



 On Fri, Aug 27, 2010 at 8:27 AM, Christopher Night cosmologi...@gmail.com
  wrote:

 Here's what I always do:

 dt = clock.tick() * 0.001
 x += vx * dt
 y += vy * dt

 And all the sprites have a think(dt) method that updates them as if dt
 seconds have passed. What else do you need?

 -Christopher


 On Fri, Aug 27, 2010 at 11:19 AM, James Paige 
 b...@hamsterrepublic.comwrote:

 On Fri, Aug 27, 2010 at 10:59:09AM -0400, Kris Schnee wrote:
  On 2010.8.27 10:36 AM, B W wrote:
  Howdy,
 
  Reviving this old thread. The comments by Patrick and Brian really
  intrigued me, so I pursued the topic. Found a few interesting articles
  and one great article. My study has resulted in a recipe for those of
 us
  continually nagged by the question, how can I get constant game speed
  independent of frame rate?. The demo requires Pygame, but the clock
  module only requires Python.
 
  Isn't it simply a matter of creating a Pygame Clock object and calling
  clock.tick() to delay until the appropriate time to maintain some max
  framerate?

 That only caps a max framerate. What Gumm is talking about is when your
 framerate and your game simulation rate can be adjusted independantly

 ---
 James Paige






Re: [pygame] frame independant movement

2010-08-27 Thread Christopher Night
Here's what I always do:

dt = clock.tick() * 0.001
x += vx * dt
y += vy * dt

And all the sprites have a think(dt) method that updates them as if dt
seconds have passed. What else do you need?

-Christopher

On Fri, Aug 27, 2010 at 11:19 AM, James Paige b...@hamsterrepublic.comwrote:

 On Fri, Aug 27, 2010 at 10:59:09AM -0400, Kris Schnee wrote:
  On 2010.8.27 10:36 AM, B W wrote:
  Howdy,
 
  Reviving this old thread. The comments by Patrick and Brian really
  intrigued me, so I pursued the topic. Found a few interesting articles
  and one great article. My study has resulted in a recipe for those of us
  continually nagged by the question, how can I get constant game speed
  independent of frame rate?. The demo requires Pygame, but the clock
  module only requires Python.
 
  Isn't it simply a matter of creating a Pygame Clock object and calling
  clock.tick() to delay until the appropriate time to maintain some max
  framerate?

 That only caps a max framerate. What Gumm is talking about is when your
 framerate and your game simulation rate can be adjusted independantly

 ---
 James Paige