Re: [pygame] Current working version of Python and pygame

2020-10-23 Thread Berlioz Silver
You can add python to PATH by rerunning the same installer you used to
install it. There will be a "modify" choice, and in the next two pages are
options to adjust the parts of python installed, and to add it to "the
environment"-- the PATH.

I would suggest using 3.7. 3.8 is likely to work, but at this time I do not
believe 3.9 has functioning pygame wheels, and this will be a pain point
for students.

On Fri, Oct 23, 2020 at 4:45 PM claudio canepa  wrote:

> >  Question 1:  If someone already has installed Python but did not check
> this box on, is there some simple command line magic to do whatever this
> checkbox does?  If so, what do I need to tell my student to do?
>
> With a python 3.X  installed  they need replace 'python' by 'py -3.X' in
> the cmdline.
> Examples, for a python 3.7 installation:
> To invoke the interactive interpreter:
>py -3.7
> To run a script:
>   py -3.7 myscript.py
>
> Another difference with unix-like OSes is that the python's Scripts
> directory is not on the path, so pip (and other commands in Scripts) need a
> full qualified path in the command, like
>   c:\python37\Scripts\pip install ...
> or the alternative form
>   py -3.7 -m pip install ..
>
> I don't know if it would be better to work from a venv:
>
> Create venv
> py -3.7 -m venv venv_path
> Activate
> venv_path\Scripts\activate
>
> After that, in that console 'python' would be the python in the venv, and
> venv_path\Scripts will be in the PATH, so commands like 'pip', 'pytest',
> etc would work fine.
>
> To deactivate the venv:
>deactivate
>
> > Question 2:  If someone does not have Python installed yet (or wants to
> install a newer version), what is the most recent version of Python (Mac
> and Windows) that I should ask them to install today?  I understand that
> there is a big effort to get the 2.0 version of Pygame out, but I want my
> students to use version 1.9 for now.  If they install the current version
> of Python: 3.9, will they be able to use pip to install a working version
> of pygame 1.9?  (Last time I checked, this did not work correctly?
>
> python 3.8 has been tested more time; also 3.9 is not compatible with
> windows7, which maybe some students have in their house.
>
>
> On Fri, Oct 23, 2020 at 7:08 PM Irv Kalb  wrote:
>
>> I am teaching a Python class, where I use pygame to demonstrate OOP
>> concepts.  I need to have my students get the proper environment to run
>> Python with pygame.
>>
>> I use a Mac, and I have Python 3.7.3, and pygame 1.9.6 installed.
>> Everything works fine for me.  But I have students who either have Python
>> already installed and need to install pygame, or who need to install both
>> Python and pygame.
>>
>> I am not a Windows user, and I typically don't use the command line for
>> anything other than installations.  My understanding is that if you are on
>> Windows, and you want to use pygame, then during the installation of
>> Python, when the installation puts up dialog box about installing Python,
>> you must check the checkbox at the bottom that says:
>>
>>  Add Python 3.x to PATH
>>
>> Question 1:  If someone already has installed Python but did not check
>> this box on, is there some simple command line magic to do whatever this
>> checkbox does?  If so, what do I need to tell my student to do?
>>
>> Question 2:  If someone does not have Python installed yet (or wants to
>> install a newer version), what is the most recent version of Python (Mac
>> and Windows) that I should ask them to install today?  I understand that
>> there is a big effort to get the 2.0 version of Pygame out, but I want my
>> students to use version 1.9 for now.  If they install the current version
>> of Python: 3.9, will they be able to use pip to install a working version
>> of pygame 1.9?  (Last time I checked, this did not work correctly?
>>
>> Thanks in advance,
>>
>> Irv
>>
>>
>>


Re: [pygame] OpenGL stretch of a pygame.Surface

2014-08-07 Thread Berlioz Silver
right. Before you blit. My bad.


On Mon, Aug 4, 2014 at 6:03 PM, Greg Ewing 
wrote:

> Berlioz Silver wrote:
>
>> You want pixels2d, which gives you a variable which _references_ the data.
>>
>
> Yes, sorry, I got it the wrong way round. You need to start
> with a normal surface that you can blit into, and then use
> pixels2d to create a numpy view of it that you can pass
> directly to OpenGL.
>
>  While the reference is still there, the surface is locked (otherwise you
>> could change the data mid-blit, which would be bad). Instead, you should
>> use:
>>
>> del (variable with pixels2d in it)
>>
>> right before you pass it off to GL or pygame.
>>
>
> I think you mean *after* passing it to GL, don't you?
>
> --
> Greg
>


Re: [pygame] OpenGL stretch of a pygame.Surface

2014-08-04 Thread Berlioz Silver
You want pixels2d, which gives you a variable which _references_ the data.
While the reference is still there, the surface is locked (otherwise you
could change the data mid-blit, which would be bad). Instead, you should
use:

del (variable with pixels2d in it)

right before you pass it off to GL or pygame.

Also, how are you setting up opengl? I haven't gotten that working (hence
why I've looked into surfarray).

Also, if you are dropping to a reasonably moniterable framerate (~120 or so
and below) you can check to see what is taking too long. Simply separate
your commands with calls to time.time() and check at the end. you can print
out the time required (possibly on keypress?) and it'll show you what is
taking so long:

firstTime = time.time()
(create texture)
aCheckpoint = time.time()
(draw your sprites)
bCheckpoint = time.time()
(scale)
cCheckpoint = time.time()

print firstTime, aCheckpoint - firstTime, bCheckpoint - aCheckpoint -
firstTime [etc]

This'll give you the time used (in milliseconds) for each step of the
frame. While I have my own suspicions of what is taking so long, timing it
will show us for certain.


On Wed, Jul 30, 2014 at 9:35 PM, VertPingouin <
sylvain.bousse...@vertpingouin.fr> wrote:

> Ok I now create my texture once.
>
> I'm having some issues with this
>
> > You're creating an extra copy of the texture data here.
> > To avoid that, you could use surfarray to create a surface
> > backed by a numpy array, do your drawing into that, and
> > then pass the numpy array directly to glTexImage2D.
>
> As I understand it, you suggest a surface with a surfarray.pixel2d bound
> to it. But I can't blit on such surface beacause it's locked. Did you
> mean drawing directly in surfarray or just create and update a
> surfarray.2darray which involve to do a copy of the native screen also ?
>
>
> Thanks for all your advises everyone.
>
>
> Le mercredi 30 juillet 2014 à 11:15 +1200, Greg Ewing a écrit :
> > sylvain.boussekey wrote:
> >  > I managed to do it in opengl but perfs are poor.
> >
> > A few things to consider:
> >
> >  > textureData = pygame.image.tostring(textureSurface, "RGBA", 1)
> >
> > * You're creating an extra copy of the texture data here.
> > To avoid that, you could use surfarray to create a surface
> > backed by a numpy array, do your drawing into that, and
> > then pass the numpy array directly to glTexImage2D.
> >
> >  > texture = glGenTextures(1)
> >  > glBindTexture(GL_TEXTURE_2D, texture)
> >  > glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
> GL_NEAREST)
> >  > glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
> GL_NEAREST)
> >
> > * You're creating a new OpenGL texture for each frame and
> > then discarding it. Try making these calls just once
> > at the beginning and re-using the texture.
> >
> > * You're using a non-power-of-2 texture size. Not all
> > OpenGL implementations support that; yours seemingly does,
> > but it might be less efficient than a power-of-2 size.
> > You could try allocating the next larger power-of-2 size and
> > updating the part that you use with glTexSubImage2D().
> >
>
>
>


Re: [pygame] Re: Pygame not handling keyboard tracking correctly

2014-06-23 Thread Berlioz Silver
OK EVERYONE.

If someone had read the python docs, they'd have known exactly why this
occurs. The difference between the keyword operator "is" and "==" is due to
the fact that:
*  some people want to compare a custom class and an integer, and if the
custom class' __ methods return the same as the integer, the want a value
of true.
AND
* some people want to know if the number they got IS EXACTLY 3 and won't do
wonky stuff when they multiply it.

Thus we have 4 operators for equality comparisons:

== (eq)
=== (is)



On Mon, Jun 23, 2014 at 8:14 AM, bw  wrote:

>  Try:
>
> id(a), id(b)
>
> In some cases they are different objects, and "a is b" rightly evaluates
> to False.
>
> Gumm
>
> On 6/23/2014 00:39, diliup gabadamudalige wrote:
>
> when you say a=100 and b=100 it is understood that a and b are both given
> TWO values and that both are the same is a coincidence.
> BUT if that is the case how can a is b be TRUE for small integers and a is
> b False for large integers? What logic is Python using here?
>
>
> On Mon, Jun 23, 2014 at 1:07 PM, diliup gabadamudalige 
> wrote:
>
>> ok
>> look at this!
>>  a = 100
>> b = 100
>> a == b
>> True
>>  a is b
>> True
>> a = 1000
>> b = 1000
>> a is b
>> False
>>  a == b
>> True
>>
>>  what on earth is this? what is this logic?
>>
>>
>> On Mon, Jun 23, 2014 at 1:03 PM, Sam Bull  wrote:
>>
>>> On lun, 2014-06-23 at 11:45 +0530, diliup gabadamudalige wrote:
>>> > I called event.clear() cause it says in the Pygame documentation that
>>> > if you leave unused events on the buffer that eventually it may fill
>>> > up and cause the program to crash.
>>>
>>>  Yes, but if you are getting everything from the buffer using event.get()
>>> or whatever every frame, then it's not going to fill up, as these
>>> returned events are removed from the queue. As long as you are reading
>>> the whole buffer, say every 100ms, you're going to be fine. Otherwise,
>>> you're just throwing away the events that have arrived between the
>>> event.get() and event.clear() calls.
>>>
>>> >
>>> > if x is True:
>>> > is not correct
>>> >
>>>  > if x == True
>>> > is correct?
>>>
>>>  This obviously depends on what x is.
>>>
>>> So, if we write:
>>> "foo" is True
>>>
>>> We can clearly see these are not the same object. One is a string, and
>>> the other is the True object. But, if we do:
>>> "foo" == True
>>>
>>> Then, we are asking if the string evaluates to a True value, when
>>> treated as a boolean. And any non-empty string will be considered True,
>>> and so it is equal to True (but not the same object).
>>>
>>>
>>> Futhermore, what Greg was saying is that some objects can be of the same
>>> value and still not be the same object. Thus:
>>> a = 4040
>>> b = 4040
>>> a == b  # True
>>> a is b  # Could be False
>>>
>>> b = a  # b now references the a object itself
>>> a is b  # Always True
>>>
>>> This becomes more obvious if we were to use mutable types:
>>> a = [2]
>>> b = [2]
>>> # Obviously, these are two distinct objects
>>> a == b  # True
>>> a is b  # False
>>> # Changing one, would not change the other, as they are
>>> different
>>> # objects.
>>> a.append(3)
>>> a == b  # False
>>>
>>>
>>> On an interesting sidenote, it is not even required that an object is
>>> equal to itself:
>>> a = float("NaN")
>>> a == a  # False
>>>
>>
>>
>>
>>   --
>> 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.
>>
>> **
>>
>>
>
>
>  --
> 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

Re: [pygame] Segmentation Fault, Abort trap: 6

2014-05-23 Thread Silver
According to here
(https://groups.google.com/forum/#!topic/kivy-users/QdSkaIcP9d0) this is
usually due to a faulty installation.


On 5/23/2014 2:17 AM, Marian Steinbach wrote:
> Hi!
> 
> I just installed pygame today after some time to re-animate an old project of 
> mine. I used the current source from bitbucket.
> 
> I’m getting this error:
> 
> Fatal Python error: (pygame parachute) Segmentation Fault
> Abort trap: 6
> 
> What could it mean?
> 
> I'm on Mac OS 10.9.3, Python version is 2.7.5. SDL has been installed via 
> homebrew just today.
> 
> Thanks!
> 
> Marian
> 
> 


-- 
O< ascii ribbon campaign - stop html mail - www.asciiribbon.org

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com



[pygame] pygame midi module

2013-07-22 Thread Silver
I was trying out the pygame.midi module in the python interpreter. It
seems nice although it is a WIP (?). Just thought I'd let you know
trying to create multiple output objects for the same output can cause a
segfault.

Specifically, when you re-init the module (pygame.midi.quit();
pygame.midi.init()) it doesnt remember that the output is already occupied.

Is there anywhere I should report this?


Re: [pygame] Attribute Error

2012-11-22 Thread Silver
On 11/22/2012 2:22 PM, myles broomes wrote:
> 
> I didnt name it pygame.py? The name of the file is pong.py. It isnt just this 
> file im having trouble with, its every file that involves the pygame module. 
> > Date: Thu, 22 Nov 2012 12:39:53 -0500
>> Subject: Re: [pygame] Attribute Error
>> From: false.ho...@gmail.com
>> To: pygame-users@seul.org
>>
>> Don't name your file pygame.py.
>>
>> -- 
>> --Robert Deaton
> 
> 

Well the error you are getting is where the name -pygame- got defined
where it shouldn't and has overwritten you module import.

whether or not you have a file named pygame in your module path/folders
or whether a functions is setting that name to something else I can't tell.


put
"print pygame"
before you call pygame.init() and then tell us the result. That will help.



Re: [pygame] BGRA to RGB/RGBA, fastest way to do so

2012-09-01 Thread Silver
On 9/1/2012 12:52 PM, gm770 wrote:
> I'm trying to convert a color string buffer, and looking for the fastest way
> to do so.
> I'm capturing a 2 screen desktop (h=1080, w=3840), but it comes in as BGRA,
> and I don't see an obvious way to convert that to RGBA or RGB.
> 
> The fastest way I have so far is ~1.78 sec, but I'm sure there must be
> something faster.
> 
> def toRGBA(BGRA_str):
> buf = bytearray(BGRA_str)
> for x in xrange(0,len(buf),4):
> buf[x], buf[x+2] = buf[x+2], buf[x]
> return buf
> 
> Slower methods include: 
> - starting with an empty array, and via loop, appending to create RGB. (~3.8
> sec)
> - turn the buffer to a list of chars, swap and return the joined results.
> (~2.14 sec)
> 
> 
> 
> --
> View this message in context: 
> http://pygame-users.25799.n6.nabble.com/BGRA-to-RGB-RGBA-fastest-way-to-do-so-tp163.html
> Sent from the pygame-users mailing list archive at Nabble.com.
> 
>From the doc page comments:
As for "BGR" (OpenCV): Just use "RBG" but reverse the string first
and then flip the surface (vertically and horizontally).

I am using this with fromstring:

frame = cvQueryFrame(capture)# get a video frame
using OpenCV
bgr = frame.imageData# this is a string
using BGR
rgb = bgr[::-1]  # reverse it to get RGB
im = pygame.image.fromstring(rgb, size, 'RGB')   # create pygame surface
im = pygame.transform.flip(im, True, True)   # flip it



you could also use map():

x = [buf[x], buf[x+2] for x in xrange(0, len(buf), 4)]## convert to list
format

map(lambda x: [x[2], x[1], x[0], x[3]], bgra) ## returns a list of
four-item lists in RGBA format.


or you could import/export it from pygame:

ARGB = BGRA[::-1]
ARGB_image = pygame.image.fromstring(ARGB, size, "ARGB")
RGBA_str = pygame.image.tostring(ARGB_image, "RGBA")



Re: [pygame] rotate around point

2012-08-21 Thread Silver
try using math.sin() and math.cos()

for example:

lets call the position of the shoulder shoulderPosition which is a tuple
(0,0)
lets call the angle you want to rotate it to angleShoulder (in radians,
to convert from degrees use math.radians()
lets call the length of the upper arm upperArmLength

then

elbowPosition =
(upperArmLength*math.cos(angleShoulder)+shoulderPosition[0],
upperArmLength*math.sin(angleShoulder)+shoulderPosition[1])

then you can center your image there and rotate it.

Heres an image on how it works

On 8/21/2012 10:08 AM, Ricardo Franco wrote:
> Hi, guys. Tks for the answers, but I didnt understand how to rotate it yet.
> I made a workaround by putting my arm image inside a blank square cover, so
> the center of the image is where I want.
> This way I can rotate around the center and get the spected result with the
> arm -> shoulder joint.
> But I cant get a good result within forearm -> arm joint.
> 
> 2012/8/20 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"  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
>>>  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
>>>
>>
> 
> 


-- 
O< ascii ribbon campaign - stop html mail - www.asciiribbon.org
<>

[pygame] help with clock

2012-05-08 Thread Silver
I wrote a small clock program that I might use if it turns out well, but
I am having a small issue where the top of the arcs that grow over time
shifts when I would like it to stay still. Does anyone know how to
achieve this?

from pygame import *
import time, math
import pygame, sys


def timeintoms():
t = time.time()
#print t
t %= 24*60*60 
#print t, "Time since last day"
t *= 1000
#print t, "Milliseconds"
return t

def draw_arc(surface, color,pos, radius, width, angle1, angle2):
angle2 -= math.pi/2
angle1 += math.pi/2
pygame.draw.arc(surface, color, (pos[0], pos[1], radius, radius), -angle2, angle1, width)

pygame.init()
screen = pygame.display.set_mode((200,200))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise SystemExit
screen.fill((0,0,0))
t = timeintoms()
s = t / 1000
m = s / (60)
h = m / (12)
s %= 60
m %= 60
h %= 12
#print(str(h)+":"+str(m)+":"+str(s))
angleg = math.radians((s / 60)*360)
angleb = math.radians((m / 60)*360)
angleo = math.radians((h / 12)*360)
angle1 = 0
#print(angleg-angle1)
draw_arc(screen, (21,176,26), (0,0), 200, 10, angle1, angleg)
draw_arc(screen, (3,67,223), (20,20), 160, 10, angle1, angleb)
draw_arc(screen, (249,115,6), (40,40), 120, 10, angle1, angleo)
pygame.display.update()



Re: [pygame] Intercepting the Keyboard

2012-03-08 Thread Silver
On 3/7/2012 8:03 PM, Ryan Strunk wrote:
> Hello everyone,
> In creating audio-based games, I'm trying to make my programs work with
> major screen readers. The problem is that the industry leader, JAWS, likes
> to intercept keystrokes sent to the system. This means that if you build
> arrow key use into a pygame program, JAWS gets to your arrow keys first and
> processes them before Pygame can. Unfortunately, cutting out the screen
> reader isn't an option, as it's used to read any game text that might be
> written to the screen.
> I'm curious if anyone has recommendations as to how I could have Pygame or
> Python get to keyboard events before the rest of the system. I have a friend
> who was able to make this happen using C#.net, but I can't even begin to ask
> how or if it's possible to do this using Python.
> Any help you all can provide would be greatly appreciated.
> All the best,
> Ryan
> 
Try using the pyHook. It allows you to catch these events really easily.
It also allows you to shut off keypresses, including ctrl-esc.


from ctypes import windll
import pyHook as pyhook

hardman = pyhook.HookManager()
hardman.KeyDown = [your key handling function here]
hardman.HookKeyboard()


Re: [pygame] Line collision detection?

2012-02-21 Thread Silver
On 2/20/2012 1:50 PM, Julian Marchant wrote:
> Hi, I tried searching the internet for an answer, but didn't find anything, 
> so I'll ask here.
> 
> One problem with normal collision detection I'm sure we're all aware of is 
> the problem that objects moving too fast can pass through other objects 
> without a collision happening. I'm experiencing this problem with a scrolling 
> shooter I'm working on because both bullets and enemies move pretty fast, one 
> enemy is very small, and the frame rate is usually somewhat low (maybe 30 
> FPS) on the machine I'm targeting.
> 
> Now, obviously, I intend to make other changes which will help, e.g. making 
> these tiny enemies bigger, but I'd like to tackle the problem directly. There 
> are two ways I can think of: The first way, which I easily could implement 
> and would be most effective, is to move the bullets in steps and do collision 
> detection each step. I have done something like this in a previous game and 
> it worked well, but it seems like overkill in this game (the bullet subrect 
> is only 5x5 pixels) and it isn't perfect anyway.
> 
> The second way, which I would prefer, is to detect collision with a line from 
> the bullet's new position to the bullet's previous position. I've seen this 
> discussed on the Game Maker Community. The problem with this is I have no 
> idea of how this could be done in a remotely efficient manner. The only 
> method I can think of is to check every individual pixel one at a time, which 
> is obviously not a good idea. Bullets can move diagonally, so just checking 
> the x or y position won't work.
> 
> So, in a nutshell, my question is: how could I do "line collision" detection 
> like this in a relatively efficient way?


Personally a way to combine the idea in the last reply (four corner
lines) would be to use a kind of inequality.

To do this in pygame you could extend the collision rectangle so that it
fills the whole area that the bullet travels in. Then you could do the
collision detection per-pixel or with whatever accuracy you wish.



So, if I have a rectangle (25, 25, 10, 10), moving at an x speed of 8, I
could do this:

speed = 8

if (25,25,10+speed, 10).collide(your target rect):
then ## you r pixel perfect collision algorithms, an example:

for stepoffset in range(speed):
if (25+stepoffset,25,10,10).collide(your target rect)
collide.


this could easily be expanded to support two moving projectiles.


it might not be as efficient as line-collision, but it seems easier to
understand to me.

I hope this helps.


Re: [pygame] Re: Is Pygame suitable for full HD games?

2012-02-06 Thread Silver
If you blit to a separate image, then it to the screen, I think you
aren't taking advantage of the HWSURFACE flag. If somebody else could
confirm this is correct, please do.

To set a surface to have the HWSURFACE flag, you need to create the
surface with it:

image = pygame.Surface((1920,1080), pygame.HWSURFACE)

then just blit it as normal.



I hope this answers your questions,
    Silver


Re: [pygame] Is Pygame suitable for full HD games?

2012-02-05 Thread Silver
On 2/5/2012 6:23 AM, Luis Morcillo wrote:

> I finished the tiled background engine, and I've noticed a
> 15 fps drop in 1920x1080. And when I added a 5 planes parallax scroll,
> fps are going down to 10-20. I doubt it's the machine, as I play games
> like Starcraft in Ultra settings on it. Also, I'm noticing most games
> developed with Pygame are 640x480 or 800x600. So the question would
> be: is Pygame suitable for doing a full HD side-scrolling platformer?
> 
> My current approach is to render all scrolls planes and the tiled
> background to a single surface (the ".image" of my Stage class),
> instead of rendering each one in different planes. I haven't tried
> separating yet, but I doubt it will improve performance, as the
> blitting will be the same. Am I wrong?
> 
If you don't blit it directly to a HWSURFACE, then it will still be
software blitting and probably wont make much of a difference. Try
initiating your .image with the HWSURFACE flag, and see if it improves
speed.

I think you are blitting everything to a .image, then the .image to the
screen once, right?



> I've read the Surface.blit() function is somehow slow and shouldn't be
> overused, but I don't know another way of rendering images to the
> screen. I tried using flags "HWSURFACE | DOUBLEBUF | FULLSCREEN" and
> it increased 2-3 fps. Am I missing some other optimization or am I
> just using the wrong engine for an HD platformer?


Say, are you using per-pixel transparency?
I know for a fact that it slows pygame down a lot, so if you don't need
intermediate tranlucency (eg, fading) you could use colorkeys.

I know that per-pixel alphas are slow, because I ran a test at 1920x1080
and adding a fifth surface with per-pixel alpha dropped frames from ~ 30
to ~8 per second.

Using colorkeys gave me 200 fps w/ pygame.RLEACCEL.
Adding one surface w/ transparency dropped it to 60fps.

I can send the code if you wish.


I do have a higher-end system, so opengl will probably be a good idea.
I'd suggest looking into PyGL3Display, which works for me although I
have just started to try it out.

I hope I have been helpful to your efforts.



[pygame] Just sharing

2012-02-03 Thread Silver
I've been working on my little gravity program, except it really doesn't
apply to gravity anymore. Feel free to use it as you wish.

:
* press Esc to exit, q to almost stop all the particles, mouse to move
the central particle, any other key to add a new particle.
* 3d distances+ interactions
* 'spin'
* mouse attracts particles, scroll to control attraction speed
* uses multiprocessing (though not perfectly. Still working on the
comments I got from here, thanks!)

Note: If you aren't using python 3, uncomment the section in the file so
that the print statements don't raise a syntax error.
import pygame
from pygame import *
import random

import multiprocessing
import time
import math, sys

width = 1920
height = 1080
zheight = 1080
x = 0


## if running py2.7 or earlier, uncomment this:
"""
def print(n):
print n



"""



def attract(itemlist): ## primary functin
mspd = 4
gravitar = itemlist[1]
itemlist = itemlist[0]
exc = 0
red = 0
rep = 8
for i in itemlist:
if i.id != gravitar.id: #and i.spind == gravitar.spind:
#print(i.spind)
#print(gravitar.spind)
n = True
if i.spind == gravitar.spind:
n = False



if gravitar.mass > i.mass:
greatermass = gravitar.mass
else:
greatermass = i.mass
xdiff = gravitar.x - i.x  
ydiff = gravitar.y - i.y
zdiff = gravitar.z - i.z
dist = ((xdiff**2) + (ydiff**2) + (zdiff**2))**.5
if dist < greatermass:
dist = greatermass

if i.id == -1:
dist **= .8


#landmark
if i.id == -1:
acceleration = ((rep*(rep*gravitar.mass))/(dist**2)) / gravitar.mass
else:
acceleration = ((rep**3)/(dist**2))

xc = xdiff/dist
yc = ydiff/dist
zc = zdiff/dist
if n:
if i.id != -1:
gravitar.dx += acceleration * xc
gravitar.dy += acceleration * yc
gravitar.dz += acceleration * zc
else:
gravitar.dx -= acceleration * xc
gravitar.dy -= acceleration * yc
gravitar.dz -= acceleration * zc

else:
exc += 1
#if exc > 1:
#print "Exc is" + str(exc)
#pass
#raise ValueError, exc
"""if gravitar.dx > mspd:
red += gravitar.dx - mspd
gravitar.dx = mspd
if gravitar.dx < -mspd:
red += abs(gravitar.dx) - mspd
gravitar.dx = -mspd   
if gravitar.dy > mspd:
red += gravitar.dy - mspd
gravitar.dy = mspd
if gravitar.dy < -mspd:
red += abs(gravitar.dy) - mspd
gravitar.dy = -mspd   

if red > 0:
gravitar.red = red
else:
gravitar.red = None"""

if gravitar.x > width or gravitar.x < 0:
gravitar.dx *= -.98
gravitar.x += gravitar.dx*1.2
else:
gravitar.x += gravitar.dx
if gravitar.y > height or gravitar.y < 0:
gravitar.dy *= -.98
gravitar.y += gravitar.dy*1.2
else:
gravitar.y += gravitar.dy
if gravitar.z > zheight or gravitar.z < 0:
gravitar.dz *= -.98
gravitar.z += gravitar.dz*1.2
else:
gravitar.z += gravitar.dz


gravitar.mass = ((abs(gravitar.dx) + abs(gravitar.dy) +abs(gravitar.dz))/3.0)
#gravitar.x += gravitar.dx
#gravitar.y += gravitar.dy

#gravitar.dx *= .999
#gravitar.dy *= .999
gravitar.mass = 10/gravitar.mass
return gravitar






class Gravitar(object):
def __init__(self, id):
self.id = id
self.red = None
self.x = random.random()*width
self.y = random.random()*height
self.z = random.random()*zheight
self.dx = random.random()*3
self.dy = random.random()*3
self.dz = random.random()*3
self.mass = 8
self.spind = random.choice([.5,-.5])

class SGravitar(object):
def __init__(self):
self.red = None
self.id = -1
self.x = 0
self.y = 0
self.z = zheight/2
self.dx = 0
self.dy = 0
self.dz = 0
self.mass = 20
self.spind = 1



def genlist():
n = []
global x
for i in range( 2):
n.append(Gravitar(i))
x += 1

return n

if __name__ == '__main__':

pygame.init()
screen = pygame.display.set_mode((width, height), pygame.FULLSCREEN)

screeno = pygame.Surface((screen.get_rect().width, screen.get_rect().height))
screeno.convert()
screeno.fill((0,0,0))
screeno.set_alpha(1, pygame.RLEACCEL)
# Establish communication queues


pool = multiprocessing.Pool(pro

[pygame] Re: antialiasing routine

2012-01-23 Thread Silver
On 1/23/2012 3:54 PM, Silver wrote:
> Anybody know a really fast antialiasing routine for python/pygame?

Nevermind. I really need to pay attention and look stuff up elsewhere.
Sorry for mail spam.


Re: [pygame] Re: Python optimization help

2012-01-23 Thread Silver
On 1/20/2012 1:09 AM, Weeble wrote:
> Step 1: measure!
> 
> Unless you measure, you can't tell what's costing you time here. It could
> be rendering the circles. It could be processing the physics. It could be
> overhead in interprocess communication. Both of the latter appear to be
> O(N^2), and the communication costs cannot be parallelized. However, it
> does seem likely the calculations are the significant cost unless you have
> a ridiculous number of cores and amazing memory bandwidth.
> 
> Your calculations look reasonably amenable to use of numpy. This will do
> the numeric calculations in well-optimized C code. The for-loop in attract
> is embarrassingly parallel and shouldn't be hard to convert to an
> array-based form. In addition, since numpy releases the GIL during most
> array operations, you might find that multi-threading is good enough, and
> if you do go down that route you could avoid some of the cost of
> inter-process communication.
> 
> It might be obvious, but pick a number of workers that does not exceed your
> available number of cores. There's no value in having the workers fight
> each other for time on the same cores. multiprocessing.Pool will by default
> pick a number of workers equal to your number of cores, so you probably
> don't need to override it.
> 
> If after all that it's still not fast enough, I suspect you'll need to go
> to GPU-based solutions. Given the nature of the problem, I'd imagine you
> could get a good further speed boost out of this route, but you may well
> need to spend days or weeks getting familiar with these technologies.
On 20.01.2012 04:45, Robert Xiao wrote:
> If you are CPU-bound, extra threads won't help in Python due to the GIL (it 
> limits an entire Python process to one core, even with multiple threads). 
He doesn't use threads though, he uses multiprocessing, which makes your
point somewhat moot. Also, from my own experiments, multiple threads DO
use multiple cores, they just interfere with (i.e. block) each other due
to the GIL. But you're right in that also multiple processes must
compete for the available processing power, even if they do that more
efficiently than threads in Python.

It would be nice, when you post code for others to examine, to

a) remove any unused code (i.e. "Consumer" and "Task"),
b) remove comments that refer to old versions of the code,
c) include a clean way to exit the program and
d) use more descriptive variable names.

Bad examples: "x", "lastx", "itemlist", "result" (when you really mean
"gravitars"), "i" in the for loop in "attract" - "body" or
"other_gravitar" would have been better here.

> Oddly enough, lowering the amount of extra workers in the pool results
> in a higher speed?
How do you measure speed? Where's your FPS counter? Have you timed your
"attract" function with the timeit module?

Your example uses 12 workers but your code is totally CPU bound. How
many CPUs / cores does your computer have? Adding workers doesn't
magically add new cores  Communication between the main process and
the worker processes adds some overhead as well as process switching
(the latter should be very fast on Unices though), so even if your
system had 12 cores, the speed wouldn't scale linearly from 1 to 12 cores.

One way to speed up your program without resorting to
hardware-acceleration would be to implement your main calculation
function "attract" in C with the help of Cython (cython.org). A little
static type information added can sometimes do wonders.

Finally a few oddities in your code, which aren't necessarily speed related:

- Why do you use pool.map_async() when you then use the blocking
res.get() immediately anyway? Just use pool.map().

- Your way of constructing the list of arguments to the workers isn't
very clear with the use of the self-referencing list. Also, passing the
full list with each job in each iteration certainly adds some overhead
(though probably negligible compared to the time spent in the "attract"
function). Consider using a shared state for this list via
multiprocessing.Manager().

- The "genlist" function seems a bit pointless. Why not create a
two-item list directly in your __main__ statement block and maintain the
list item counter "x" also there? No need for ugly globals.

gcount = 2
gravitars = [Gravitar(i) for i in range(gcount)]

- The use of (screen) "width" and "height" as global variables in
"Gravitar" and "attract" is unclean and prone to subtle errors in a
multiprocessing environment. I would introduce a world object, which is
passed to "attract" (or accessible via a shared state).

Attached is a IMHO much cleaner, but not yet optimized, version of your
script.

HTH, Chris



Thanks, this will help me. I managed to getnumpy installed on my
haphazard system, so now I'm going to learn how to time stuff properly.


[pygame] antialiasing routine

2012-01-23 Thread Silver
Anybody know a really fast antialiasing routine for python/pygame?


Re: [pygame] moving a dot!

2012-01-23 Thread Silver
On 1/22/2012 2:32 PM, babaz wrote:
> Hello,
> 
> How can I modify this programm to be able to move the yellow dot with the 
> keys of a keyboard?
> 
> Here is the script :
> 
> # -*- coding: cp1252 -*-
> ## Michael ELBAZ
> ## AE(a)
> 
> full_screen = True
> window_size = (1024, 768)
> 
> import sys, random, pygame, os, platform
> from pygame.locals import *
> from math import *
> 
> delta=2
> delta_step=1
> 
> circles = ((0, delta),)
> 
> circle_scale = 0.3
> circle_radius = 8
> n_grid = 3
> grid_spacing = 0.2
> grid_length = 0.05
> grid_width = 2
> rotation_speed = pi/2
> grid_color = (100, 100, 255)
> fix_radius = 8
> bg_color = (0, 0, 0)
> circle_color = (255, 255, 0)
> disapp_frames = 1
> 
> window_center = (window_size[0]/2.0, window_size[1]/2.0)
> window_scale = min(window_size)/2.0
> def coord(real):
> """takes real coordinates, returns pixel coordinates"""
> return (int(round(real[0]*window_scale + window_center[0])),\
> int(round(-real[1]*window_scale + window_center[1])))
> g_cos, g_sin = 1, 0
> def set_rotation(angle):
> """sets up rotation"""
> global g_cos, g_sin
> g_cos, g_sin = cos(angle), sin(angle)
> def rotate(point):
> """rotates a 3D point about the Z-axis by given angle set by 
> set_rotation()"""
> return (g_cos*point[0] + g_sin*point[1], -g_sin*point[0] + 
> g_cos*point[1])
> 
> # graphics initializations
> frames, show = 0, True
> try:
> pygame.init()
> if full_screen:
> surf = pygame.display.set_mode(window_size, HWSURFACE | FULLSCREEN 
> | DOUBLEBUF)
> else:
> surf = pygame.display.set_mode(window_size)
> 
> t0 = pygame.time.get_ticks()
> while True:
> 
> 
> for event in pygame.event.get():
> if event.type == KEYDOWN:
> if event.key == K_ESCAPE:
> raise Exception()
> elif event.type == MOUSEBUTTONDOWN: frames, show = 0, False
> elif event.type == MOUSEBUTTONUP: frames, show = 0, True
> 
> 
> 
> for circ in circles:
> c = (circle_scale*circ[0], circle_scale*circ[1])
> if show:
> col = (150, 150, 0)
> pygame.draw.circle(surf, col, coord(c), circle_radius, 0)
> else:
> step = 150/disapp_frames
> lev = max(0, 150 - frames*step)
> col = (lev, lev, 0)
> if lev > 0:
> pygame.draw.circle(surf, col, coord(c), circle_radius, 
> 0)
> 
> for event in pygame.event.get():
>   
> if event.key == K_LEFT:
> delta -= delta_step
> if event.key == K_RIGHT:
> delta += delta_step
> 
> if show:
> col = (150, 150, 0)
> pygame.draw.circle(surf, col, coord(c), 
> circle_radius, 0)
> else:
> step = 150/disapp_frames
> lev = max(0, 150 - frames*step)
> col = (lev, lev, 0)
> if lev > 0:
> pygame.draw.circle(surf, col, coord(c), 
> circle_radius, 0)
> 
> 
> pygame.draw.circle(surf, grid_color, coord((0, 0)), fix_radius)
> pygame.display.flip()
> frames += 1
> 
> 
> 
> 
> finally: pygame.quit()
> 
> Thank you very much !
> 
> 
Franc Dernons code works, your issue was that you were calling
pygame.event.get() twice in one frame.
The first pygame.event.get() was stealing the keyboard events from teh
second, so the second WAS working, just not getting events. If you ran
this at an insanely slow rate you could give events separately to each
loop and see the odd effect. He consolidated the loops together so
event.get() was called only once.


-- 
O< ascii ribbon campaign - stop html mail - www.asciiribbon.org


[pygame] Re: Python optimization help

2012-01-19 Thread Silver
On 1/19/2012 5:33 PM, Silver wrote:
> On 1/19/2012 5:32 PM, Silver wrote:
>> I'm trying to speed up this program as much as possible. Anyone able to
>> help?
>>
>>
> Waugh. Old version...

Oddly enough, lowering the amount of extra workers in the pool results
in a higher speed?


[pygame] Re: Python optimization help

2012-01-19 Thread Silver
On 1/19/2012 5:32 PM, Silver wrote:
> I'm trying to speed up this program as much as possible. Anyone able to
> help?
> 
> 
Waugh. Old version...
import pygame
import random

import multiprocessing
import time
import math

width = 1000
height = 800

x = 0


class Consumer(multiprocessing.Process):

def __init__(self, task_queue, result_queue):
multiprocessing.Process.__init__(self)
self.task_queue = task_queue
self.result_queue = result_queue

def run(self):
proc_name = self.name
while True:
next_task = self.task_queue.get()
if next_task is None:
# Poison pill means we should exit
print '%s: Exiting' % proc_name
break
#print '%s: %s' % (proc_name, next_task)
answer = next_task[0](*next_task[1])
self.result_queue.put(answer)
return


class Task(object):
def __init__(self, a, b):
self.a = a
self.b = b
def __call__(self):
time.sleep(0.1) # pretend to take some time to do our work
return '%s * %s = %s' % (self.a, self.b, self.a * self.b)
def __str__(self):
return '%s * %s' % (self.a, self.b)



def end():
for i in xrange(num_consumers):
tasks.put(None)


def attract(itemlist): ## primary functin
gravitar = itemlist[1]
itemlist = itemlist[0]
exc = 0
for i in itemlist:
if i.id != gravitar.id:
if gravitar.mass > i.mass:
greatermass = gravitar.mass
else:
greatermass = i.mass
xdiff = gravitar.x - i.x  
ydiff = gravitar.y - i.y
dist = math.sqrt((xdiff**2)+(ydiff**2))
if dist < greatermass:
dist = greatermass


#landmark
acceleration = ((2*(i.mass*gravitar.mass))/(dist**2)) / 
gravitar.mass

xc = xdiff/dist
yc = ydiff/dist
gravitar.dx -= acceleration * xc
gravitar.dy -= acceleration * yc
else:
exc += 1
if exc > 1:
#print "Exc is" + str(exc)
pass
#raise ValueError, exc
gravitar.x += gravitar.dx
gravitar.y += gravitar.dy
if gravitar.x > width or gravitar.x < 0:
gravitar.dx *= -1
if gravitar.y > height or gravitar.y < 0:
gravitar.dy *= -1
gravitar.dx *= .999
gravitar.dy *= .999
return gravitar






class Gravitar(object):
def __init__(self, id):
self.id = id
self.x = random.random()*width
self.y = random.random()*height
self.dx = 0
self.dy = 0
self.mass = random.randint(4,8)

def genlist():
n = []
global x
for i in xrange( 2):
n.append(Gravitar(i))
x += 1

return n

if __name__ == '__main__':

pygame.init()
screen = pygame.display.set_mode((width, height))


# Establish communication queues


pool = multiprocessing.Pool(processes = 12)

# Enqueue jobs


# Add a poison pill for each consumer
result = genlist()
lastx = x
# Start printing results
while True:
## blit all here
if x != lastx:
print x
lastx = x
   

screen.fill((0,0,0))
#print result
for item in result:
pygame.draw.circle(screen, (255,255,255), ( int(item.x), 
int(item.y)), int(item.mass))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
x += 1 
result.append(Gravitar(x))


#print "Mapping..."
result = [[result,i] for i in result]
res = pool.map_async(attract, result)
result = []
#print "Calculating frame"
#print res
result = res.get()
#print result

[pygame] Python optimization help

2012-01-19 Thread Silver
I'm trying to speed up this program as much as possible. Anyone able to
help?


import pygame
import random

import multiprocessing
import time
import math

width = 1000
height = 800

x = 0


class Consumer(multiprocessing.Process):

def __init__(self, task_queue, result_queue):
multiprocessing.Process.__init__(self)
self.task_queue = task_queue
self.result_queue = result_queue

def run(self):
proc_name = self.name
while True:
next_task = self.task_queue.get()
if next_task is None:
# Poison pill means we should exit
print '%s: Exiting' % proc_name
break
#print '%s: %s' % (proc_name, next_task)
answer = next_task[0](*next_task[1])
self.result_queue.put(answer)
return


class Task(object):
def __init__(self, a, b):
self.a = a
self.b = b
def __call__(self):
time.sleep(0.1) # pretend to take some time to do our work
return '%s * %s = %s' % (self.a, self.b, self.a * self.b)
def __str__(self):
return '%s * %s' % (self.a, self.b)



def end():
for i in xrange(num_consumers):
tasks.put(None)


def attract2(itemlist): ## primary functin
gravitar = itemlist[1]
itemlist = itemlist[0]
exc = 0
for i in itemlist:
if i.id != gravitar.id:
if gravitar.mass > i.mass:
greatermass = gravitar.mass
else:
greatermass = i.mass
xdiff = gravitar.x - i.x  
ydiff = gravitar.y - i.y
dist = math.sqrt((xdiff**2)+(ydiff**2))
if dist < greatermass:
dist = greatermass


#landmark
acceleration = ((2*(i.mass*gravitar.mass))/(dist**2)) / 
gravitar.mass

xc = xdiff/dist
yc = ydiff/dist
gravitar.dx -= acceleration * xc
gravitar.dy -= acceleration * yc
else:
exc += 1
if exc > 1:
#print "Exc is" + str(exc)
pass
#raise ValueError, exc
gravitar.x += gravitar.dx
gravitar.y += gravitar.dy
if gravitar.x > width or gravitar.x < 0:
gravitar.dx *= -1
if gravitar.y > height or gravitar.y < 0:
gravitar.dy *= -1
gravitar.dx *= .999
gravitar.dy *= .999
return gravitar



def attract(itemlist):  ### secondary function
gravitar = itemlist[1]
itemlist = itemlist[0]
exc = 0
for i in itemlist:
if i.id != gravitar.id:
if gravitar.mass > i.mass:
greatermass = gravitar.mass
else:
greatermass = i.mass
greatermass **=2
xdiff = gravitar.x - i.x  
ydiff = gravitar.y - i.y
dist = (xdiff**2)+(ydiff**2)
if dist < greatermass:
dist = greatermass


#landmark
acceleration = ((2*(i.mass*gravitar.mass))/(dist)) / gravitar.mass

xc = xdiff/dist
yc = ydiff/dist
gravitar.dx -= acceleration * xc
gravitar.dy -= acceleration * yc
else:
exc += 1
if exc > 1:
#print "Exc is" + str(exc)
pass
#raise ValueError, exc
gravitar.x += gravitar.dx
gravitar.y += gravitar.dy
if gravitar.x > width or gravitar.x < 0:
gravitar.dx *= -1
if gravitar.y > height or gravitar.y < 0:
gravitar.dy *= -1
gravitar.dx *= .999
gravitar.dy *= .999
return gravitar


class Gravitar(object):
def __init__(self, id):
self.id = id
self.x = random.random()*width
self.y = random.random()*height
self.dx = 0
self.dy = 0
self.mass = random.randint(4,8)

def genlist():
n = []
global x
for i in xrange( 2):
n.append(Gravitar(i))
x += 1

return n

if __name__ == '__main__':

pygame.init()
screen = pygame.display.set_mode((width, height))


# Establish communication queues


pool = multiprocessing.Pool(processes = 12)

# Enqueue jobs


# Add a poison pill for each consumer
result = genlist()
lastx = x
# Start printing results
while True:
## blit all here
if x != lastx:
print x
lastx = x
   

screen.fill((0,0,0))
#print result
for item in result:
pygame.draw.circle(screen, (255,255,255), ( int(item.x), 
int(item.y)), int(item.mass))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
x += 1 
result.append(Gravitar(x))


#print "Mapping..."
result = [[result,i] for i in result]
re

[pygame] Re: Help

2012-01-17 Thread Silver
On 1/17/2012 8:20 PM, Silver wrote:
> Ok, so I got multicore working and didn't kil my pc. However, the
> threads aren't really doing what I want them to do. anyone know why The
> main python process amx's out and the rest are left at ~1% cpu?
> 
> (I have many cores, so one core isn't the issue)
Never mind, got it working using Pool.

I get like 1 fps with maxed out cpu. WOOO!

(It is like... oh.. ~100,000,000 operations per frame..)


[pygame] Help

2012-01-17 Thread Silver
Ok, so I got multicore working and didn't kil my pc. However, the
threads aren't really doing what I want them to do. anyone know why The
main python process amx's out and the rest are left at ~1% cpu?

(I have many cores, so one core isn't the issue)
import pygame
import random

import multiprocessing
import time
import math

width = 1000
height = 800



class Consumer(multiprocessing.Process):

def __init__(self, task_queue, result_queue):
multiprocessing.Process.__init__(self)
self.task_queue = task_queue
self.result_queue = result_queue

def run(self):
proc_name = self.name
while True:
next_task = self.task_queue.get()
if next_task is None:
# Poison pill means we should exit
print '%s: Exiting' % proc_name
break
#print '%s: %s' % (proc_name, next_task)
answer = next_task[0](*next_task[1])
self.result_queue.put(answer)
return


class Task(object):
def __init__(self, a, b):
self.a = a
self.b = b
def __call__(self):
time.sleep(0.1) # pretend to take some time to do our work
return '%s * %s = %s' % (self.a, self.b, self.a * self.b)
def __str__(self):
return '%s * %s' % (self.a, self.b)



def end():
for i in xrange(num_consumers):
tasks.put(None)


def attract(itemlist, gravitar):
for i in itemlist:
if i.id != gravitar.id:
xdiff = gravitar.x - i.x  
ydiff = gravitar.y - i.y
dist = math.sqrt((xdiff**2)+(ydiff**2))
force = 2*(i.mass*gravitar.mass)/(dist**2)
acceleration = force / gravitar.mass
xc = xdiff/dist
yc = ydiff/dist
gravitar.dx -= acceleration * xc
gravitar.dy -= acceleration * yc
gravitar.x += gravitar.dx
gravitar.y += gravitar.dy
if gravitar.x > width or gravitar.x < 0:
gravitar.dx *= -1
if gravitar.y > height or gravitar.y < 0:
gravitar.dy *= -1
gravitar.dx *= .999
gravitar.dy *= .999
return gravitar

class Gravitar(object):
def __init__(self, id):
self.id = id
self.x = random.random()*width
self.y = random.random()*height
self.dx = 0
self.dy = 0
self.mass = random.randint(1,6)

def genlist():
n = []
for i in xrange( 2000):
n.append(Gravitar(i))
return n

if __name__ == '__main__':

pygame.init()
screen = pygame.display.set_mode((width, height))


# Establish communication queues


tasks = multiprocessing.Queue()
results = multiprocessing.Queue()

# Start consumers
num_consumers = multiprocessing.cpu_count() * 8
print 'Creating %d consumers' % num_consumers
consumers = [ Consumer(tasks, results)
  for i in xrange(num_consumers) ]
for w in consumers:
w.start()

# Enqueue jobs


# Add a poison pill for each consumer
result = genlist()

# Start printing results
x = 0
while True:
## blit all here

x += 1

screen.fill((0,0,0))
for item in result:
pygame.draw.circle(screen, (255,255,255), ( int(item.x), 
int(item.y)), int(item.mass))
x = -1
for gtar in result:
x += 1
tasks.put([attract,[result, gtar]])
was = len(result)
result = []
print "Calculating frame"
while True:
pygame.event.get()
pygame.display.update()
result.append(results.get())
print len(result), "/", was
if len(result) == was:
break

Re: [pygame] Antialiased circle

2012-01-17 Thread Silver
On 1/17/2012 12:17 PM, Nick Arnoeyts wrote:
> Oh, here it is;
> http://www.pygame.org/docs/ref/gfxdraw.html#pygame.gfxdraw.aacircle
> 
> Op 17 januari 2012 21:16 schreef Nick Arnoeyts  het
> volgende:
> 
>> If you want C++, I believe you'd have to use SDL_gfx / SDL_Draw or work
>> with pure pixels.
>>
>> For pygame, look at the primitives module, I believe.
>>
>> Op 17 januari 2012 21:14 schreef Silver  het
>> volgende:
>>
>> Does SDL have a function for this?
>>>
>>
>>

Thanks to both who answered!



[pygame] Antialiased circle

2012-01-17 Thread Silver
Does SDL have a function for this?


Re: [pygame] Capturing Multiple Keyboard Inputs

2012-01-16 Thread Silver
On 1/16/2012 11:35 AM, Radomir Dopieralski wrote:
> On Mon, Jan 16, 2012 at 20:22, Silver  wrote:
>> On 1/15/2012 8:16 PM, Ian Mallett wrote:
>>> On Sun, Jan 15, 2012 at 7:46 PM, Ryan Strunk  wrote:
>>>
>>>> Hello everyone,
>>>> I am testing my understanding of the pygame.key module by creating a
>>>> program
>>>> that pans the sound of a car engine and raises/lowers its frequency. While
>>>> the individual keys do exactly what they're supposed to, I run into a big
>>>> problem when I try to do two things at once. For example, if I hold the up
>>>> arrow, the frequency of the sound rises with no problem. If I then hold
>>>> down
>>>> the left arrow while still holding up, however, the frequency stops rising
>>>> and the pan begins to adjust itself. How can I make both keys carry out
>>>> their assigned task at the same time?
>>>> As a side note, aside from exporting the redundant code below into its own
>>>> methods, are there any other ways to check for multiple keys without giving
>>>> each its own if check?
>>>> Ugly code is below:
>>>>
>>>> import pygame
>>>> from sound_lib.stream import FileStream
>>>> from sound_lib.output import Output
>>>>
>>>> def main():
>>>>clock = pygame.time.Clock()
>>>>o = Output()
>>>>sound = FileStream(file="sounds/car.wav")
>>>>screen = pygame.display.set_mode((640, 400))
>>>>sound.looping = True
>>>>sound.play()
>>>>pygame.key.set_repeat(50, 50)
>>>>while(True):
>>>>for event in pygame.event.get():
>>>>if event.type == pygame.KEYDOWN:
>>>>if event.key == pygame.K_UP:
>>>>sound.frequency += 200
>>>>if event.key == pygame.K_DOWN:
>>>>sound.frequency -= 200
>>>>if event.key == pygame.K_LEFT:
>>>>if sound.pan <= -0.9:
>>>>sound.pan = -0.9
>>>>else:
>>>>sound.pan -= 0.1
>>>>if event.key == pygame.K_RIGHT:
>>>>if sound.pan >= 0.9:
>>>>sound.pan = 0.9
>>>>else:
>>>>sound.pan += 0.1
>>>>if event.key == pygame.K_ESCAPE:
>>>>exit()
>>>>clock.tick(10)
>>>>
>>>> if __name__ == '__main__':
>>>>main()
>>>>
>>>> Thanks,
>>>> Ryan
>>>>
>>> You should use pygame.key.get_pressed() to check whether the left/up keys
>>> are pressed.  Something like:
>>>
>>> while pygame.event.get(): pass
>>> key = pygame.key.get_pressed()
>>> if key[K_LEFT]: #whatever
>>> if key[K_UP]: #whatever
>>>
>>> Ian
>>
>> OK, I am seriously confuzzled here. I thought that pygame.event.get()
>> gave you all the events, and that his code SHOULD capture multiple
>> keypresses.
> 
> It gives you all events. You get the even for pressing the first key,
> and you get the event for pressing the second key.
> You also get the events for releasing those keys later on. You can
> keep track of which keys are pressed that way, but pygame does that
> for you internally, so you can just get the state of all the keys with
> get_pressed, which is more convenient.
> 
>> What is the difference between get_pressed and event.get()?
> 
> The former gives you the states of all the keys (including keys like
> shift and ctrl), the latter gives you an event from the event queue.
> 
>> Oh, and would the key repeat be worth doing manually to see if that is
>> the issue?
> 
> If your game depends on the timing of those repeats, you will most
> certainly want to use pygame.Clock and do your own timing, instead of
> relying on event.get and the operating system's key repeat.
> 
>> soemthing like:
>>
>> waspressed = []
>> thisframepressed = []
>>
>> every frame:
>>thisframepressed = []
>>if event.key in waspressed:
>>## trigger again
>>thisframepressed.append(event.key)
>>else:
>>waspressed.append(event.key)
>>for i in waspressed:
>>if not i in thisframepressed:
>>waspressed.remove(i)
> 
> No, don't use events for that. Just run your main loop at a constant
> FPS with pygame.Clock and check for the key states with get_pressed
> regularly. Don't forget to pump the events though, or the window will
> become unresponsive.
Thanks a lot.


Re: [pygame] Capturing Multiple Keyboard Inputs

2012-01-16 Thread Silver
On 1/15/2012 8:16 PM, Ian Mallett wrote:
> On Sun, Jan 15, 2012 at 7:46 PM, Ryan Strunk  wrote:
> 
>> Hello everyone,
>> I am testing my understanding of the pygame.key module by creating a
>> program
>> that pans the sound of a car engine and raises/lowers its frequency. While
>> the individual keys do exactly what they're supposed to, I run into a big
>> problem when I try to do two things at once. For example, if I hold the up
>> arrow, the frequency of the sound rises with no problem. If I then hold
>> down
>> the left arrow while still holding up, however, the frequency stops rising
>> and the pan begins to adjust itself. How can I make both keys carry out
>> their assigned task at the same time?
>> As a side note, aside from exporting the redundant code below into its own
>> methods, are there any other ways to check for multiple keys without giving
>> each its own if check?
>> Ugly code is below:
>>
>> import pygame
>> from sound_lib.stream import FileStream
>> from sound_lib.output import Output
>>
>> def main():
>>clock = pygame.time.Clock()
>>o = Output()
>>sound = FileStream(file="sounds/car.wav")
>>screen = pygame.display.set_mode((640, 400))
>>sound.looping = True
>>sound.play()
>>pygame.key.set_repeat(50, 50)
>>while(True):
>>for event in pygame.event.get():
>>if event.type == pygame.KEYDOWN:
>>if event.key == pygame.K_UP:
>>sound.frequency += 200
>>if event.key == pygame.K_DOWN:
>>sound.frequency -= 200
>>if event.key == pygame.K_LEFT:
>>if sound.pan <= -0.9:
>>sound.pan = -0.9
>>else:
>>sound.pan -= 0.1
>>if event.key == pygame.K_RIGHT:
>>if sound.pan >= 0.9:
>>sound.pan = 0.9
>>else:
>>sound.pan += 0.1
>>if event.key == pygame.K_ESCAPE:
>>exit()
>>clock.tick(10)
>>
>> if __name__ == '__main__':
>>main()
>>
>> Thanks,
>> Ryan
>>
> You should use pygame.key.get_pressed() to check whether the left/up keys
> are pressed.  Something like:
> 
> while pygame.event.get(): pass
> key = pygame.key.get_pressed()
> if key[K_LEFT]: #whatever
> if key[K_UP]: #whatever
> 
> Ian

OK, I am seriously confuzzled here. I thought that pygame.event.get()
gave you all the events, and that his code SHOULD capture multiple
keypresses.

What is the difference between get_pressed and event.get()?

Oh, and would the key repeat be worth doing manually to see if that is
the issue?

soemthing like:

waspressed = []
thisframepressed = []

every frame:
thisframepressed = []
if event.key in waspressed:
## trigger again
thisframepressed.append(event.key)
else:
waspressed.append(event.key)
for i in waspressed:
if not i in thisframepressed:
waspressed.remove(i)


[pygame] a little help

2012-01-14 Thread Silver
Oops, got my rect width argument wrong... Never mind.


[pygame] A little help please

2012-01-14 Thread Silver
I need some help with a program that I'm trying to write with pygame.

I am having two issues:
* the squares aren't being drawn 1 px small so that they leave a black 
grid
* the squares on the edges are extending, even though I don't think I
told them to.

anyone know how to fix it?
import pygame
import math


squaresize = 64
sqsz = squaresize

width = 799
height = width

radius = .5*sqsz

pygame.init()

screen = pygame.display.set_mode((width,height))

while True:
pygame.event.get()
mousex = pygame.mouse.get_pos()[0]
mousey = pygame.mouse.get_pos()[1]
screen.fill((0,0,0))
for x in xrange(width/squaresize):
for y in xrange(height/squaresize):
hx = x
hy = y
hx *= sqsz
hy *= sqsz
#print hx,hy,sqsz, sqsz
nx = hx+(sqsz/2)-mousex
ny = hy+(sqsz/2)-mousey
nz = ((nx**2)+(ny**2))**.5
if nz == 0:
nz = .001#print nz
n = radius / nz
if n == 0:
n = .001
if n > 1:
n = 1

#print n
color = n*255
#print (color,color,color)
#print hx, hy, hx+15, hy+15
pygame.draw.rect(screen, (color,color,color), 
(hx,hy,hx+sqsz-1,hy+sqsz-1))
pygame.display.update()


Re: [pygame] Capabilities of Pygame

2012-01-12 Thread Silver
On 1/12/2012 5:45 PM, Ryan Strunk wrote:
> Hello everyone,
> 
> -[erased]
> 
> Ryan
> 
> 
Hey, as a veteran programmer, what I can say about python's speed is
that it is sufficient to do a very many of things.

With python/pygame the only speed issues I have run into are:
* Programming Language issues that can be fixed with common sense (such
as appending to a huge list, which reallocates the whole thing and takes
forever)
* running a huge for loop
* printing lots of text (expect more than a hundred print's a second to
bring significant slowness)
* Pixel logic. Not gonna lie, python is not so good here. Small images
can be done at speed, but anything larger is a pain. (my computer
comfortably does 80x80)
* 3D -- I personally avoid using python for 3d. I've tried numerous
times to get pyopengl working and failed.



If you wish to use arrays, I suggest using numpy.
For image processing, I suggest scipy.

Maybe something else will help too.

If you look into multiprocessing to split stuff into separate threads,
beware and look carefully at instructions to keep your system from
crashing. It's easy to miss one of the crucial details and windows does
not have a barrier in place to stop infinite process generation.


Re: [pygame] New way for drawing an arc

2012-01-05 Thread Silver
Just worked on trying to use AA. turns out the way I'm checking
locations, pixel-to-pixel, very few locations actually get caught by my
secondary checks. The effect is pretty much invisible.

Another way to do an arc would be to calculate the minimum outer circle
width between points, using a combination of the pythagorean theorem and
trigonometry, but I won't do it now. Maybe in the future.




Re: [pygame] New way for drawing an arc

2012-01-05 Thread Silver
On 1/5/2012 3:41 PM, Christopher Night wrote:
> 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
> 

Not yet, but currently I'm trying to incorporate antialiasing into my
function. This function in C should run at the speed the current
rotation function runs :).


Polygons.. Say, you could use an altered version of my function to
calculate the exact accuracy of polygon you'd need to get full
reproduction. Maybe you could use this idea?


[pygame] New way for drawing an arc

2012-01-05 Thread Silver
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
import math

def draw_arc_matrix(matrix, pos, radius, color, width, angle1, angle2):
#print "Drawing arc at", pos, "with radius of ", radius
for x in xrange(getmatrixwidth(matrix)):
for y in xrange(getmatrixheight(matrix)):
n = ((x-pos[0])**2 )+ ((y-pos[1])**2 )
if n > (radius-width)**2:
if n < (radius)**2:
## now to check arc
#print x,y
#setpoint(matrix, [x,y], color)
angle = math.atan2(y-pos[1], x-pos[0])
angle = math.degrees(angle)+180
#print angle, angle1, angle2
if angle1 > angle2:
if angle < angle1:
if angle > angle2:
setpoint(matrix, [x,y], color)
#print x,y
else:
if angle > angle1:
if angle < angle2:
#print x,y
setpoint(matrix, [x,y], color)
def setpoint(matrix, pos, color):
matrix.set_at(pos, color)

#matrix[pos[0]][pos[1]] = color
#return matrix

def getmatrixwidth(matrix):
# reurn len(matrix)
return matrix.get_rect().width

def getmatrixheight(matrix):
# return len(matrix[0])
return matrix.get_rect().height

if __name__ == "__main__":
import pygame
pygame.init()
screen = pygame.display.set_mode((200,200))
angle = 0
anglec = 1
while True:
anglec += .1
anglec %= 360
screen.fill((0,0,0))
draw_arc_matrix(screen, (100,100), 80, (255,255,255), 10, angle, anglec)
pygame.display.update()
pygame.event.get()