Re: [pygame] Tiling a Rotated Bitmap

2008-04-02 Thread Kamilche

Brian Fisher wrote:

So why do you need a rectangular tile to tile? why not tile a rotated
image on a rotated grid? (i.e. like with Pete's code)

The resulting tile can be any shape, I don't care. I may have coded it 
up wrong, but it appeared Pete's code resulted in something that didn't 
tile.


Do you spot a mistake in the app I posted?

--Kamilche




Re: [pygame] Tiling a Rotated Bitmap

2008-04-02 Thread Kamilche
Well, that was interesting, but also didn't work. It's similar to my 
attempt of tiling then rotating then cutting a piece out of the middle.


I've modified the code to show what happens when that tile is tiled. 
Interesting, tho!


--Kamilche

import pygame
import math

filename=r"G:\Incarnation\Models\Textures\test.png"
SCREENWIDTH = 800
SCREENHEIGHT = 600

def Rotated(surf, degrees = 0):
   # rotate surface
   rotsurf = pygame.transform.rotozoom(surf, degrees, 1)

   # compute the offsets needed
   c = math.cos(math.radians(degrees))
   s = math.sin(math.radians(degrees))
   widthx = (surf.get_width() - 1) * c
   widthy = (surf.get_width() - 1) * s
   heightx = (surf.get_height() - 1) * s
   heighty = (surf.get_height() - 1) * c


   # the 8 positions, corners first
   positions = [
   (widthx, -widthy),
   (-widthx, widthy),
   (heightx, heighty),
   (-heightx, -heighty),
   ]

   rot_copy = rotsurf.copy()

   # apply the blits
   for pos in positions:
   rotsurf.blit(rot_copy, pos)
   return rotsurf

def Tile(surf, pic, rect):
x = rect[0]
y = rect[1]
while y < rect[3]:
x = 0
while x < rect[2]:
surf.blit(pic, [x, y])
x += pic.get_width()
y += pic.get_height()


def main():
   pygame.init()
   bg = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT), 0, 32)

   quit = 0
   pic = pygame.image.load(filename).convert_alpha()
   pic2 = pic
   while not quit:
   bg.fill((255, 0, 0, 255))
   bg.blit(pic2, (0, 0))
   Tile(bg, pic2, [0, 200, 512, 512])
   pygame.display.flip()
   for e in pygame.event.get():
   if e.type == pygame.QUIT:
   quit = 1
   break
   elif e.type == pygame.MOUSEMOTION:
   pic2 = Rotated(pic, e.pos[0])

   pygame.quit()

main()


Re: [pygame] Tiling a Rotated Bitmap

2008-04-02 Thread Kamilche

Pete Shinners wrote:
I would expect you could do this. You'll need to rotate the surface, and 
 then blit it back onto itself 8 times with offsets. The offsets will be 
the rotated corners of the original image rect.




Yeah, it didn't work. It seems like it should, but run the following 
code (your code worked up into a program), and wave the mouse back and 
forth to change the angle.


Odd, huh? It's a tricky bit, apparently. The only hits I found on the 
internet were for software patents I didn't understand.


--Kamilche


import pygame
import math

filename=r"C:\Documents and Settings\Administrator\Desktop\batik.jpg"

SCREENWIDTH = 640
SCREENHEIGHT = 480

def Rotated(surf, degrees = 0):
# rotate surface
print 'Rotated ', degrees, ' degrees.'
rotsurf = pygame.transform.rotate(surf, degrees)

# compute the offsets needed
c = math.cos(math.radians(degrees))
s = math.sin(math.radians(degrees))
widthx = (surf.get_width() - 1) * c
widthy = (surf.get_width() - 1) * s
heightx = (surf.get_height() - 1) * s
heighty = (surf.get_height() - 1) * c

# the 8 positions, corners first
positions = [
(widthx + heightx, widthy + heighty),
(widthx - heightx, widthy - heighty),
(-widthx + heightx, -widthy + heighty),
(-widthx - heightx, -widthy - heighty),
(widthx, widthy),
(-widthx, -widthy),
(heightx, heighty),
(-heightx, -heighty),
]

# apply the blits
for pos in positions:
rotsurf.blit(rotsurf, pos)
return rotsurf

def main():
pygame.init()
bg = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT), 0, 32)

quit = 0
pic = pygame.image.load(filename).convert_alpha()
pic2 = pic
while not quit:
bg.fill((255, 0, 0, 255))
bg.blit(pic2, (0, 0))
pygame.display.flip()
for e in pygame.event.get():
if e.type == pygame.QUIT:
quit = 1
break
elif e.type == pygame.MOUSEMOTION:
pic2 = Rotated(pic, e.pos[0])

pygame.quit()

main()


Re: [pygame] I'm loving wills book :)

2008-04-02 Thread Kamilche

Lamonte(Scheols/Demonic) wrote:

that pygame book, its nice, anyone learn anything new?

Oh yeah, I was going to get that! Thanks for mentioning it. It took a 
while to come out!




Re: [pygame] Tiling a Rotated Bitmap

2008-04-01 Thread Kamilche
Well, basically, I want to take a picture, rotate it 15 degrees, and use 
some algorithm to jam all the pixels lying outside the bounding box back 
inside the box, and have the result be tilable.


I thought it should be possible, but it's a thornier problem than I 
realized.


--Kamilche


[pygame] Tiling a Rotated Bitmap

2008-04-01 Thread Kamilche
Hi all. I'm trying to create a rotated tilable bitmap out of a tilable 
bitmap, but it's not working. My first attempt was to tile the bitmap 
across a larger picture, rotate the larger picture, and then cut a tile 
out of the middle, but that didn't work - the resulting picture wasn't 
tilable.


I see that the problem is a lot more complex than I thought, and I don't 
have a handle on how to do it.


Does anyone know how to perform such a task?

--Kamilche


Re: [pygame] Perspective Test

2008-03-11 Thread Kamilche

Julia wrote:

As soon as I get some spare time I'm reverse engineering this Ian :)

On Mon, Mar 10, 2008 at 1:25 AM, Ian Mallett <[EMAIL PROTECTED] 
<mailto:[EMAIL PROTECTED]>> wrote:


My version.


Yeah, that was neat. Not really related to perspective tho - you should 
put it under its own title so it comes up in future searches!


I also enjoyed it.

--Kamilche



Re: [pygame] Perspective Test

2008-03-08 Thread Kamilche

Julia wrote:
Awesome code Kamilche. I really like it. I'm going to put it in my 
favorites folder :)




Thanks, glad you enjoyed it! I should probably mention I was inspired to 
create this code after reading an explanation of one point perspective 
at this site:


http://www.olejarz.com/arted/perspective



[pygame] Perspective Test

2008-03-07 Thread Kamilche
Here's a perspective test I wrote, that I thought others might find 
enjoyable. It illustrates a single-point perspective (a 'vanishing 
point'), and shows how a room with a floor, ceiling, door, and avatar 
changes as the vanishing point changes.



import pygame, os, sys, urllib

SCREENSIZE  = (1024, 768)
BACKCOLOR   = (150, 150, 150)
INVISIBLE   = (  0,   0,   0,   0)
PERSPECTIVECOLOR= (  0,   0,   0, 128)
PERSPECTIVEWIDTH= 2
WALLCOLOR   = (255, 128,   0, 220)
WINDOWCOLOR = (  0,  64, 200, 100)
DOORCOLOR   = (100,  64,  50, 200)
CEILINGCOLOR= (255, 255, 255, 255)
FLOORCOLOR  = (121,  74,  81, 255)
HORIZONCOLOR= (  0, 128,   0, 200)
VPCOLOR = (255,   0,   0, 255)
WALLDEPTH   = .35

VANISHINGPOINT  = (SCREENSIZE[0]/2, SCREENSIZE[1]/2)

bg = None
temp = None
girl = None

def CalculatePoint(depth, point):
xa, ya = VANISHINGPOINT
xb, yb = point
xbb = xa + depth * (xb-xa)
ybb = ya + depth * (yb-ya)
return int(xbb), int(ybb)

def Intersection(a,b,c,d):
Ax,Ay = a; Bx,By = b; Cx,Cy = c; Dx,Dy = d
u = float((Dx-Cx)*(Ay-Cy)-(Dy-Cy)*(Ax-Cx)) / 
float((Dy-Cy)*(Bx-Ax)-(Dx-Cx)*(By-Ay))

x = Ax + u*(Bx-Ax)
y = Ay + u*(By-Ay)
return int(x),int(y)

def DrawWall():
w, h = SCREENSIZE
topleft = CalculatePoint(WALLDEPTH, (0, 0))
topright = CalculatePoint(WALLDEPTH, (w, 0))
bottomleft = CalculatePoint(WALLDEPTH, (0, h))
bottomright = CalculatePoint(WALLDEPTH, (w, h))
pos = topleft
wallwidth = int(topright[0]-topleft[0])
wallheight = int(bottomleft[1]-topleft[1])
temp.fill(WALLCOLOR)
bg.blit(temp, topleft, [0, 0, wallwidth, wallheight])
pygame.draw.lines(bg, PERSPECTIVECOLOR, 1, [topleft, topright, 
bottomright, bottomleft], PERSPECTIVEWIDTH)


def DrawOrthogonals():
pygame.draw.line(bg, PERSPECTIVECOLOR, (0, 0), VANISHINGPOINT, 
PERSPECTIVEWIDTH)
pygame.draw.line(bg, PERSPECTIVECOLOR, (SCREENSIZE[0], 0), 
VANISHINGPOINT, PERSPECTIVEWIDTH)
pygame.draw.line(bg, PERSPECTIVECOLOR, (0, SCREENSIZE[1]), 
VANISHINGPOINT, PERSPECTIVEWIDTH)
pygame.draw.line(bg, PERSPECTIVECOLOR, SCREENSIZE, VANISHINGPOINT, 
PERSPECTIVEWIDTH)
pygame.draw.line(bg, HORIZONCOLOR, (0, VANISHINGPOINT[1]), 
(SCREENSIZE[0], VANISHINGPOINT[1]), PERSPECTIVEWIDTH)


def DrawDoor():
w, h = SCREENSIZE
topleft = CalculatePoint(.9, (0, .25*h))
topright = CalculatePoint(.7, (0, .25*h))
bottomleft = CalculatePoint(.9, (0, h))
bottomright = CalculatePoint(.7, (0, h))
pos = topleft
windowwidth = int(topright[0]-topleft[0])
windowheight = int(bottomleft[1]-topleft[1])
lst = [topleft, topright, bottomright, bottomleft, topleft]
temp.fill(INVISIBLE)
pygame.draw.polygon(temp, DOORCOLOR, lst)
bg.blit(temp, [0, 0])
pygame.draw.circle(bg, DOORCOLOR, topleft, 5)
pygame.draw.circle(bg, DOORCOLOR, topright, 5)
pygame.draw.circle(bg, DOORCOLOR, bottomright, 5)
pygame.draw.circle(bg, DOORCOLOR, bottomleft, 5)

def DrawCeiling():
w, h = SCREENSIZE
vx, vy = VANISHINGPOINT
numtiles = 8
for i in range(0, SCREENSIZE[0]+1, SCREENSIZE[0]/numtiles):
pygame.draw.line(bg, CEILINGCOLOR, (i, 0), VANISHINGPOINT, 1)

# Calculate horizontal lines
topright = CalculatePoint(WALLDEPTH, (w, 0))
for i in range(0, SCREENSIZE[0]+1, SCREENSIZE[0]/numtiles):
try:
x, y = Intersection((0, 0), topright, (i, 0), VANISHINGPOINT)
left = Intersection([0, y], [w, y], (0, 0), VANISHINGPOINT)
right = Intersection([0, y], [w, y], (w, 0), VANISHINGPOINT)
pygame.draw.line(bg, CEILINGCOLOR, left, right, 1)
except:
pass
#pygame.draw.line(bg, CEILINGCOLOR, (0, 0), topright, 1)

def DrawFloor():
w, h = SCREENSIZE
factor = 4
for i in range(-w*factor, w*2*factor, 100):
pygame.draw.line(bg, FLOORCOLOR, (i, h), VANISHINGPOINT, 1)

def DrawGirl():
w, h = SCREENSIZE
data = [(.8, (75, h)), (.9, (w/2+50, h)), (WALLDEPTH+.05, (150, h))]
data.sort()
for depth, dest in data:
pt = CalculatePoint(depth, dest)
resizedgirl = pygame.transform.rotozoom(girl, 0, depth)
bg.blit(resizedgirl, [pt[0]-resizedgirl.get_width()/2, 
pt[1]-resizedgirl.get_height()])

pygame.draw.circle(bg, (0, 0, 255), pt, 5)

def Text(s, _font = []):
if len(_font) == 0:
font = pygame.font.Font(None, 24)
_font.append(font)
font = _font[0]
shadow = font.render(s, 1, (0, 0, 0))
color = font.render(s, 1, (255, 255, 0))
w, h = color.get_size()
pic = pygame.Surface((w, h), pygame.SRCALPHA, 32).convert_alpha()
pic.fill(INVISIBLE)
pic.blit(shadow, [1, 1])
pic.blit(color, [0, 0])
return pic

def Draw():
bg.fill(BACKCOLOR)
DrawCeiling()
DrawFloor()
DrawOrthogonals()
DrawDoor()
DrawWall()
DrawGirl()
pygame.draw.circle(bg, VPCOLOR, VANISHINGPOI

Re: [pygame] Text To Speech PYTTS

2008-02-29 Thread Kamilche

Ian Mallett wrote:

That is an interesting effect...
Thanks for sharing!
I don't think that could be adapted to a game very well though.
Ian

You could have the genie do tts on all the chat stuff, mainly. Other 
than that, not much application.




Re: [pygame] Text To Speech PYTTS

2008-02-29 Thread Kamilche
I just posted an example on comp.lang.python about how to control the 
Microsoft Genie agent using Python, if you are interested.


--Kamilche


Re: [pygame] Ann: Pygame 1.8 SVN snapshot as Win32 installers

2008-01-27 Thread Kamilche

Brian Fisher wrote:

I'd be in favor of leaving SDL's current behavior (windib over
directX) unless we have a real compelling reason to do otherwise -
it's had 3 point releases since the change, and windib has continued
to improve while directX has not been used or developed. Also, I'm far
more interested in using a library that ensures compatibility and
correct functioning across a variety of computers than the most
performant one unless we are talking a really significant difference.

So is there a case where performance is significantly different? like
6 fps instead of 30?



On the machines I've tried, windib is faster than DirectX. I'm using a 3 
year old machine running Windows 2000, 2.6 ghz, so I can't vouch for 
machines older than that.


Some of my users couldn't play the game with DirectX as the default, it 
would err out, so I have the following snippet to force windib mode on 
my game:


if sys.platform == 'win32':
os.environ['SDL_VIDEODRIVER'] = 'windib'

Plus there were issues with how DirectX fed mouse input to Pygame. When 
you moved the mouse quickly, it would feed all the points between the 
last mousepoint and the new mousepoint to Pygame, resulting in sluggish 
behavior. I had to modify the mainloop to throw out all mousemove events 
except the last one each time through the mainloop to avoid slow 
redraws. With Windib, it was faster because it didn't feed every 
mousemove like; it would allow 'skips' for fast movement.


In my opinion, windib should be the default.

--Kamilche


Re: [pygame] When is pygame 1.8 coming out?

2008-01-24 Thread Kamilche

Marcus von Appen wrote:

too.

It's still not released ;-).



But don't you want beta testers? ;-)

Put it under a heading of 'beta' - that'd be good. We all know that 
means 'use at your own risk.'


--Kamilche


Re: [pygame] When is pygame 1.8 coming out?

2008-01-24 Thread Kamilche

Marcus von Appen wrote:

On, Thu Jan 24, 2008, Kamilche wrote:


Bo Jangeborg wrote:


[...]

What's stopping you from joining the developers ? It's a collaborative 
effort of volunteers as far as I know.


Bo)

I tried. I submitted some changes, some code samples, went to a Thursday 
online meeting - nothing came of it. In chat it was like I was invisible, 
and no one could hear me.


Maybe because they are on Tuesday ;-). 


I suppose it could have been on Tuesday, not Thursday. I don't recall as 
it's been over a year since I tried to contribute.


I worked all morning and got the pygame-ctypes examples whipped into 
shape.  I encountered several problems over and over again:


1. Requiring the programmer to set their PYTHONPATH to read the package. 
The end user won't be able to do this, so forcing that on the programmer 
to make theirs run just ensures it will break for the user in the future.


2. Importing Numeric, when everywhere in the documents you say use 
numpy. All the examples that claimed to be able to use either, would 
actually only work with Numeric. If you want us to use numpy, change all 
your examples to use numpy only, not this half-baked 'either or' that 
breaks when you don't have Numeric installed.


3. Checking for the sys.platform being 'windows' when it should actually 
be 'win32', which causes getlibc to fail.


4. Doing a 'return' in the middle of the event loop, which crashes 
Pygame on Windows.


5. Not calling pygame.quit at the end of the event loop, which crashes 
Pygame on Windows.


6. Not calling pygame.event.pump() in the event loop, which causes IDLE 
to hang.


Just so's ya know - that's what needs to be done.
Posting a link to the Windows installer for pygame 1.8 would be helpful, 
too.


--Kamilche



Re: [pygame] When is pygame 1.8 coming out?

2008-01-24 Thread Kamilche

Bo Jangeborg wrote:

Kamilche skrev:

Luke Paireepinart wrote:


Also - I was trying to make DLL's for Python in the past, and 
discovered the gnarly 'must have the same compiler Python was 
compiled with' error. Is that gone with Python 2.5?


Basically - if I go to the effort of making a vanilla C DLL, will it 
be callable from Python ctypes even though it was compiled with a 
different compiler? And will this C DLL work on all platforms, or 
will I have to recompile it for each platform and call different 
DLL's based on endianness?
I've used ctypes to interface with a few different DLLs, and some of 
them were compiled with mingW, I think, and I believe Python 2.5 is 
compiled with Visual Studio?
DLLs are only available on Windows.  They're called .so files on 
Linux (and probably mac too.)  Just add a line at the top of your 
script that determines using env vars what OS you're on, and load the 
correct file.  If it implements the same features across platforms 
you shouldn't have any problems.

How do I make a PYD file?
Don't you think it might be better to just work on pygame-ctypes a 
bit than to re-implement it?




Well, I suppose I could fix up all the broken references enough to try 
it out.  I just wish pygame was receptive to other people's ideas. 
I've submitted improvements to the examples before, and added features 
like cross-platform 'full screen mode', but they never got put into 
the software.


I'll take another look at pygame ctypes later today.

--Kamilche



What's stopping you from joining the developers ? It's a collaborative 
effort of volunteers as far as I know.


Bo)

I tried. I submitted some changes, some code samples, went to a Thursday 
online meeting - nothing came of it. In chat it was like I was 
invisible, and no one could hear me.


I was interested enough to help, but not interested enough to beg for 
admittance, which is apparently what it takes.


--Kamilche




Re: [pygame] When is pygame 1.8 coming out?

2008-01-24 Thread Kamilche

Luke Paireepinart wrote:


Also - I was trying to make DLL's for Python in the past, and 
discovered the gnarly 'must have the same compiler Python was compiled 
with' error. Is that gone with Python 2.5?


Basically - if I go to the effort of making a vanilla C DLL, will it 
be callable from Python ctypes even though it was compiled with a 
different compiler? And will this C DLL work on all platforms, or will 
I have to recompile it for each platform and call different DLL's 
based on endianness?
I've used ctypes to interface with a few different DLLs, and some of 
them were compiled with mingW, I think, and I believe Python 2.5 is 
compiled with Visual Studio?
DLLs are only available on Windows.  They're called .so files on Linux 
(and probably mac too.)  Just add a line at the top of your script that 
determines using env vars what OS you're on, and load the correct file.  
If it implements the same features across platforms you shouldn't have 
any problems.

How do I make a PYD file?
Don't you think it might be better to just work on pygame-ctypes a bit 
than to re-implement it?




Well, I suppose I could fix up all the broken references enough to try 
it out.  I just wish pygame was receptive to other people's ideas. I've 
submitted improvements to the examples before, and added features like 
cross-platform 'full screen mode', but they never got put into the 
software.


I'll take another look at pygame ctypes later today.

--Kamilche




Re: [pygame] When is pygame 1.8 coming out?

2008-01-23 Thread Kamilche

Lenard Lindstrom wrote:

Kamilche wrote:
Well, ctypes isn't as hard as I had feared. I've got an example 
running that blits some simple boxes and pictures to the screen. I 
must admit, getting it going did make use of my knowledge of the C 
programming language, tho.


I couldn't use pygame ctypes, because most of the examples were 
broken, and I just didn't want to figure out why. Instead, I wrote a 
module to interface to SDL directly, using the ctypes feature of 
Python 2.5. I was happily surprised to discover that SDL was just a 
single DLL!


I'm looking forward to getting into it more, and eliminating the 
installation intricacies and dependency on Pygame. If anyone's 
interested, I can post the example I've made when I get back home 
tonight.


I made a Windows installer available for Python 2.5 and Pygame 1.8rc3 
available in October. It is close to the SVN but lacks Numpy support. Is 
is available here:


http://www3.telus.net/len_l/pygame-1.8.0rc3.win32-py2.5.exe

Documentation is here:

http://www3.telus.net/len_l/pygame-1.8-docs.zip

Hope this helps.




Thanks, I'll check it out. Is this documented on the pygame website 
anywhere, and I just missed it?


I got the ctypes SDL version of my program humming along. I was happy as 
a clam until I tried to composite two RGBA pictures with per-pixel 
alpha. What's up with that? :-( Pygame was apparently holding my hand 
there, and I didn't know it until it got yanked away.


Are there many other tripups like that, where Pygame had to reimplement 
something SDL was doing poorly? If it was just the RGBA-RGBA 
compositing, it seems like a single C DLL would suffice, but I don't 
want to get into that if there's more bombs waiting to explode.


Also - I was trying to make DLL's for Python in the past, and discovered 
the gnarly 'must have the same compiler Python was compiled with' error. 
Is that gone with Python 2.5?


Basically - if I go to the effort of making a vanilla C DLL, will it be 
callable from Python ctypes even though it was compiled with a different 
compiler? And will this C DLL work on all platforms, or will I have to 
recompile it for each platform and call different DLL's based on 
endianness? How do I make a PYD file?


And will there be an afterlife when I die, or do old coders just fade 
away? :-D


--Kamilche


Re: [pygame] When is pygame 1.8 coming out?

2008-01-23 Thread Kamilche
Well, ctypes isn't as hard as I had feared. I've got an example running 
that blits some simple boxes and pictures to the screen. I must admit, 
getting it going did make use of my knowledge of the C programming 
language, tho.


I couldn't use pygame ctypes, because most of the examples were broken, 
and I just didn't want to figure out why. Instead, I wrote a module to 
interface to SDL directly, using the ctypes feature of Python 2.5. I was 
happily surprised to discover that SDL was just a single DLL!


I'm looking forward to getting into it more, and eliminating the 
installation intricacies and dependency on Pygame. If anyone's 
interested, I can post the example I've made when I get back home tonight.


--Kamilche


Re: [pygame] When is pygame 1.8 coming out?

2008-01-23 Thread Kamilche

Marcus von Appen wrote:

On, Wed Jan 23, 2008, Kamilche wrote:


Patrick Devine wrote:

On Jan 23, 2008 9:59 AM, Kamilche <[EMAIL PROTECTED]> wrote:

If it's still not available, what have people migrated to for their
Python 2.5 game development? Are they using ctypes with SDL, or something?

I thought everyone was using Pyglet now.  :-D

-pdev.

Well, I'm looking at using ctypes and SDL right now... wish me luck. Weird 
how pygame started going unsupported and I didn't even notice till now!


It's not unsupported and not dead. In fact we're working with high
pressure on getting 1.8 done and released. Maybe we're even able to do
it this year.

Regards
Marcus


Well, if there's no windows installer for it, and hasn't been for three 
years, how supported is it, really? It's too much to expect the average 
developer to have the same build tools and correctly compile all the 
sources, just to use the latest version.




Re: [pygame] When is pygame 1.8 coming out?

2008-01-23 Thread Kamilche

Patrick Devine wrote:

On Jan 23, 2008 9:59 AM, Kamilche <[EMAIL PROTECTED]> wrote:

If it's still not available, what have people migrated to for their
Python 2.5 game development? Are they using ctypes with SDL, or something?


I thought everyone was using Pyglet now.  :-D

-pdev.

Well, I'm looking at using ctypes and SDL right now... wish me luck. 
Weird how pygame started going unsupported and I didn't even notice till 
now!


I actually found a link for pygame 1.8 dated for 2005 - that's 3 years ago!



[pygame] When is pygame 1.8 coming out?

2008-01-23 Thread Kamilche
When is version 1.8 of pygame coming out? I went looking on the 
Internet, and saw lots of messages about 'any week now' dating back to 
2006.


What I need is a windows installer of pygame 1.8 that runs with Python 
2.5. I don't have all the prerequisite compilers and packages to compile 
my own version.


If it's still not available, what have people migrated to for their 
Python 2.5 game development? Are they using ctypes with SDL, or something?


--Kamilche


[pygame] Re: New GUI

2008-01-22 Thread Kamilche

Marcus wanted an example of how events could be handled better.
I've worked up an example of how the mainline code could look, if the
event handling were done using a more VB-like structure.

import kamgui

# This example creates a screen with 2 buttons and 3 labels.

# -
# App level features handled with this code:
# -
# Clicking the buttons updates the status label.
# Moving the mouse updates the mousepos label.
# The fps label is updated when the global 'FPS' event is fired.

# --
# Engine level 'automatic' features:
# --
# The buttons automatically hilight when you hover the
# mouse over them, and unhilight when you leave.

# Clicking the button sets the focus to the button,
# and draws it with a border around it and darker text.

# Events that are targeted to a specific control, propagate
# up the ownership hierarchy until the event is handled.
# If no control is listening, the event is silently ignored.

# Events that are sent to no specific control,
# are broadcast to all 'listening' controls.

# To make a control listen, simply add the event name to the
# 'events' listbox for that control. In this example,
# the app is listening for 'MousePos' and 'FPS.'

# All these engine level features are handled behind the scenes.



class MyApp(kamgui.App):
events = ['MousePos', 'FPS']

def On_Initialize(self, e):
' Create the controls '
self.mousepos = kamgui.Label(parent = self,
fontcolor = kamgui.constants.YELLOW)
button = kamgui.Button(parent = self, pos = [100, 100],
 name = 'DoNothing', caption = 'Do Nothing')
button = kamgui.Button(parent = self, pos = [150, 210],
name = 'DoSomething', caption = 'Do Something',
size = [200, 50])
self.fps = kamgui.Label(parent = self, text = 'FPS',
pos =(self.size[0], 0), align = 'r',
fontcolor = kamgui.constants.DKGREEN)
self.status = kamgui.Label(parent = self,
text = 'Welcome to KamGUI!',
pos = (0, self.size[1]), align = 'lb')

def On_Terminate(self, e):
' Quit the app'
print 'Quitting MyApp'

def On_FPS(self, e):
' Display FPS'
self.fps.SetText('%d FPS' % e.value)

def On_MousePos(self, e):
' Display current mouse position'
self.mousepos.SetText(e.pos)

def DoSomething_Click(self, e):
' Do something when button is clicked.'
self.status.SetText('Did something.')

def DoNothing_Click(self, e):
' Do nothing.'
self.status.SetText('Did nothing.')


MyApp().Run()



Re: [pygame] New GUI

2008-01-22 Thread Kamilche

Patrick Mullen wrote:


For a toolkit that can only be used in pygame, ignoring things like
pyopengl, python-ogre, etc, such limited use I don't see as being very
marketable.  If it was generalized, and pluginable to almost any
python program, that starts to have some real value.



True - being Pygame specific does greatly limit the market, I hadn't 
considered that. Thanks for the feedback!





Re: [pygame] New GUI

2008-01-22 Thread Kamilche

Casey Duncan wrote:

My own pygame dev being at the hobby-level, I can't say that I would 
have much interest in a commercial add-on to pygame myself. However, I 
would be interested in a high-level overview of what you found wrong 
with the existing guis and how your solution does not suffer from these 
perceived problems.


 From a business standpoint, you might have trouble marketing such a 
thing in the face of the incumbent free solutions, regardless of how 
superior it might be. The dual-pricing scheme that Laura mentioned could 
help encourage adoption. Another option might be two versions, a 
bare-bones open source library that is functional but has few bells and 
whistles (perhaps lacking the gui builder), and a commercial upgrade 
that has everything anyone could want.



Yeah, that's true. I wish there had been something like mine available 
at the time I started my project - I would certainly have used it and 
saved myself lots of trouble.


When push comes to shove, the worst drawback of all the Pygame GUI's, is 
not having a GUI builder. It's offensive to me, to have to write code to 
draw a screen!


I know lots of people would love this GUI I put out, and it existence 
would help promote the Python language as a whole. But you're right, 
there are lots of free GUI's out there. If I do end up making it 
available, I'll probably do something like 'free for free software 
projects, but if it's used in a commercial or shareware software 
project, there's a licensing fee of $100 per developer' or some such thing.


I'm not sure whether or not to release it. There's a difference between 
'Good enough to use in house' and 'Good enough to sell, complete with 
examples, documentation, and help.'


What I REALLY want, is people to collaborate on it with me, adding 
enhancements and new controls. I suppose I could just get it out there 
in base form, but with the licensing in place, and see if enough people 
are inspired by it to make it take off.


--Kamilche


Re: [pygame] New GUI

2008-01-22 Thread Kamilche

Marcus von Appen wrote:

On, Tue Jan 22, 2008, Kamilche wrote:

[Unhappiness about the existing GUIs]

It's interesting to see that a lot of people tell some public
list/forum/whatever how unhappy they are with existing solutions, but do
not dare to get into touch with any of the solution developers or even
describe the problem areas they see somewhere.

It explains, why there's so much lousy software on the market. People
just complaining, but not helping in any way.

Kamilche, as I am the OcempGUI head, I'd like to hear where exactly your
problems and expectation were (and still are) regarding an user interface
system for your applications and games.

Regards
Marcus


Sure. I've attached a more thorough critique of some of the features in 
Ocemp GUI, since you're interested.


General and UI Observations

In mnemonics, '#' is used to denote the accelerator key, instead of '&' 
- nonstandard. The mnemonics don't work with the right alt key, just the 
left alt key.


In radio buttons, multiline text is centered by default. It really 
should be left aligned.


There'e no 'pygame.quit' at the end, so after running, the examples hang 
and you have to manually close the DOS box. This makes them hang in IDLE 
as well.


The borders and window styles are non standard, and unattractive.
The font has hinting problems - a different font would be better.

There's no selection capability on the text edit boxes - you can't drag 
your mouse to select text, have it highlight, and do standard text 
editing on it.


Many examples are so simple as to be useless, such as the 'event.py' 
example. An event showing a button actually executing code when clicked 
would be good, instead of showing a 'picture of a button' in one example 
and showing an 'event that's raised' in another example.


In the 'example.py' application, the 'box' entry shows 4 items placed on 
top of each other. Clicking on the background items brings them to the 
foreground, and they never go back. Was that intentional? Why are they 
changing zorder? This is not obvious to me.


In the file dialog example, clicking '..' when at the top doesn't bring 
you to the list of drives. You have to manually overtype drive C with 
drive D using the limited editing capability allowed in the folder name box.


The image map example suffers from performance problems. Just moving the 
mouse over the imagemap box causes events to queue up and get rendered 
so slowly, you quickly wonder if the example is broken. A single swish 
of the mouse from left to right, and you have to wait 3 seconds for the 
display to catch up.


The sliders suffer a performance problem as well. Dragging the sliders 
isn't instant, you have to wait for it to catch up to the mouse.


The 'hello world' examples have an unpainted area to the right of the 
window, that is picking up whatever was underneath when the window was 
created.


The main window is not resizable.

The status bar is not recognizable as such, it looks like a frame with 
text in it. It needs to look like a status bar, and have multiple panels 
you can set.


The toggle buttons don't look any different than depressed normal 
buttons. Toggle buttons usually look significantly different than normal 
buttons, by such hints as having a different shape, different shading, 
or graphics on them as well.


There are no examples of an FPS indicator, a global event that several 
controls might want to handle.


The tooltip makes no attempt to stay on screen - it gets cut off on the 
right.


The window example is too small - it shows a single button that you can 
click. I would like to see window examples throughout the examples, not 
just this unrealistically simple example.


No fullscreen mode available.

No 3d option for the text.

No menus.

No way to enlarge/shrink controls when the window size changes.

Code Observations
-
I don't have time to critique all the example code, so I just ran 
through the 'radio.py' example.


'from ocempgui.widgets import *' - pollutes namespace

After creating a table, you must set the alignment explicitly for each 
row. Why not have the most common alignment, which is probably 
align_top, the default?


table.set_row_align (0, ALIGN_TOP)
table.set_row_align (1, ALIGN_TOP)

When creating radio buttons in a loop, you must specify the group 
manually with an if switch. Why not have all radio buttons that belong 
to the same parent, automatically in the same group?


btn = RadioButton (s, group)
if i == 0:
group = btn

By the end, you realize it requires 88 lines of code to create a simple 
screen that doesn't DO anything. Ideally, a GUI builder should build it 
for you and save the results to a file. In your code, you 

[pygame] New GUI

2008-01-22 Thread Kamilche
I've looked at wxPython, PGU, Ocemp GUI, PyUI, and other GUI toolkits 
available for Python. Each of them had, to my eyes, severe flaws that 
prevented me from using them for my apps. Therefore, I've spent many 
months developing my own GUI and event system.


The GUI has windowing, translucency, buttons, menus, slider bars, 
frames, and more. It has a drag n drop GUI builder. The controls can be 
'anchored', meaning when you resize the window, the controls resize 
automatically as well. It has an easy event handling system similar to 
VB6, but also the capability for controls to handle 'global' events.


I'm using it for a couple of commercial apps I'm making. I'm considering 
making the GUI itself available commercially, as well. I'm writing this 
email to gauge the level of interest in it.


If you're interested, respond in this thread. Pricing is an unknown - if 
you have thoughts in that area, I'd appreciate hearing them.


--Kamilche



Re: [pygame] Free chapter of my book

2007-10-12 Thread Kamilche

Ken Seehart wrote:

  Will McGugan wrote:

Horst JENS wrote:

I think that either the comment should say "in 10 frames"
or the randint statement should be randint(1,10).


correction:

or the ranint statement should be randint(1,20)

  

Ack! Well spotted. Never hard code values in to comments!

Will
A former employee where I work once said that it's better not to comment 
at all because all comments are fundamentally redundant and might become 
inconsistent with the code.  He proceeded to remove all comments.  
Naturally, he was a perl programmer :-)


Ken

Well, inconsistent comments are the worst. But as a broad overall 'what 
this area is supposed to do' bit, they're handy. When I'm tired, and 
looking for a spot to update, I tend to skim the comments until I hit 
the right area. I've been fooled by bad comments myself, tho, it happens 
sometimes. Comments should never be too specific.


--Kamilche




Re: [pygame] Code: Center of Triangle

2007-09-27 Thread Kamilche

DR0ID wrote:

Hi


def CalculateDistance(a, b):
x, y, z = b[0] - a[0], b[1] - a[1], b[2] - a[2]
dist = x*x + y*y + z*z
return dist * dist



no offense, but  "x*x + y*y + z*z" is already the distance squared, so
no need for "return dist*dist". (or did you do this on purpose?).

~DR0ID



Uh, yeah, good catch. :-)



[pygame] Code: Center of Triangle

2007-09-27 Thread Kamilche
Worked this up today for myself, thought I'd post it in case someone 
else found it useful.


import pygame

def CenterOfTriangle(A, B, C):
return  (A[0] + B[0] + C[0])/3.0, (A[1] + B[1] + C[1])/3.0, (A[2] + 
B[2] + C[2])/3.0


def CalculateDistance(a, b):
x, y, z = b[0] - a[0], b[1] - a[1], b[2] - a[2]
dist = x*x + y*y + z*z
return dist * dist

def NearestVert(triangle, pos):
distance = 
v = -1
for i in range(len(triangle)):
temp = CalculateDistance(triangle[i], [pos[0], pos[1], 0])
if temp < distance:
distance = temp
v = i
assert(v >= 0)
return v

def main():
pygame.init()
screen = pygame.display.set_mode([640, 480], 0, 32)
quit = 0

triangle = [[132, 319, 0], [282, 120, 0], [434, 319, 0]]
center = CenterOfTriangle(*triangle)

v = -1
font = pygame.font.Font(None, 18)
pic = font.render('Center: %d, %d, %d Triangle: %s' % 
(int(center[0]), int(center[1]), int(center[2]), triangle), 1, (0, 0, 0))


while not quit:
screen.fill((255, 255, 255))
pygame.draw.polygon(screen, (0, 0, 0), [triangle[0][:2], 
triangle[1][:2], triangle[2][:2]], 1)

x, y, z = int(center[0]), int(center[1]), int(center[2])
screen.fill((255, 0, 0), [x-2, y-2, 4, 4])
screen.blit(pic, [0, 450])
pygame.display.flip()
pygame.event.pump()
for e in pygame.event.get():
if e.type == pygame.QUIT:
quit = 1
break
elif e.type == pygame.MOUSEBUTTONDOWN:
v = NearestVert(triangle, e.pos)
elif e.type == pygame.MOUSEMOTION:
if v > -1:
triangle[v] = [e.pos[0], e.pos[1], 0]
center = CenterOfTriangle(*triangle)
pic = font.render('Center: %d, %d, %d Triangle: %s' 
% (int(center[0]), int(center[1]), int(center[2]), triangle), 1, (0, 0, 0))

elif e.type == pygame.MOUSEBUTTONUP:
v = -1

pygame.quit()

main()



Re: [pygame] refresh problem

2007-09-06 Thread Kamilche
Lots of people forget to put 'pygame.event.pump()' in the main loop. Try 
that, see if it stabilizes.


Re: [pygame] Not Quiting

2007-07-01 Thread Kamilche

Luke Paireepinart wrote:

Lenard Lindstrom wrote:
Normally it does. So I wonder if IDLE doe something unusual like 
intercept SystemExit. If the shell is restarted with a crtl-F6 the 
pygame window closes.

Yeah, I agree that it's an IDLE problem, not a pygame bug.





To make it work best with IDLE, also call 'pygame.event.pump()' every 
time through the main loop. Between that and calling 'pygame.quit()' at 
the end, all works fine.


--Kamilche



Re: [pygame] Not Quiting

2007-06-30 Thread Kamilche

Ian Mallett wrote:
By code I mean any program that works otherwise, by it crashes I mean I 
have to quit using the taskmanager and endtask, and by how I quit I mean


keystate = pygame.key.get_pressed()
for event in pygame.event.get():
  if event.type == pygame.QUIT or keystate[K_ESCAPE]: 
sys.exit()




You should definitely 'pygame.quit()' before you quit the program.


Re: [pygame] Starting Window Position

2007-06-28 Thread Kamilche

Ian Mallett wrote:
My name is Ian.  The full story on this is that I sent the message from 
my computer and then it sent a reply email saying it didn't work.  I 
sent my message to my friend, Ken, who is also on the mailing list to 
see if he could get better results.  As soon as he had sent my message, 
both messages appeared in our mailboxes, so Ken sent the "opps" message 
on my behalf.  Check the archives?  Will do.  I'll tell you if I find 
anything.


On 6/27/07, *Luke Paireepinart* <[EMAIL PROTECTED] 
> wrote:


Ken Seehart wrote:
 > Doh! Sorry about the duplicate post...
YOU BETTER BE!
Just kidding.
Don't worry about it, not a big deal.
Kinda confusing on what your name really is, though O_O;
I would suggest, KenIan (is that pronounced like Kenyan?), to check the
Pygame mailing list archives first.
I believe I remember seeing this question a few months ago.
I wouldn't doubt it has something to do with SDL environment variables.
If your search proves fruitless, I'm sure someone else will have he;lp,
but if you do succeed, let us know so we don't go answering a question
you already answered yourself :)
-Luke



if sys.platform == 'win32':
#os.environ['SDL_VIDEO_WINDOW_POS'] = '3,23' or
os.environ['SDL_VIDEO_CENTERED'] = '1'



Re: [pygame] Text-Based RPG

2007-06-19 Thread Kamilche

Kris Schnee wrote:


What's different about the tavern versus a regular room? Most likely 
it's just some variables that you might as well put into a single Room 
class. For instance, if a room can be light or dark, you could give the 
Room class a "light" variable by putting in the __init__ function:
self.light = options.get("light",True) ## Which makes True the default 
value




Or:

class Room(object):
name = 'Room'
light = 1


class Tavern(Room):
name = 'Tavern'
light = 0


Then, at startup time, store the type of the room in the data, so you 
know which variable to instantiate at startup time.


It's a matter of preference, but I don't like stuffing data into 
variables on __init__ unless I have to.


Re: [pygame] OK, I'm starting this whole thing over again...

2007-06-11 Thread Kamilche

Dave LeCompte (really) wrote:

"Charles Joseph Christie II" <[EMAIL PROTECTED]> asked:




For me, I find that writing code a second time goes faster, because I've
learned a lot of lessons. Writing it a third or fourth time is just
tedious, though.


Heh, that's true, but those versions are better than the second version, 
so sometimes, it's worth your while.


Only when you KNOW the next version will be lots better, should you 
rewrite. You'll know because you'll want to forge ahead, but keep 
stumbling over old bad programming choices.


If you don't know what's wrong, and don't know how to proceed, you need 
to debug instead of rewrite.


Incremental development is good! Don't code for a week without testing 
it, then try to figure out why it's not working - instead build a simple 
bit that can stand alone, such as space ships floating down from the 
screen, and test it. When that's working, add a fighter craft that moves 
left-right at the bottom controlled by arrow keys. When that's working, 
add a single bullet that floats up when you press the spacebar, and 
disappears. When that's working, work on making the collision routine 
between the single bullet and the spaceship. When that's working, add an 
explosion to the spaceship.


In general, I like to put no more than a couple of hours of coding in, 
before testing. If you find you NEED to code for days on end before you 
can test, it's probably because you don't have the code broken down into 
enough classes and modules.


Good luck!

--Kamilche



Re: [pygame] 3D sample code

2007-06-08 Thread Kamilche

Will McGugan wrote:

  [EMAIL PROTECTED]  wrote:

On Thu, June 7, 2007 2:45 pm, Horst JENS wrote:
  

On Mon, 2007-06-04 at 21:19 +0100, Will McGugan wrote:

  

I've just posted some sample code for using OpenGL with PyGame. Hope
you find it interesting.

http://www.willmcgugan.com/2007/06/04/opengl-sample-code-for-pygame/

  

that's exactly what i was looking for... thanks!


It is interesting. Am I right in understanding that you basically have to
choose between Pygame's normal (SDL) drawing functions, like surface.blit,
and OpenGL's? You can't just draw a 3D scene like that of the code above,
and then blit an interface or text atop it. Instead you have to switch to
a 2D mode, turn your Pygame drawing into an OpenGL texture, and draw a
rectangle textured with the new drawing -- and delete/replace the texture
every time you want to change something. That's so cumbersome that I've
barely ever gotten it to work; is there a better way to integrate OpenGL
and Pygame graphics?
  
You're right that you cant use any of the regular SDL drawing functions 
with OpenGL - or any other accelarated 3D API. You can work with 2D 
graphics in OpenGL though, by drawing texture quads. If you wrap that in 
a simplified interface, then the code doesn't look much different from 
what you are used to in 2D PyGame.


Will


Is there a way to render 3d objects out to disk only, and use the 
renders in a normal Pygame program? Is there any advantage to doing so, 
in speed, or memory, or anything?







Re: [pygame] QuadMap

2007-06-07 Thread Kamilche

DR0ID wrote:

nice!

Some comments would be appreciated. Is it an affine transformation? The 
hit test look like  raytracing code; how does it work?




Well, no can do - I'm looking stuff up in books and online, and barely 
understanding this myself. For instance - you must specify the 
quadrilateral corners in topleft, bottomleft, bottomright, topright 
order for the picture to be upright - why's that? Specifying them in a 
different order gives various flipping and mirroring effects... but 
sometimes it crashes. Anyways, if you can figure it out, let me know. :-D


But what I can give you, is a more interesting version that textures the 
quadrilaterals.


import pygame, math, Numeric

WIDTH   = 800
HEIGHT  = 600

BLACK   = (  0,   0,   0, 255)
WHITE   = (255, 255, 255, 255)
RED = (255,   0,   0, 255)
YELLOW  = (255, 255,   0, 255)
BLUE= (  0,   0, 255, 255)
GREEN   = (  0, 255,   0, 255)
GRAY= (212, 208, 200, 255)
MAGENTA = (255,   0, 255, 255)

class Mesh(object):
quads = None
texture = None
posx = 0
posy = 0

def __init__(self):
self.pic = pygame.Surface([WIDTH, HEIGHT], pygame.SRCALPHA, 
32).convert_alpha()

self.quads = []

def Add(self, quads):
self.quads.append(quads)

def Texture(self, texture):
quad = None
w, h = self.pic.get_size()
tw, th = texture.get_size()
array = pygame.surfarray.pixels3d(texture)
alpha = pygame.surfarray.pixels_alpha(texture)
myarray = pygame.surfarray.pixels3d(self.pic)
myalpha = pygame.surfarray.pixels_alpha(self.pic)
for quad in self.quads:
for y in range(quad.miny, quad.maxy):
for x in range(quad.minx, quad.maxx):
offset = quad.PointToOffset([x, y])
if offset:
x1 = int((tw-1) * offset[0])
y1 = int((th-1) * offset[1])
myarray[x, y] = array[x1, y1]
myalpha[x, y] = alpha[x1, y1]

def Draw(self, bg):
bg.blit(self.pic, [self.posx, self.posy])
for quad in self.quads:
quad.Draw(bg)

def PointToOffset(self, pos):
for quad in self.quads:
offset = quad.PointToOffset(pos)
if offset:
return offset
return None

def OffsetToPoint(self, offset):
for quad in self.quads:
quad.point = quad.OffsetToPoint(offset)

class Quad(object):
data  = None
point = None

def __init__(self, p1, p2, p3, p4):
self.p1 = list(p1)
self.p2 = list(p2)
self.p3 = list(p3)
self.p4 = list(p4)
self.polys = [self.p1, self.p2, self.p3, self.p4]
self.minx = 9
self.maxx = -1
self.miny = 9
self.maxy = -1
for x, y in self.polys:
self.minx = min(self.minx, x)
self.maxx = max(self.maxx, x)
self.miny = min(self.miny, y)
self.maxy = max(self.maxy, y)

def Draw(self, bg):
pygame.draw.line(bg, RED,self.p1, self.p2, 1)
pygame.draw.line(bg, YELLOW, self.p2, self.p3, 1)
pygame.draw.line(bg, BLUE,   self.p3, self.p4, 1)
pygame.draw.line(bg, GREEN,  self.p4, self.p1, 1)
if self.point:
pygame.draw.rect(bg, MAGENTA, [self.point[0]-2, 
self.point[1]-2, 4, 4], 0)


def OffsetToPoint(self, offset):
if offset == None:
return None
s, t = offset
x1, y1 = self.p1
x2, y2 = self.p2
x3, y3 = self.p4
x4, y4 = self.p3
xa = x1 + t * (x2 - x1)
ya = y1 + t * (y2 - y1)
xb = x3 + t * (x4 - x3)
yb = y3 + t * (y4 - y3)
X = xa + s * (xb - xa)
Y = ya + s * (yb - ya)
return int(X), int(Y)

def PointToOffset(self, pos):
x, y = pos[0], pos[1]
if not (x >= self.minx and x <= self.maxx and y >= self.miny 
and y <= self.maxy):

return None
x1, y1 = self.p1
x2, y2 = self.p2
x3, y3 = self.p4
x4, y4 = self.p3

Ax = x2 - x1
Ay = y2 - y1
Bx = x4 - x3
By = y4 - y3
Cx = x3 - x1
Cy = y3 - y1
Dx = x  - x1
Dy = y  - y1
Ex = Bx - Ax
Ey = By - Ay

a = -Ax * Ey + Ay * Ex
b = Ey * Dx - Dy * Ex + Ay * Cx - Ax * Cy
c = Dx * Cy - Dy * Cx

det = b * b - 4 * a * c
if det >= 0:
if abs(a) < 0.001:
t = -c / float(b)
else:
t = (-b - math.sqrt(det)) / float(2 * a)
denom = (Cx + Ex * t)
if denom > 0.01:
s = (Dx - Ax * t) / float(denom)
else:
s = (Dy - Ay * t) / float(Cy + Ey * t)

if (t >= 0) and (t <= 1) and  (s >= 0) and (s <= 1):
return s, t

def LoadPic(filename = 'test2.jpg'):
try:
pic = pygame.image.load(filenam

[pygame] QuadMap

2007-06-06 Thread Kamilche
Here's a program that will map points from one quadrilateral to another 
quadrilateral:


import pygame, math

WIDTH   = 800
HEIGHT  = 600

BLACK   = (  0,   0,   0, 255)
WHITE   = (255, 255, 255, 255)
RED = (255,   0,   0, 255)
YELLOW  = (255, 255,   0, 255)
BLUE= (  0,   0, 255, 255)
GREEN   = (  0, 255,   0, 255)

class Quad(object):
data = None
point = None
def __init__(self, p1, p2, p3, p4):
self.p1 = list(p1)
self.p2 = list(p2)
self.p3 = list(p3)
self.p4 = list(p4)

def Render(self, bg):
pygame.draw.line(bg, RED,self.p1, self.p2, 1)
pygame.draw.line(bg, YELLOW, self.p2, self.p3, 1)
pygame.draw.line(bg, BLUE,   self.p3, self.p4, 1)
pygame.draw.line(bg, GREEN,  self.p4, self.p1, 1)
if self.point:
pygame.draw.rect(bg, BLACK, [self.point[0]-2, 
self.point[1]-2, 4, 4], 0)


def SetPoint(self, offset):
if offset == None:
self.point = None
return
s, t = offset
x1, y1 = self.p1
x2, y2 = self.p2
x3, y3 = self.p4
x4, y4 = self.p3
xa = x1 + t * (x2 - x1)
ya = y1 + t * (y2 - y1)
xb = x3 + t * (x4 - x3)
yb = y3 + t * (y4 - y3)
X = xa + s * (xb - xa)
Y = ya + s * (yb - ya)
self.point = X, Y

def HitTest(self, pos):
x, y = float(pos[0]), float(pos[1])
x1, y1 = self.p1
x2, y2 = self.p2
x3, y3 = self.p4
x4, y4 = self.p3

Ax = x2 - x1
Ay = y2 - y1
Bx = x4 - x3
By = y4 - y3
Cx = x3 - x1
Cy = y3 - y1
Dx = x  - x1
Dy = y  - y1
Ex = Bx - Ax
Ey = By - Ay

a = -Ax * Ey + Ay * Ex
b = Ey * Dx - Dy * Ex + Ay * Cx - Ax * Cy
c = Dx * Cy - Dy * Cx

det = b * b - 4 * a * c
if det >= 0:
if abs(a) < 0.001:
t = -c / float(b)
else:
t = (-b - math.sqrt(det)) / float(2 * a)
denom = (Cx + Ex * t)
if denom > 0.01:
s = (Dx - Ax * t) / float(denom)
else:
s = (Dy - Ay * t) / float(Cy + Ey * t)

if (t >= 0) and (t <= 1) and  (s >= 0) and (s <= 1):
return s, t


class Square(Quad):
def __init__(self, posx, posy, width, height):
p1 = posx, posy
p2 = posx + width, posy
p3 = posx + width, posy + height
p4 = posx, posy + height
super(Square, self).__init__(p1, p2, p3, p4)


def main():
pygame.init()
bg = pygame.display.set_mode([WIDTH, HEIGHT], 0, 32)
quit = 0
data = []
data.append( Quad([ 20,  50], [120,  30], [150, 110], [ 10, 130]) )
data.append( Square(200, 20, 100, 100) )
data.append( Quad([210, 170], [250, 260], [100, 240], [120, 150]) )
while not quit:
bg.fill(WHITE)
for quad in data:
quad.Render(bg)
pygame.display.flip()
pygame.event.pump()
moved = 0
for e in pygame.event.get():
if e.type == pygame.QUIT:
quit = 1
break
elif e.type == pygame.MOUSEMOTION:
if not moved:
moved = 1
for quad in data:
offset = quad.HitTest(e.pos)
if offset:
break
for quad in data:
quad.SetPoint(offset)
pygame.quit()


main()


Re: [pygame] Slow performance in fullscreen mode

2007-06-05 Thread Kamilche

Brian Bull wrote:


Yes, this worked fine, thank you Kamiche.



You're welcome, glad it worked for you also!


Re: [pygame] Slow performance in fullscreen mode

2007-05-31 Thread Kamilche

Brian Bull wrote:

Hi,

My Pygame app runs fine in windowed mode, using 


pygame.display.set_mode((1024,768))


But when I switch to fullscreen mode with


pygame.display.set_mode((1024,768),pygame.FULLSCREEN)


the display looks fine but the app speed slows down dramatically. Perhaps the 
problem is that Pygame is emulating an absent video mode in some form? 1024 x 
768 is supposed to be one of the video modes of this monitor...

Does anyone have any suggestions please? I would like to be able to use 
fullscreen 1024x768 without the performance hit...

Thanks
A. 


"The information contained in this transmission is confidential. It is intended for 
the named address only. If you are not the named address you may not copy, distribute or 
take any action in reliance upon this transmission"


Try throwing away all but the first mouse movement, each time through 
the loop. That sped up my app significantly... as it turned out, full 
screen mode was sending every xy change to the app, whereas windowed 
mode was throwing away samples between mouse movements (the preferred 
behavior.)


Example:

Windowed mode during a fast mousemove might send:

1-1, 5-5

Fullscreen mode was sending something like this:

1-1, 1-2, 2-2, 3-2, 3-3, 4-3, 4-4, 5-4, 5-5



Re: [pygame] Website move

2007-05-27 Thread Kamilche

Phil Hassey wrote:
The pygame.org website was recently moved to a new server and had some 
troubles ... Sorry it took me a few days to get to fixing it - I was in 
the middle of a moving myself!


Anyway - I think everything is fixed now, if you notice any more SQL 
errors showing up, please tell me.


Thanks!
Phil

Moody friends. Drama queens. Your life? Nope! - their life, your story.
Play Sims Stories at Yahoo! Games. 



Thanks Phil! We appreciate your hard work.



Re: [pygame] Choppy sound playback

2007-05-08 Thread Kamilche

Chris Smith wrote:
Help! I'm getting very choppy sound playback on my code. Here's a quick 
example:


#!/usr/bin/python

import pygame

pygame.init()
pygame.mixer.init (44100,-16,True,4096)
foo=pygame.mixer.Sound("sound.ogg")
foo.set_volume(1)
foo.play()

Sound plays, but like a very dirty record, with lots of digi-noise. 
Sound on other programs works fine; any obvious issues that anyone can 
think of?


-- Chris
--
Science is open source religion



Try the following:

pygame.mixer.quit()
pygame.mixer.init(44100, -16, 2, 4096)

That third parameter should be 1 for mono, and 2 for stereo.

If that still doesn't do it for you, try turning the volume down to .5 
on the channel.


--Kamilche


Re: [pygame] sound crackling and fmod

2007-04-30 Thread Kamilche
He's right - pygame.mixer.pre_init and all that doesn't appear to help, 
at least on my Windows 2000 machine. I left it in just in case it helps 
on some platforms tho.


I found what DID help, was setting the channel volume down to .5. One 
song I have perfectly illustrated the problem, when I played it on both 
pygame and windows media player. In Pygame, it sounded like it was 
overdriving the computer speakers, but when I played it in Windows Media 
Player, it was perfect, but quieter. I put 2 and 2 together, and reduced 
the volume, and got much better results.


The final result is a little worse than Windows Media Player, but at 
least it's not grating to the ears any more.


--Kamilche


Re: [pygame] about the great 100% CPU thread

2007-04-30 Thread Kamilche

Laura Creighton wrote:

My note about that did not get out due to my company and domain name
changing.

The pypy project has destroyed several machines so far in its 2 year history.
Mostly laptops, but at least one tower as well.  We're using all the CPU for
extended periods of time, and when we talk to manufacturers about it,
often about claims because the machine is under warrantee, they all ask
us what the heck we have been doing.  We tell them.  And they tell us that
their machines are not designed to run at 100% CPU for extended periods of
time.

However, should James Paige decide that despite all of this his dual
mac _still_ isn't having enough fun, we could send him some nightly
pypy builds.  That ought to do the trick. :-)

Laura






No way! It's amazing that computer manufacturers build a machine that 
can't run full-bore 24 hours a day, 365 days a year. Well, I can believe 
it for laptops, sure, they've always had a heating problem, but towers 
too? Planned obsolescence sucks. :-P


I hope you got them all replaced under warranty.

--Kamilche


[pygame] Re: Europython - FREE VACATION!

2007-04-28 Thread Kamilche

Laura Creighton wrote:

Hope to see you there,
Laura Creighton

Wow! Free vacaton for  certain people! (hint hint). Too bad I don't have 
any 'referreed papers.' :-( What IS a referreed paper?


But if I were one of the people she was hinting about, I'd certainly be 
bustling about submitting one. Assuming the travel stipend covers plane 
fare, lodging, and food, of course.


--Kamilche



Re: [pygame] Fugu's Friend

2007-04-27 Thread Kamilche

Will McGugan wrote:


Wow! Nice work. A+ for the A*! :-)

I noticed that turtle can't fit through the diagonal spaces between 
blocks. Must be the hard shell!


Actually, that was intentional. The first time I encountered an astar 
pathfinding routine written in Pygame, it let them 'cheat' by going 
between diagonally lined up blocks. You can disallow it by having your 
routine check diagonal blocks in addition to blocks to the left and 
right. It has a side effect of allowing the path to go in a diagonal 
direction too.



Feeling a blog coming on...


I'll have to go check it out! I like your blog. :-)

--Kamilche



[pygame] Fugu's Friend

2007-04-26 Thread Kamilche
Well, I was inspired by Fugu, so I wrote a variation of it called 
"Fugu's Friend" that displays an animated turtle that rotates to face 
the correct direction for movement, toggles fullscreen mode on 
alt-enter, displays info such as FPS and current mouse position, lets 
you toggle a 'game throttle' to avoid 100% cpu usage, lets you change 
the speed at which the turtle swims, and lets you change paths whenever 
you click, throwing away the old path and starting a new path.


I hope you find it entertaining or useful.

http://www.kamilche.com/files/fugusfriend.zip


--Kamilche


Re: [pygame] Sub-pixel rendering

2007-04-25 Thread Kamilche
Well, color me interested. There's not enough pages devoted to advanced 
topics such as pathfinding and particle effects, in most game books.


Throw in a 'line of sight' pathfinding routine that uses polygons 
instead of pixels for its map, or a particle engine with several 
examples, and I'm there! ;-)


--Kamilche


Re: [pygame] Sub-pixel rendering

2007-04-25 Thread Kamilche

Will McGugan wrote:

Hi folks,

I've just posted a module to do sub-pixel blitting with 2D PyGame. 
Hopefuly someone will find it useful!


http://www.willmcgugan.com/2007/04/25/going-sub-pixel-with-pygame/

Regards,

Will McGugan





Wow. That's really beautiful, thanks for posting it! That is such a 
complex particle effect you got going there... I went looking for the 
pages of code it took to create it, and found the few paltry lines. :-D


Have you ever considered working up a variety of special effects and 
selling them to other coders? I'd buy them, if the price were 
reasonable. You've obviously got the maths to do it. ;-)


--Kamilche


Re: [pygame] Path finding demo, now with more fugu

2007-04-20 Thread Kamilche

Will McGugan wrote:

Hi folks,

Just put a path finding demo on my website, that you may find interesting.

http://www.willmcgugan.com/2007/04/20/swim-fugu-swim/

Regards,

Will McGugan




Ooh, your pathfinding demo is addicting. Fugu swims very well indeed!

And by the way - your blog states that you enjoy juggling technology 
women. I'm a technology woman - but you'd have to find 2 others before 
you could juggle us. ;-)


--Kamilche


Re: [pygame] pygame standard mouse

2007-04-19 Thread Kamilche

Wahid Marditama wrote:

Hi all,

I find the standard mouse in pygame is slow when display is set to 
fullscreen. Anyway around this? Or, is there a good 'virtual' mouse 
code? I tried writing one but it does not work as expected.


Wahid


Yeah, I had that happen too. The way I fixed it was in my main loop, I 
throw away all mouse movements except one. This forces you to update the 
mouse once per loop, instead of many times per loop. DirectX appears to 
be feeding every XY transformation to the event loop, instead of 'most 
recent coordinates' as happens in windowed mode.


For simplicity, I throw all away except the first one. If you wanted to 
be more accurate, you should probably throw away all except the LAST 
movement. That way you're always guaranteed of being up to date.


--Kamilche


Re: [pygame] Location of Pygame Window

2007-03-28 Thread Kamilche

Kris Schnee wrote:
A weird question for you. What determines the location on-screen of the 
Pygame graphics window? I find it appears in unpredictable locations, 
sometimes going past the edge of the screen so that I have to drag it 
into place to see the whole thing. Is there a way to give it a constant 
starting location?


Kris





os.environ['SDL_VIDEO_WINDOW_POS'] = '3,23'

or

os.environ['SDL_VIDEO_CENTERED'] = '1'



Re: [pygame] PyWeek #4 in April!

2007-03-08 Thread Kamilche

Patrick Mullen wrote:

The problem with this, and it has been discussed before, is that those who
have extensive (internal, or even external but not well documented or
supported) libraries start off with a huge advantage over those who come
into it fresh.  There are quite a few pretty extensive libraries that 
are in

fact allowed, and you can use your own library as well if you document it,
release it well in advance of the contest, and get it approved.  I've been
working on a massively multiplayer game for a year and a half.  Now I'm
going to take that, put in some models that fit the theme, and call it a
day.  Not so good...

The idea of the contest is sort of to put everyone on a level playing 
field,

and allow freedom of experimentation.  I don't know about some people, but
when I am limited on time I tend to come up with very unique code design
that I don't often use in my full projects, sometimes I even learn 
something

from it besides just having a good time :)

A week really is enough time to accomplish some great things or at least a
great start to a new project.  More time than that and it's too easy to put
things off or have feature creep really set in, less time is just too
rushed; although that's an experience in itself.



Well, that keeps it a competition instead of an exhibition. I would like 
to see more advanced games than you can get with only 1 week of effort, 
but that's asking too much of people. A nice tradeoff would be to let 
them use code they've developed in the past as part of their project.


Just my 2 cents worth. I'd be happy to see your online game in the 
competition, as long as you included the source code. :-D


--Kamilche



Re: [pygame] PyWeek #4 in April!

2007-03-08 Thread Kamilche

Richard Jones wrote:

PyWeek #4 will run in the first week of April:

 Start: 00:00UTC Sunday 1st April
Finish: 00:00UTC Sunday 8th April
 


REGISTRATION IS OPEN

Visit the PyWeek website for more information: 

  http://pyweek.org/ 



THE PYWEEK CHALLENGE: 

- Invites all Python programmers to write a game in one week from scratch 
  either as an individual or in a team, 
- Is intended to be challenging and fun, 
- Will hopefully increase the public body of python game tools, code and 
  expertise, 
- Will let a lot of people actually finish a game, and 
- May inspire new projects (with ready made teams!) 

Entries must be developed during the challenge, and must incorporate some 
theme decided at the start of the challenge. The rules for the challenge are 
at: 

  http://media.pyweek.org/static/rules.html 



Richard 



The limitation of not using pre-existing libraries and artwork is a 
deterrent. You might be able to talk more game creators with advanced 
skills into competing, if those limitations didn't exist.


I think you should allow pre-existing libraries, but only if they supply 
the source code with the game. To me, this contest is more of a 'watch 
how I code' exhibition more than anything, and I think it would be fun 
to loosen the rules to let more advanced game creators participate.


--Kamilche



[pygame] AACircle

2007-02-26 Thread Kamilche
Hi all, I've written an antialiased circle routine that creates a 
surface 2x as large as requested, blits a circle to it, then shrinks it 
down to size. The reason I made it is because the 
pygame.transform.rotozoom doesn't make a perfect looking circle.


Here it is. Any suggestions on how to make it more efficient would be 
appreciated. In particular, I suspect the loop that comes after the line 
'Add the pixels values to a temporary array' could be made more 
efficient with Numeric, but I don't know Numeric well enough to know how 
to do that.


--Kamilche



def AACircle(radius = 10, antialias = 2, color = [255, 128, 0], width = 0):
' Paint a circle'
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
d = radius * 2
r2 = radius * antialias
d2 = r2 * 2

# Create surface twice the size (or more)
pic = pygame.Surface([d2, d2], 0, 8)
pic.set_palette([[x, x, x] for x in range(256)])
pic.fill(BLACK)

# Draw the circle on the large picture
pygame.draw.circle(pic, WHITE, [r2, r2], r2, width)

# Add the pixel values to a temporary array
array = Numeric.zeros((d, d), Numeric.Int)
srcarray = pygame.surfarray.pixels2d(pic)
for x in range(d2):
for y in range(d2):
array[x/antialias][y/antialias] += srcarray[x][y][0]
array /= antialias * antialias

# Create the final surface
pic2 = pygame.Surface([d, d], pygame.SRCALPHA, 32).convert_alpha()
pic2.fill(color)
pygame.surfarray.pixels_alpha(pic2)[:, :] = array.astype(Numeric.UInt8)

# Return the final surface
return pic2



Re: [pygame] pygame is a disgrace

2007-02-15 Thread Kamilche

Jer Juke wrote:

Yeah, you heard me

> (snip)
...these people are a disgrace and a detriment to 

> python game development efforts on the whole.




You're not impressing anybody with your vicious attack on people who 
maintain and support Pygame. You're doing them a great disservice, and 
ensuring YOU will never receive any support from people who read this 
mailing list.


--Kamilche


Re: [pygame] Perspective Transform Quad

2007-02-01 Thread Kamilche
Well, thanks for the info. I thought as much. I think I'll give it a 
miss - I don't need it badly enough to require OpenGL to be included as 
well.


--Kamilche


[pygame] Perspective Transform Quad

2007-02-01 Thread Kamilche

I have a need to tile a bitmap across an arbitrary quadrilateral, and
apply perspective to it.
The Python Imaging Library (PIL) has an undocumented function that
might work, but I can't figure out how to make it work. You're
supposed to pass it 8 parameters, a b c d e f g h .

What I want is to take a rectangular texture map and 'flop it down on
the floor' - pinch in the left and right with perspective, and squash
down the top with perspective. I've modified those 8 parameters and
examined the results, but that hasn't brought me any closer to my
goal.

The PIL function is this:

im2 = im.transform(im.size, Image.PERSPECTIVE, (1, 0, 0, 0, 1, -100,
0, .001), Image.BILINEAR)

Here's hoping someone can shed some light on this function!


Re: [pygame] Pixel Perfect collision suggestion.

2007-01-30 Thread Kamilche

V. Karthik Kumar wrote:
I happened to read the changes list a day ago. I saw the code, I thought 
that this change might help detect regular pp cols faster.


This version keeps checking pixels from the outer rectangle of the 
colliding area to the inner. It works considerably faster when objects 
are regular and convex, which is often the case.


This isn't a patch as such, I'd recommend people try it out and report 
the results and then decide.


Regards,
Karthik




def pp_collide(obj1,obj2):
"""If the function finds a collision it will return True
if not it will return False.
"""
rect1, rect2, hm1, hm2 = obj1.rect, obj2.rect, obj1.hitmask, obj2.hitmask
if not rect1.colliderect(rect2):
return False
rect = rect1.clip(rect2)

w, h, x1, y1, x2, y2 = rect.width, rect.height, rect.x-rect1.x, 
rect.y-rect1.y, rect.x-rect2.x, rect.y-rect2.y

while w > 0 and h > 0:
for x in range(w):
if hm1[x1+x][y1] and hm2[x2+x][y2]:
return True
if hm1[x1+x][y1+h-1] and hm2[x2+x][y2+h-1]:
return True
for y in range(1, h-1):
if hm1[x1][y1+y] and hm2[x2][y2+y]:
return True
if hm1[x1+w-1][y1+y] and hm2[x2+w-1][y2+y]:
return True
w, h, x1, y1, x2, y2 = w-2, h-2, x1+1, y1+1, x2+1, y2+1
return False


Is it faster than pygame's builtin rect.collidepoint method?


Re: [pygame] Masking Test: Simulated Lighting (Follow-Up)

2007-01-21 Thread Kamilche

Kris Schnee wrote:

Kamilche wrote:

Try the following code. It uses a gradient light.


I'm trying to figure out how your example (much better than mine) works. 
It looks like the key is the last line of this function:



def RefreshNight(night, alpha, light, x, y):
a = NIGHTCOLOR[3]
alpha.fill([a, a, a])
r = LIGHTSIZE/2
alpha.blit(light, [x-r, y-r])
pygame.surfarray.pixels_alpha(night)[:, :] = 
pygame.surfarray.pixels2d(alpha)


So, to get around the problem of a pre-drawn lightmask not getting 
properly put onto the dark mask, you're using the surfarray module to 
address the alpha channel of the dark mask directly? Is that how this 
works? I don't recognize the [:,:] syntax -- a list containing two 
copies of a list, maybe.


I tried using a version of that line instead of directly blitting my 
lightmask onto dark, but Python complained that it couldn't safely cast 
the array. I guess there's some trick to how the surfaces are defined, 
but I haven't been able to figure it out yet.


Kris



The easiest way to grok it, is to save the image of the gradient I 
create in the CreateLight function.


That last line copies the picture of the grayscale light gradient plus 
desired night level, to the alpha channel of the final nighttime 
picture. The color never changes on the nighttime picture - just the 
alpha channel.


--Kamilche


Re: [pygame] Masking Test: Simulated Lighting (Follow-Up)

2007-01-21 Thread Kamilche

Kris Schnee wrote:
But a problem appeared in trying to make the process more efficient, by 
drawing a lightmask on its own, once, then each blitting it onto the 
black mask, then blitting the black mask onto the screen. Doing it that 
way would be better for complex, gradient lights such as the big one 
seen in my previous code. That is, you'd make a (radius*2,radius*2) 
surface that's black with a gradually-shaded circle of translucency, 
once, then blit it onto solid black each frame. But when I tried that,
Pygame took me too literally. 


Try the following code. It uses a gradient light.

import pygame

SCREENSIZE = [800, 600]
LIGHTSIZE = 400
NIGHTCOLOR = [0, 0, 0, 200]

def CreateLight():
gradient = pygame.Surface([LIGHTSIZE, LIGHTSIZE], 0, 8)
gradient.set_palette([[x, x, x] for x in range(256)])
a = NIGHTCOLOR[3]
gradient.fill((a, a, a))
r = LIGHTSIZE/2
for i in range(r):
c = (a * (r-i))/r
pygame.draw.circle(gradient, [c, c, c], [r, r], r-i)
c -= 1
return gradient

def CreateBackground():
bg = pygame.Surface(SCREENSIZE, pygame.SRCALPHA, 32).convert_alpha()
bg.fill((0, 0, 128, 255))
bg.fill((255, 0, 0, 255), (50, 50, 100, 100))
return bg

def CreateNight():
pic = pygame.Surface(SCREENSIZE, pygame.SRCALPHA, 32).convert_alpha()
pic.fill(NIGHTCOLOR)
return pic

def CreateAlpha():
pic = pygame.Surface(SCREENSIZE, 0, 8)
pic.set_palette([[x, x, x] for x in range(256)])
a = NIGHTCOLOR[3]
pic.fill([a, a, a])
return pic

def RefreshNight(night, alpha, light, x, y):
a = NIGHTCOLOR[3]
alpha.fill([a, a, a])
r = LIGHTSIZE/2
alpha.blit(light, [x-r, y-r])
pygame.surfarray.pixels_alpha(night)[:, :] = 
pygame.surfarray.pixels2d(alpha)


def main():
pygame.init()
screen = pygame.display.set_mode(SCREENSIZE, 0, 32)
bg = CreateBackground()
circle = CreateLight()
night = CreateNight()
alpha = CreateAlpha()
done = 0
x, y = 400, 300
while not done:
RefreshNight(night, alpha, circle, x, y)
screen.blit(bg, (0, 0))
screen.blit(night, (0, 0))
pygame.display.flip()
pygame.event.pump()
for event in pygame.event.get():
if (event.type == pygame.QUIT) or \
   (event.type == pygame.KEYDOWN and event.key == 
pygame.K_ESCAPE):

done = True
break
elif event.type == pygame.MOUSEMOTION:
x, y = event.pos
pygame.quit()

main()


Re: [pygame] Load Graphics 30x faster than pygame.image.load

2007-01-20 Thread Kamilche
Yeah, loading from DVD, CD, or even HD without enough RAM would 
significantly change those numbers.


I didn't load the same file over and over - I loaded a random file from 
an alway-open FD, but the file the FD pointed to only had 100 pictures 
in it.


Still it would be nice to load them all at once, but alas, the game 
has way too many graphics to do that with. I'm going to have to think 
harder about room scripting.


Right now the problem is the animations are jerky as one stops and 
another begins. This was not apparent until room scripting was put in. 
I'll have to preload all the animations for a script, or load them in a 
separate thread, or something.


--Kamilche


Re: [pygame] Load Graphics 30x faster than pygame.image.load

2007-01-20 Thread Kamilche

Luke Paireepinart wrote:

Kamilche wrote:

Bob Ippolito wrote:

That doesn't seem to make any sense... you've already loaded the
picture, why convert it to a string just to convert it back to a
picture? It's using up about the same amount of RAM as a string or as
an image object.



Assume the string is read from disk, instead of doing a pygame image 
load. The speed bump truly surprised me!


So every time you change your graphics you have to run a separate script 
to convert the images to strings?
It seems like this introduces unneeded complexity since your graphics 
shouldn't be loading at runtime anyway, except
perhaps in your case in a MMORPG where you may want small loading times 
(to the point where the user won't notice it

or at least fast enough that you don't need a loading screen.)

--Kamilche






Well, I estimate I'll have 180,000 or so graphics. I'm hoping it will 
fit on a single DVD by the time I'm done; obviously, loading them all at 
runtime isn't an option.


--Kamilche


Re: [pygame] Load Graphics 30x faster than pygame.image.load

2007-01-20 Thread Kamilche

Bob Ippolito wrote:

That doesn't seem to make any sense... you've already loaded the
picture, why convert it to a string just to convert it back to a
picture? It's using up about the same amount of RAM as a string or as
an image object.



Assume the string is read from disk, instead of doing a pygame image 
load. The speed bump truly surprised me!


--Kamilche


[pygame] Load Graphics 30x faster than pygame.image.load

2007-01-19 Thread Kamilche
I discovered a technique for loading graphics quickly using Pygame, 
about 30x faster than a straight pygame.image.load.


The gist of it is convert the picture to a string with

   s = pygame.image.tostring(pic, 'RGBA')
   w, h = pic.get_size()

and later, when loading, use
   pygame.image.frombuffer(s, [w, h], 'RGBA')

Unfortunately, I can't use it in my current project, because I need to 
access the color palette of 256 color images. I can't use this technique 
to store and load these palettized images, because images come out solid 
black.


Hope this technique comes in useful to someone else tho! (Someone that 
doesn't need 256 color images.)


--Kamilche



Re: [pygame] BUG: "/" key won't work with brazilian ABNT 2 keyboard

2007-01-13 Thread Kamilche

Aaron Maupin wrote:
Not sure if this is connected, but when I was working on a Pygame 
project with text input, it didn't detect my Japanese keyboard.  It 
seemed to treat it like a standard U.S. keyboard.  For example, if I 
pressed SHIFT-2, I got an @ instead of the correct ".


I was using Windows and the OS correctly mapped the keyboard, typing in 
IDLE worked as expected, it was only my Pygame program that seemed to be 
using a different keymap.  Since non-alphanumeric keys weren't that 
important, I didn't investigate and just hacked around it...




I remember some complexities when dealing with keystrokes back when I 
was programming native Windows 95 apps. You can use virtual keycodes to 
trap stuff, but it was sometimes incorrect - there was a translating 
routine you had to run it through to get the 'real' keycode. Maybe 
Pygame isn't using MapVirtualKey?


http://msdn2.microsoft.com/en-us/library/ms646306.aspx



Re: [pygame] BUG: "/" key won't work with brazilian ABNT 2 keyboard

2007-01-12 Thread Kamilche

João Antônio wrote:

Here (pygame 1.7.1, Fedora Core 6 x86_64, Keyboard:ABNT 2), it printed
the code 47.

---
João Antônio T. Rosa

On 1/11/07, Conrado PLG <[EMAIL PROTECTED]> wrote:

Hi,

I think I've found a bug in pygame, I've searched google and the
mailing list archives to no avail.

I was using the ocempgui library and noticed that the "/" ("?" with
shift) key wouldn't work (I use a brazilian ABNT 2 keyboard). With
some testing I think the problem is within pygame.
Using this code in the event loop:

for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
 print event.key

I noticed that event.key is 0 when I press that key.

Any ideas on what is going on?

Thanks,
Conrado

Yeah, I have keyboard bugs too. For one guy, the shift key registers as 
0. For me, I can't hit the print screen plus some other keys.


--Kamilche



Re: [pygame] Numpy slower than Numeric

2006-12-28 Thread Kamilche

Lenard Lindstrom wrote:
Check out the types of array and alphaarray in TestNumpy(). Very 
informative. They are both Numeric arrays. All that is accomplished is 
that numpy.clip is called on one. It probably just treats it as an 
iterable.




Interesting. If I convert to numpy arrays specifically however, I get an 
error on 'pygame.surfarray.blit_array' of "TypeError: argument 2 must be 
array, not numpy.ndarray" This error disappears when I convert the numpy 
array back to a Numeric array before blitting tho.


So - what does this mean for Pygame? It appears to me there is no good 
reason to use numpy, if you have to convert to/from Numeric arrays to 
get it to work right anyway.


--Kamilche

def TestNumpy():
global pic2
pic2 = GetPic()
print 'numpy version: %s' % numpy.__version__
array = numpy.array(pygame.surfarray.pixels3d(pic2).astype(numpy.int))
alphaarray = 
numpy.array(pygame.surfarray.pixels_alpha(pic).astype(numpy.unsignedinteger))

starttime = time.time()
for i in range(10):
array[:, :] = numpy.clip(array + [20, 0, 0], 0, 255)
numericarray = Numeric.array(array).astype(Numeric.Int)
pygame.surfarray.blit_array(pic2, numericarray)
numericarray = Numeric.array(alphaarray).astype(Numeric.UInt8)
pygame.surfarray.pixels_alpha(pic2)[:, :] = numericarray
Update()
print 'numpy time:   %f seconds' % (time.time() - starttime)


Re: [pygame] Numpy slower than Numeric

2006-12-28 Thread Kamilche

Rikard Bosnjakovic wrote:

On 12/28/06, Kamilche <[EMAIL PROTECTED]> wrote:


Sure, here it is. It's a total hack using global variables, but it
works. Numeric takes 1 second, numpy takes 2.6, doing the same
operations to the same picture.


On line 30, array = pygame.surfarray.array3d(pic2).astype(numpy.int),
I need to change the final ".int" to ".Int", else it won't work for me
("AttributeError: 'module' object has no attribute 'int'"). After
switching, I get these results:

Downloading http://www.kamilche.com/images/pygame/elf.png
Numeric time: 0.437000 seconds
numpy time:   0.609000 seconds

If I run it 10 times in a row, the last result it this:

Numeric time: 0.453000 seconds
numpy time:   0.578000 seconds


That is, I cannot reproduce the slow behaviour on your machine. Unless
it's because of the int -> Int-change, ofcourse.



Ok, version check - if I change it back to Int:I get an error 
'AttributeError: 'module' object has no attribute 'Int'' error, the 
exact opposite of yours.


Numeric version: 24.2
Numeric time: 0.954000 seconds

numpy version: 1.0.1
numpy time:   2.312000 seconds



I modified the code to print the versions.
Here's the modified code:

import Numeric
import numpy
import urllib
import pygame
import os
import cStringIO
import time

bg  = None
screen  = None
pic = None
pic2= None

def TestNumeric():
global pic2
pic2 = GetPic()
print 'Numeric version: %s' % Numeric.__version__
array = pygame.surfarray.array3d(pic2).astype(Numeric.Int)
alphaarray = pygame.surfarray.array_alpha(pic).astype(Numeric.UInt8)
starttime = time.time()
for i in range(10):
array[:, :] = Numeric.clip(array + [20, 0, 0], 0, 255)
pygame.surfarray.blit_array(pic2, array)
pygame.surfarray.pixels_alpha(pic2)[:, :] = alphaarray
Update()
print 'Numeric time: %f seconds' % (time.time() - starttime)

def TestNumpy():
global pic2
pic2 = GetPic()
print 'numpy version: %s' % numpy.__version__
array = pygame.surfarray.array3d(pic2).astype(numpy.int)
alphaarray = 
pygame.surfarray.array_alpha(pic).astype(numpy.unsignedinteger)

starttime = time.time()
for i in range(10):
array[:, :] = numpy.clip(array + [20, 0, 0], 0, 255)
pygame.surfarray.blit_array(pic2, array)
pygame.surfarray.pixels_alpha(pic2)[:, :] = alphaarray
Update()
print 'numpy time:   %f seconds' % (time.time() - starttime)

def GetPic(url = 'http://www.kamilche.com/images/pygame/elf.png'):
filename = 'elf.tga'
if os.path.exists(filename):
return pygame.image.load(filename)
print 'Downloading %s' % url
fd = urllib.urlopen(url)
picdata = fd.read()
fd.close()
pic = pygame.image.load(cStringIO.StringIO(picdata))
pygame.image.save(pic, filename)
return pic

def Update():
bg.fill((64, 128, 32, 128))
bg.blit(pic, (0, 0))
bg.blit(pic2, (pic.get_width()+10, 0))
screen.blit(bg, (0, 0))
pygame.display.update()

def main():
global bg, screen, pic, pic2
pygame.init()
screen = pygame.display.set_mode((800, 600), 0, 32)
pic = GetPic()
pic2 = GetPic()
bg = pygame.Surface((800, 600), pygame.SRCALPHA, 32).convert_alpha()
Update()
TestNumeric()
TestNumpy()

main()



Re: [pygame] Rotating Images on a specified axis.

2006-12-27 Thread Kamilche

Patrick Mullen wrote:

Rotate will distort the image as well, unless you rotate in 90 degree
increments.  Make sure to always rotate based on the source, and not off of
previous frames of the rotation.  Rotate is unfiltered, and won't look as
good as rotozoom; rotozoom is slower I believe.



Yeah, those 'picture will contain artifacts' and 'code is messy' 
comments in the documentation scared me off of rotozoom at first... but 
rotozoom is da bomb.


If I need to rotate 0, 90, 280, or 270, I will use the normal rotate, 
but all other angles get rotozoom.





Re: [pygame] Numpy slower than Numeric

2006-12-27 Thread Kamilche

Jakub Piotr Cłapa wrote:

Kamilche wrote:

I make heavy use of Numeric in my sprite engine.
When I did the following, I was able to 'drop in' numpy as a 
replacement, but it took 3x longer to load my complex graphics! :-O


Maybe you could offer a reduced test case so we could check this? I'm 
sure numpy developers would also be interested...




Sure, here it is. It's a total hack using global variables, but it 
works. Numeric takes 1 second, numpy takes 2.6, doing the same 
operations to the same picture.


--Kamilche




import Numeric
import numpy
import urllib
import pygame
import os
import cStringIO
import time

bg  = None
screen  = None
pic = None
pic2= None

def TestNumeric():
global pic2
pic2 = GetPic()
array = pygame.surfarray.array3d(pic2).astype(Numeric.Int)
alphaarray = pygame.surfarray.array_alpha(pic).astype(Numeric.UInt8)
starttime = time.time()
for i in range(10):
array[:, :] = Numeric.clip(array + [20, 0, 0], 0, 255)
pygame.surfarray.blit_array(pic2, array)
pygame.surfarray.pixels_alpha(pic2)[:, :] = alphaarray
Update()
print 'Numeric time: %f seconds' % (time.time() - starttime)

def TestNumpy():
global pic2
pic2 = GetPic()
array = pygame.surfarray.array3d(pic2).astype(numpy.int)
alphaarray = 
pygame.surfarray.array_alpha(pic).astype(numpy.unsignedinteger)

starttime = time.time()
for i in range(10):
array[:, :] = numpy.clip(array + [20, 0, 0], 0, 255)
pygame.surfarray.blit_array(pic2, array)
pygame.surfarray.pixels_alpha(pic2)[:, :] = alphaarray
Update()
print 'numpy time:   %f seconds' % (time.time() - starttime)

def GetPic(url = 'http://www.kamilche.com/images/pygame/elf.png'):
filename = 'elf.tga'
if os.path.exists(filename):
return pygame.image.load(filename)
print 'Downloading %s' % url
fd = urllib.urlopen(url)
picdata = fd.read()
fd.close()
pic = pygame.image.load(cStringIO.StringIO(picdata))
pygame.image.save(pic, filename)
return pic

def Update():
bg.fill((64, 128, 32, 128))
bg.blit(pic, (0, 0))
bg.blit(pic2, (pic.get_width()+10, 0))
screen.blit(bg, (0, 0))
pygame.display.update()

def main():
global bg, screen, pic, pic2
pygame.init()
screen = pygame.display.set_mode((800, 600), 0, 32)
pic = GetPic()
pic2 = GetPic()
bg = pygame.Surface((800, 600), pygame.SRCALPHA, 32).convert_alpha()
Update()
TestNumeric()
TestNumpy()

main()



[pygame] Numpy slower than Numeric

2006-12-26 Thread Kamilche

I make heavy use of Numeric in my sprite engine.
When I did the following, I was able to 'drop in' numpy as a 
replacement, but it took 3x longer to load my complex graphics! :-O


try:
import numpy as Numeric
Numeric.Int = Numeric.int
Numeric.Float = Numeric.float
Numeric.UInt8 = Numeric.unsignedinteger
except ImportError:
import Numeric

I'm leaving numpy in as a fallback import only, now, because of the 
speed hit.




Re: [pygame] rc 3. please test windows installer.

2006-12-26 Thread Kamilche

Luke Paireepinart wrote:

Jasper wrote:

Brian Fisher wrote:

On 12/25/06, Jakub Piotr Cłapa <[EMAIL PROTECTED]> wrote:

AFAIK you ought to switch to numpy (which is maintained). ;-)


According to the people behind numeric, users ought to switch to NumPy
"as quickly as possible"

see the "Older Array Packages" section at the bottom here:
http://numpy.scipy.org/
Moreover, IIRC pygame's use of Numeric causes problems for those 
trying to use Numpy and py2exe, which apparently gets confused when 
dealing with both Numeric and Numpy.  I was forced to unroll my 
migration to Numpy as a result; updating Pygame's obsolete references 
to Numeric would definitely be nice!



Just a thought:
If NumPy is backward compatible with Numeric, couldn't we just do an 
'import Numpy as Numeric' or something?
or maybe have a whole additional script that imports the specific 
functions from Numpy as the corresponding functions from Numeric?
and do something similar to 'from pygame.locals import *' we could do 
'from pygame.fixLegacy import *' or something, and it would

import all of the Numpy functions under the old Numeric names.
-Luke



It's not backward compatible, that I've seen. I also noted the 'use 
numpy' suggestion and tried what you suggested - stuff broke all over 
the place. I'm in the process of converting it right now.




Re: [pygame] SDL vs. Pygame: Alpha Differences

2006-12-24 Thread Kamilche

René Dudfield wrote:

Hi,

maybe I could put in a new blit mode for you before this release... if
it can't be done already.

Can you describe what you want?  I'm still not clear on it.

Do you want this?
DR, DG, DB, DA = SR, SG, SB, DA




Well, after studying Brian's code carefully and trying various 
techniques with my sprite engine, I have come to realize Brian's comment 
is true - there is no pleasing me. :-D His method works, as fast as any 
alternate method I have come up with, but the problem is it's still not 
fast enough.


It would still be nice to have the following, but it wouldn't solve my 
nighttime speed problem: Blit from source RGBA to dest RGBA would blend 
the source RGB onto the dest RGB using the src alpha, leaving the dest 
alpha untouched.


The problem is this: Let's say the above worked. I still have to compose 
the desired sprites into a temporary buffer, apply the night with the 
special blit, then blit them out of that temporary buffer onto the final 
buffer. Those two extra blits are killing the speed.


That special blit would still be nice, but it's not a showstopper, 
because there's several methods around it, including Brian's and a 
couple of others I've used.


It's basically my problem, sorry for bothering you guys with it, and 
good luck with the release! Is there any documentation on the what the 
special_flags on the blit do?


--Kamilche


Re: [pygame] SDL vs. Pygame: Alpha Differences

2006-12-23 Thread Kamilche

Brian Fisher wrote:

On 12/23/06, Kamilche <[EMAIL PROTECTED]> wrote:



... I dug up the thing you posted before (where you move the mouse
around) and modified it to use that thing as the 3rd method (when you
are in the lower third of the screen) and it seems to work.



Thanks for modifying that example. I see this is a variant on the other 
technique that was posted, but involves a couple more blits to preserve 
the alpha. I was trying to avoid all these extra blits to preserve the 
alpha, as it slows down nighttime by quite a lot.


I was hoping the new blit flags on Pygame 1.8 would help me here - 
that's why I was eager to try it out! But my initial testing came up 
with the same results - all those extra blits to not overwrite the 
destination alpha.


Basically - I would dearly love a single blit from one picture to 
another, to NOT modify the destination alpha, without require extra 
blits or manipulation, but I guess that's not available.


The speed hit on preserving that alpha is significant enough, I believe 
I will just have to let the nighttime modify the entire background, 
instead of only the landscaping.


I did think of one technique not mentioned tho! One of my variants 
blitted the night to the entire screen, then used Numeric to strip out 
the pixels where it was equal to the nighttime color. Boy, that one was 
slower than my existing method!


--Kamilche


Re: [pygame] Pygame 1.8 - PNG is an unsupported image format

2006-12-23 Thread Kamilche

René Dudfield wrote:

Hello again,

I double checked, and png is compiled in statically and works ok.
I've asked some other people to try it out on their systems, and it
works ok for them too.

Could you please try removing pygame from the site-packages directory,
and installing it again?  Sounds like something fishy is happening.

Make sure you don't have anything python/pygame thing open when you 
install.




I'm running on a Windows 2000 system with 1 gig memory. I have python 
2.4 and Pygame 1.7 installed.


Per your instructions, I ensured no python app was running. I removed 
pygame from c:\python24\lib\site-packages. I installed pygame 1.8 RC2, 
ran my test, got the same error. So  I removed the folder again, and 
installed RC1 (which was 800K larger!) and ran the tests again. They 
still didn't work.


I tried the same technique using RC1 only, on a Windows XP machine, with 
the same results. Then I restarted the XP machine, had the same results.


I saw Lenard Lindstrom had the same problem. What sort of machine are 
you running on, Lenard?


Maybe it's a problem in the Python 2.4 version only. Did the people that 
ran it successfully, have python 2.4, or python 2.5?


--Kamilche


Re: [pygame] SDL vs. Pygame: Alpha Differences

2006-12-23 Thread Kamilche

Pete Shinners wrote:

On Sat, 2006-12-23 at 12:10 -0800, Kamilche wrote:

In the SDL documentation, it says under 'SDL_SetAlpha':

"When blitting RGBA->RGBA with SDL_SRCALPHA: The source is alpha-blended 
with the destination using the source alpha channel. The alpha channel 
in the destination surface is left untouched. SDL_SRCCOLORKEY is ignored."


However, in Pygame, the alpha channel IS overwritten. Is there any 
technique to overcome this, to make it match what is written in the SDL 
documentation? Or is it a bug in SDL?


Yes, SDL has a special blitter for blending alpha to alpha. You can work
around this by disabling the SRC_ALPHA flag on the source. then it will
work the same as SDL.





I tried disabling the SRC_ALPHA on the source of a picture using two 
methods, and both of them still modified the alpha map of the original 
picture. Maybe you can tell me what I'm doing wrong?


# Sample program - 'full.png' should be a full color pic
# with an alpha channel.



import pygame

def main():
pygame.init()
nightcolor = (0, 0, 0, 64)
bg = pygame.display.set_mode((800, 600), pygame.SRCALPHA, 32)
bg.fill((128, 128, 128, 255))
pic = pygame.image.load('full.png').convert_alpha()


'''
# This blitted a black picture on top
night = pygame.Surface(pic.get_size(), 0, 32)
night.fill(nightcolor)
night.set_alpha(None)
pic.blit(night, (0, 0))
'''

# This blitted a nighttime overlay, but messed up
# the alpha channel of the destination pic.
night = pygame.Surface(pic.get_size(), 0, 24)
night.fill(nightcolor[:3])
night.set_alpha(nightcolor[3])
pic.blit(night, (0, 0))


bg.blit(pic, (0, 0))
pygame.display.update()


main()


[pygame] SDL vs. Pygame: Alpha Differences

2006-12-23 Thread Kamilche

In the SDL documentation, it says under 'SDL_SetAlpha':

"When blitting RGBA->RGBA with SDL_SRCALPHA: The source is alpha-blended 
with the destination using the source alpha channel. The alpha channel 
in the destination surface is left untouched. SDL_SRCCOLORKEY is ignored."


However, in Pygame, the alpha channel IS overwritten. Is there any 
technique to overcome this, to make it match what is written in the SDL 
documentation? Or is it a bug in SDL?


--Kamilche


[pygame] Pygame 1.8 - PNG is an unsupported image format

2006-12-23 Thread Kamilche
I tried both RC1 and RC2 of Pygame 1.8 from 
http://rene.f0o.com/~rene/pygame-1.8.0rc2.win32-py2.4.exe , and they 
both gave me this error when trying to load a PNG file:


error: Unsupported image format

Looking forward to evaluating it more! But this error stops me cold, as 
all my graphics are in PNG format.


--Kamilche


Re: [pygame] Where Do I Go From Here?

2006-12-04 Thread Kamilche

Simon Oberhammer wrote:


mh.. couldnt find screenshots, but the NPCs look nice indead :-)


They're all under the 'forum' link.


Re: [pygame] Where Do I Go From Here?

2006-12-04 Thread Kamilche

Kris Schnee wrote:

Many questions here; I could use help from someone more experienced.

But what now? Although I could and probably should focus on the
"worldsim" itself -- the physics and gameplay -- I'm not sure about how
to develop the graphics system further. Assuming that I can successfully
combine this landscape with my Pygame-only widget system and with
Pyglyph so that I can do text windows, buttons etc., it's still going to
be ugly! I thought about switching from these awkward-looking textures
to plain colors, but (perhaps because there's full lighting) that turns
the landscape into green soup. And there's still a bad case of the
jaggies (and terrible FPS) from the fact that I'm using 100x100 data
points. _And_ the sky's not animated. And so on.

So, as a lone developer, is it even worth trying to do this 3D system?


Truthfully, I wouldn't even attempt to write a 3D system from scratch. 
There are lots of open source and commercial 3D engines out there - I'd 
pick one and go with it, rather than reinvent the wheel. 3D programming 
is much harder than 2D programming, and bigger teams than yours have 
already plowed that same ground.



My reasoning is:
-That bad 3D is worse than good 2D;


I personally don't think so - take a look at http://www.kamilche.com for 
some screenshots of a 2D game I'm currently developing. In truth, I've 
been working on it for several years now. I've programmed it in a 
variety of different programming languages, but Python is the one that 
'stuck.'



-That Pygame scrolls slowly (I'm getting just 15 FPS on my non-scrolling 
2D engine with Psyco, vs. 32-34 on a minimal Pygame program with/without 
Psyco)


Pygame is slow for scrolling games - they have a hard time keeping their 
frame rate up. There are probably faster engines out there, but the ones 
I've seen force you to stick to the Windows world, or don't have Python 
bindings, or don't have per pixel alpha, etc.



-That OpenGL is potentially faster if I can make lists work properly 
(it's around 4-7 FPS right now!);


Ouch.

-But that I'm tired of being bogged down switching between graphics 
engines and still having the program look bad. I want to build gameplay 
and AI, not write yet another display system!


It seems to me that you really want a 3D game, and won't be satisfied 
with 2D. If that's the case, you really have one decision to make - to 
continue to develop your own engine, which it sounds like you don't want 
to do), or to look at pre-built 3D engines that have Python bindings.


--Kamilche



Re: [pygame] Incarnation

2006-12-02 Thread Kamilche

Kris Schnee wrote:
I tried running this, but nothing happens when I try to log in. I tried 
both leaving the name/password blank, and a made-up pair, but both times 
the program just hung.


Kris



Try this: Connect to http://www.incarnationserver.com:2000 . If you see 
gobbledygook, or FireFox asks you to donwload a file, you should be able 
to connect. If you see nothing, you're somehow unable to communicate to 
my computer on that port.


If you have a firewall, double check that you're able to send outgoing 
TCP communications on port 2000.


Farai - what's your character name in the game?

--Kamilche


Re: [pygame] Alpha Channel Speed Question

2006-11-28 Thread Kamilche

Lenard Lindstrom wrote:

On 27 Nov 2006 at 16:48, Kamilche wrote:


Lenard Lindstrom wrote:

On 22 Nov 2006 at 21:15, Kamilche wrote:

I have a question - Do you know of a way to get method 3 as outlined 
below to be faster? The necessity of doing all those extra blits to 
preserve the alpha channel is really slowing things down.



[snip]
Colorkeys are incompatible with per pixel alpha - set_alpha only works 
on pictures that don't have per pixel alpha.


Yes and no. Colorkey doesn't work on a surface with per pixel alpha. 
But a colorkey surface does alpha blit to a surface with per pixel 
alpha, preserving the destination surfaces alpha values. Colorkey is 
just fine if  the night overlay only darkens the bitmap.





Hm, now I understand. Thanks a lot for explaining that!

--Kamilche


Re: [pygame] Alpha Channel Speed Question

2006-11-27 Thread Kamilche

Lenard Lindstrom wrote:

On 22 Nov 2006 at 21:15, Kamilche wrote:

I have a question - Do you know of a way to get method 3 as outlined 
below to be faster? The necessity of doing all those extra blits to 
preserve the alpha channel is really slowing things down.





import pygame


[snip some code]

def Run():
 bgcolor1 = (255, 255, 255)
 bgcolor2 = (192, 192, 192)
 bgcolor3 = (128, 128, 128)
 nightcolor = [0, 0, 0, 64]

 # Create a bitmap - assume this is an expensive operation
 # taking a few seconds.
 bitmap = pygame.Surface((100, 100), pygame.SRCALPHA, 
32).convert_alpha()

 pygame.draw.circle(bitmap, (0, 255, 255), [50, 50], 50, 0)
 bitmappos = [0, 0]

 # Create the nighttime overlay
 night = pygame.Surface((WIDTH, HEIGHT/3), pygame.SRCALPHA, 
32).convert_alpha()

 night.fill(nightcolor)

 # Loop forever
 quitgame = 0
 while not quitgame:
 pygame.event.pump()

[snip]

 # Look for quit
 for e in pygame.event.get():
 if e.type in [pygame.QUIT, pygame.MOUSEBUTTONDOWN]:
 quitgame = 1
 break
 elif e.type == pygame.KEYDOWN:
 if e.key == 27:
 quitgame = 1
 break
 elif e.type == pygame.MOUSEMOTION:
 bitmappos = e.pos
 nightcolor[3] = e.pos[0]/float(WIDTH) * 255
 night.fill(nightcolor)

Maybe, using colorkey and Surface alpha. But I have a question too. 
Do you prepare all your bitmaps (circle) at game startup? More 
specifically, would it be expensive to prepare a black and white 
mask, to be used as the shader (night), for each bitmap? Even if it 
is you can remove excess processing by declaring night as:


pygame.Surface((WIDTH, HEIGHT/3), 0, 32)

and adjust its surface alpha using set_alpha().

Lenard Lindstrom
<[EMAIL PROTECTED]>





Colorkeys are incompatible with per pixel alpha - set_alpha only works 
on pictures that don't have per pixel alpha.


Thanks anyway!

--Kamilche


[pygame] Pushing the edges of Pygame technology

2006-11-27 Thread Kamilche
You know you're pushing the edges of a technology, when no one can 
answer your question. ;-D Well, here's hoping the new version of Pygame 
will have a solution for the slow alpha mask question I posted a few 
days ago.




Re: [pygame] Incarnation

2006-11-24 Thread Kamilche

Farai Aschwanden wrote:

Do you send it over the IP adresses? How you surpass firewalls and NAT?

Am 24.11.2006 um 21:28 schrieb Kamilche:


Farai Aschwanden wrote:
Really great work! Also my compliments and respect to the GFX artist. 
;) You pushed the game level of Pygame definately higher!
One question: How did you solve the chat sync? Do you pull the text 
inside client from the server like every 3 seconds or so or do you 
spread it by server to all clients?

Greetings
Farai


Thanks! I've worked on it for a long time.  I spread it by server to 
all clients.







Have the client make an outgoing connection to the server, and you'll 
bypass most firewall issues. Firewalls prevent mainly incoming 
connections on strange ports.


Re: [pygame] pygame and cairo

2006-11-24 Thread Kamilche

Richard Jones wrote:

On Saturday 25 November 2006 06:52, Simon Burton wrote:

I put up a cookbook entry on how to alias a cairo surface
to a pygame surface (and a numpy array):

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498278


Could you please put it in the pygame cookbook?


Thanks,

   Richard


.




What button on the web page would he press, to do that? I don't see such 
an option myself, even though I'm logged on to the webpage.




Re: [pygame] Incarnation

2006-11-24 Thread Kamilche

Farai Aschwanden wrote:
Really great work! Also my compliments and respect to the GFX artist. ;) 
You pushed the game level of Pygame definately higher!


One question: How did you solve the chat sync? Do you pull the text 
inside client from the server like every 3 seconds or so or do you 
spread it by server to all clients?


Greetings
Farai



Thanks! I've worked on it for a long time.  I spread it by server to all 
clients.


Re: [pygame] Incarnation

2006-11-23 Thread Kamilche
The number of updates is pretty huge. It does some checks to prevent it 
from redownloading updates it already has, but it's still a lengthy process.


The easiest way to avoid all this is to download the 'full zip.' I 
updated it last night, so it should be up to date, only one or two 
updates after installation.


If you've already installed the EXE version, the zip can still help - 
just copy over the files from the zip and drop on top of your existing 
Incarnation folders.


--Kamilche


[pygame] Alpha Channel Speed Question

2006-11-22 Thread Kamilche
I have a question - Do you know of a way to get method 3 as outlined 
below to be faster? The necessity of doing all those extra blits to 
preserve the alpha channel is really slowing things down.





import pygame

WIDTH = 800
HEIGHT = 600
bg = None

def Init():
global bg, font
pygame.init()
bg = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
font = pygame.font.Font(None, 18)

def Run():
bgcolor1 = (255, 255, 255)
bgcolor2 = (192, 192, 192)
bgcolor3 = (128, 128, 128)
nightcolor = [0, 0, 0, 64]

# Create a bitmap - assume this is an expensive operation
# taking a few seconds.
bitmap = pygame.Surface((100, 100), pygame.SRCALPHA, 
32).convert_alpha()

pygame.draw.circle(bitmap, (0, 255, 255), [50, 50], 50, 0)
bitmappos = [0, 0]

# Create the nighttime overlay
night = pygame.Surface((WIDTH, HEIGHT/3), pygame.SRCALPHA, 
32).convert_alpha()

night.fill(nightcolor)

# Loop forever
quitgame = 0
while not quitgame:
pygame.event.pump()

# Fill background
bg.fill(bgcolor1, (0, 0, WIDTH, HEIGHT/3))
Print(bg, 'I want to darken the circle only. (Move the mouse 
left and right to test.)', (0, 10))
Print(bg, 'Moving the mouse up here uses overlay method 1, 
which overlays the background and circle.', (0, 25))
Print(bg, 'This method is fast, but undesirable because it 
colors the background.', (0, 40))

bg.fill(bgcolor2, (0, HEIGHT*1/3, WIDTH, HEIGHT/3))
Print(bg, "Moving the mouse up here uses overlay method 2, 
which overlays the circle only, but also destroys the circle's alpha 
channel.", (0, HEIGHT/3+10))

bg.fill(bgcolor3, (0, HEIGHT*2/3, WIDTH, HEIGHT/3))
Print(bg, 'Moving the mouse down here uses overlay method 3, 
which overlays the circle only, but is very slow.', (0, HEIGHT*2/3+10))
Print(bg, "Do you know of a faster way to darken the bitmap, 
without modifying the original picture?", (0, HEIGHT*2/3+25))


# Render night (the part in question)
if bitmappos[1] < HEIGHT/3:
# Method that colors it all include the background
bg.blit(bitmap, (bitmappos[0]-50, bitmappos[1]-50))
bg.blit(night, (0, 0))
elif bitmappos[1] < HEIGHT*2/3:
# Method that colors only the circle but destroys its alpha 
channel

w, h = bitmap.get_size()
temp = pygame.Surface((w, h), pygame.SRCALPHA, 
32).convert_alpha()

temp.blit(bitmap, (0, 0))
temp.blit(night, (0, 0))
bg.blit(temp, (bitmappos[0]-50, bitmappos[1]-50))
else:
# Method that colors only the circle, but is too slow
w, h = bitmap.get_size()
temp = pygame.Surface((w, h), pygame.SRCALPHA, 
32).convert_alpha()

temp.blit(bitmap, (0, 0))
temp.blit(night, (0, 0))
pygame.surfarray.pixels_alpha(temp)[:, :] = 
pygame.surfarray.pixels_alpha(bitmap)

bg.blit(temp, (bitmappos[0]-50, bitmappos[1]-50))

pygame.display.update()

# Look for quit
for e in pygame.event.get():
if e.type in [pygame.QUIT, pygame.MOUSEBUTTONDOWN]:
quitgame = 1
break
elif e.type == pygame.KEYDOWN:
if e.key == 27:
quitgame = 1
break
elif e.type == pygame.MOUSEMOTION:
bitmappos = e.pos
nightcolor[3] = e.pos[0]/float(WIDTH) * 255
night.fill(nightcolor)

def Print(bg, text, loc):
fontcolor = (0, 0, 0)
pic = font.render(text, 1, fontcolor)
bg.blit(pic, loc)

def Terminate():
pygame.quit()

def main():
Init()
Run()
Terminate()

main()


Re: [pygame] Trapezoid function for Pygame

2006-11-04 Thread Kamilche

Farai Aschwanden wrote:

Hello

I let once build a function for Pygame that allows to transform a 
rectangle into a trapezoid. Its quite fast and works stable. I dont know 
who in this mail group is working in the Pygame group but I can offer 
that function so it could be added once into any Pygame version.
You can use this function f.e. in 2D games adding a depth to a object 
(image).


Greetings
Farai







I'm interested! :-)

--Kamilche



Re: [pygame] Rain Generator

2006-10-26 Thread Kamilche

Luke Paireepinart wrote:

Now just add little splashes at the bottom, a rain sound effect, and 
randomly change the background to white for a few frames (to simulate 
lightning)

and you can sell it as a screensaver!
I'm excited :D



Glad you find it entertaining! :-D

Uh, BTW, that URL was incorrect - the new version is at 
http://incarnation.danbo.com/ubbthreads/showflat.php?Cat=0&Number=10483&Main=10483#Post10483





Re: [pygame] Rain Generator

2006-10-26 Thread Kamilche

Kai Kuehne wrote:

Looks similar to http://www.scriptedfun.com/pygame-starfield-rain/
but it's cool.



Yep, that's the site that inspired me. Mine is a different solution to 
the same problem, but the raindrops look similar, that's true. If you 
look closely, his are leaving trails behind - mine isn't, it's using an 
entire raindrop with a tail that 'peters out.'


Luke noticed the dirty rectangle code wasn't working quite correctly, so 
I've modified the code and reposted it at 
http://incarnation.danbo.com/ubbthreads/modifypost.php .

I also added some features, such as:

* Speeding up big raindrops so they appear closer
* Changing the translucency of raindrops so smaller ones are dimmer and 
look farther away
* Optimized the particle engine so the raindrops are created once when 
the generator is created (as opposed to being continually created and 
destroyed)
* Put the drops on a timer so they move at the desired speed regardless 
of how often you call the rain generator

* Made the left and right arrow keys decrease/increase the rain speed.

plus miscellaneous enhancements.

Or - read it here if you wish:

'''
Rain.py - a rain generator by Kamilche.

This rain generator creates the particles once when the generator is 
created, to save CPU time.
The bigger the raindrop, the faster it moves. The smaller the raindrop, 
the dimmer it is.


Parameters are:
screen   = surface to draw rain on
height   = height of raindrops (will vary from 40% to 100% of size 
specified)

speed= speed of raindrops (how fast they fall)
color= color of raindrops, including alpha level (opacity)
numdrops = number of raindrops

'''

import pygame
import random
import time

SCREENSIZE = 640, 480

class Rain(object):
' Rain generator'

def __init__(self, screen, height = 160, speed = 3, color = (180, 
215, 228, 255), numdrops = 10):

'Create and reuse raindrop particles'
self.screen = screen
self.drops  = []
self.height = height
self.speed  = speed
self.color  = color
self.numdrops   = numdrops

for i in range(self.numdrops):
# Randomize the size of the raindrop.
raindropscale = random.randint(40, 100) / 100.0
w, h = 3, int(raindropscale * self.height)
# The bigger the raindrop, the faster it moves.
velocity = raindropscale * self.speed/10.0
pic = pygame.Surface((w, h), pygame.SRCALPHA, 
32).convert_alpha()

colorinterval = float(self.color[3] * raindropscale)/h
r, g, b = self.color[:3]
for j in range(h):
# The smaller the raindrop, the dimmer it is.
a = int(colorinterval * j)
pic.fill( (r, g, b, a), (1, j, w-2, 1) )
pygame.draw.circle(pic, (r, g, b, a), (1, h-2), 2)
drop = Rain.Drop(self.speed, velocity, pic)
self.drops.append(drop)

def Timer(self, now):
' Render the rain'
dirtyrects = []
for drop in self.drops:
r = drop.Render(self.screen, now)
if r:
i = r.collidelist(dirtyrects)
if i > -1:
dirtyrects[i].union_ip(r)
else:
dirtyrects.append(r)
return dirtyrects

def AdjustSpeed(self, adj):
newspeed = self.speed + adj
newspeed = max(1, newspeed)
newspeed = min(100, newspeed)
self.speed = newspeed
for drop in self.drops:
drop.SetSpeed(newspeed)
print 'Rain speed: %d' % newspeed


class Drop(object):
' Rain drop used by rain generator'
nexttime = 0   # The next time the raindrop will draw
interval = .01 # How frequently the raindrop should draw

def __init__(self, speed, scale, pic):
' Initialize the rain drop'
self.speed = speed
self.scale = scale
self.pic = pic
self.size = pic.get_size()
self.SetSpeed(speed)
self.pos = [random.random() * SCREENSIZE[0], 
-random.randint(-SCREENSIZE[1], SCREENSIZE[1])]

self.currentspeed = speed

def SetSpeed(self, speed):
' Speed up or slow down the drop'
self.speed = speed
self.velocity = self.scale * self.speed/10.0

def Reset(self):
' Restart the drop at the top of the screen.'
self.pos = [random.random() * SCREENSIZE[0], 
-random.random() * self.size[1] - self.size[1]]

self.currentspeed = self.speed

def Render(self, screen, now):
' Draw the rain drop'
if now < self.nexttime:
return None
self.nexttime = now + self.interval
 

Re: [pygame] Rain Generator

2006-10-26 Thread Kamilche

Farai Aschwanden wrote:
Could only check the rain.py that is pretty to look at. The ground touch 
of the rain is really well done!  Crashes also on my machine after about 
5 seconds.
Unfortunately I cant start snow.py, Im not psyco enough. ;) Should try 
it out once, tough they say its not stable yet.



Yeah, snow.py is pretty as well!
Psyco is really easy to turn off - just comment out the first two lines, 
and you should be able to run the second demo.


On the first example - it didn't crash for me, but it stopped responding 
at 5 seconds, because I lost the game! The object of this mini game is 
to keep that box at the bottom covered and not let any rain touch it. 
Really cute!


--Kamilche


Re: [pygame] Rain Generator

2006-10-26 Thread Kamilche

Farai Aschwanden wrote:
Nice looking rain and proper code! I experienced a tiny lag like every 3 
seconds. I experienced that also in other games/demos, couldnt find out 
why. Did other ppl also experienced this and/or knew why or is it only 
on my Mac?


Greetings
Farai



Thanks!

It doesn't lag on my Windows 2000 box, but I believe ya.
Try commenting out the line that prints the FPS - I know printing can 
slow things down.





[pygame] Rain Generator

2006-10-26 Thread Kamilche


I was inspired to create a rain generator after seeing someone else's on 
the Internet today, and thought I'd post it here:


[code]

import pygame
import random
import time

SCREENSIZE = 640, 480

class Rain(object):
' Rain generator'
drops = []
height = 160
speed = 1
color = (255, 255, 255, 255)
chance = .05

def __init__(self, **kwargs):
' Allow programmer to change settings of rain generator'
self.__dict__.update(kwargs)

def Render(self, screen):
' Render the rain'
dirtyrects = []
for drop in self.drops:
drop.Render(dirtyrects, screen)
if drop.dead:
self.drops.remove(drop)
else:
dirtyrects.append(drop.rect)
if random.random() < self.chance:
self.drops.append(Rain.Drop(self.height, self.speed, 
self.color))

return dirtyrects

class Drop(object):
' Rain drop used by rain generator'
pos = None
dead = 0

def __init__(self, height, speed, color):
' Initialize the rain drop'
w, h = 3, int((random.randint(80, 120) * height) / 100.0)
self.pic = pygame.Surface((w, h), pygame.SRCALPHA, 
32).convert_alpha()

self.height = self.pic.get_height()
self.maxy = SCREENSIZE[1] + h
self.speed = 1
self.pos = [random.random() * SCREENSIZE[0], -self.height]
factor = float(color[3])/h
r, g, b = color[:3]
for i in range(h):
self.pic.fill( (r, g, b, int(factor * i)), (1, i, w-2, 
1) )

pygame.draw.circle(self.pic, (255, 255, 255), (1, h-2), 2)
self.rect = pygame.Rect(self.pos[0], self.pos[1], 
self.pic.get_width(), self.pic.get_height())


def Render(self, dirtyrects, screen):
' Draw the rain drop'
self.pos[1] += self.speed
self.rect.topleft = self.pos
self.speed += .2
if self.pos[1] > self.maxy:
self.dead = 1
else:
screen.blit(self.pic, self.pos)

def main():
# Initialize pygame
pygame.init()
screen = pygame.display.set_mode(SCREENSIZE, 0, 32)

# Create rain generator
rain = Rain()

# Main loop
nexttime = time.time()
ctr = 0
quit = 0
while not quit:

# Uncomment the following line to make the rain go slower
#time.sleep(.01)

# Track FPS
if time.time() > nexttime:
nexttime = time.time() + 1
print '%d fps' % ctr
ctr = 0
ctr += 1

# Draw rain
dirtyrects = rain.Render(screen)

# Update the screen for the dirty rectangles only
pygame.display.update(dirtyrects)

# Fill the background with the dirty rectangles only
for r in dirtyrects:
screen.fill((0, 0, 0), r)

# Look for user quit
pygame.event.pump()
for e in pygame.event.get():
if e.type in [pygame.QUIT, pygame.KEYDOWN, 
pygame.MOUSEBUTTONDOWN]:

quit = 1
break

# Terminate pygame
pygame.quit()

if __name__ == "__main__":
main()

[/code]

If the spaces have been eaten, I also posted it at
http://incarnation.danbo.com/ubbthreads/showflat.php?Cat=0&Number=10483&an=0&page=0#Post10483



Re: [pygame] First stable release of my online game (Crescent Dawn Online)

2006-10-04 Thread Kamilche

Patrick Mullen wrote:

There's some screenshots at the blender forums:

http://blenderartists.org/forum/showthread.php?t=76549&page=3


Yeah the web sites still not quite finished.  I plan on adding a gallery 
and

a forum this weekend.

Maybe I'm not really looking for people who will make snap judgements just
yet  :)




Heh, OK. Thanks for the screenshot link!



Re: [pygame] First stable release of my online game (Crescent Dawn Online)

2006-10-04 Thread Kamilche
No screenshots! How can I come make a snap judgement of your game if you 
post no screenshots? ;-)




Re: [pygame] Pygame runs faster when mouse is moved

2006-09-19 Thread Kamilche

Greg Ewing wrote:

Kamilche wrote:
I'm encountering an interesting artifact in my 'falling snow' routine. 
When I wave the mouse around, for no reason, the snow appears to fall 
faster.


My guess is that you're taking a time step in your
animation every time your get-events call wakes up.
Moving the mouse generates mouse-movement events,
each of which causes your animation to advance.

The solution is to only take a time step when you
get whatever event you've set up to fire when
your frame timer expires. You can render at other
times if you want, but only timer events should
cause the animation to advance.



Yeah, it was something like that. The screen render loop was separate 
from the weather loop. I made the screen update loop fire off the 
weather loop, and only when there was a dirty rectangle on the screen.


--Kamilche




[pygame] Pygame runs faster when mouse is moved

2006-09-18 Thread Kamilche
I'm encountering an interesting artifact in my 'falling snow' routine. 
When I wave the mouse around, for no reason, the snow appears to fall 
faster. :-D The code is way too complicated to strip out and show you by 
itself... I was hoping someone had done some advanced Pygame routines 
and encountered this themselves, and could give me a clue.


I suspect it has to do with the event queue processing, but I don't know 
how. I run through all the events in the queue, then render... but 
nothing is drawn until the 'render' routine. It makes no difference if I 
process only one event in the queue, then render, the same behavior is 
exhibited. Even the throttle makes no difference.


--Kamilche


  1   2   >