Re: [pygame] keep a key pressed and then move a sprite

2010-11-24 Thread Kris Schnee

On 2010.11.24 1:53 PM, Nathan BIAGINI wrote:

Ok thanks to reply so fast :) yeah of course, it seems obvious now but i
didn't know there is a way to manage keyboard state without the common
event loop.
I ll use this created topic to ask something else about the optimization
of a game written with pygame. Restrict frames per second with
clock.tick(xx) and only update dirty rects (in case of static
background) is enough for a quite "simple" 2D game? Or there re more
optimizations to do? I don't try to reach perfect performance, only want
to make my faster as possible and less CPU consuming.


One other thing to try is an acceleration system.
"Psyco" uses a compiler to speed up a Python program very easily. See 
http://psyco.sourceforge.net/ . All you need to do after installing it 
is add the code "import psyco ; psyco.full()".


"Boost" ( 
http://beta.boost.org/doc/libs/1_45_0/libs/python/doc/index.html ) lets 
you write code in the C language and access that from Python. I've not 
tried that.


Re: [pygame] keep a key pressed and then move a sprite

2010-11-24 Thread Kris Schnee

On 2010.11.24 12:27 PM, Ian Mallett wrote:

Hi,

Try this:

The PyGame event manager fires events /only when a key's state changes
/(that is, the moment it is pressed or the moment it was released, a
/single /event is fired).

What you want to do is to check the /current state /of the keyboard.
"pygame.key.get_pressed()" does this.  The state "key" that it returns
can then be checked for the required key.


That's all correct. One other option (though get_pressed is probably 
better) is to watch for both the KEYDOWN and KEYUP events. You could 
start the characters moving on a KEYDOWN event and keep moving them 
until there's a KEYUP event.


Constants like K_LEFT are defined in pygame.locals, so you can either 
reference them like "pygame.locals.K_LEFT" or (easier) say "from 
pygame.locals import *" so you can just say "K_LEFT".


Also, consider separating the code for what happens to the 
character/sprite from the bit that reacts to keyboard input. I try to do 
something like:

"if keys[K_RIGHT]: player.speed_x = player.speed
if keys[K_UP]: player.speed_y = -player.speed
player.coords[x] += player.speed_x; player.coords[y] += player.speed_y"
That kind of thing lets you separate the movement logic a bit from the 
way it's inputted.


Note that if you have trouble with certain combinations of keys not 
registering when pressed together, that's a known problem inherent to 
keyboards. Google "keyboards are evil" for an explanation.


Re: [pygame] Python 3.1 compatible setup.py for 1.9.1

2010-11-22 Thread Kris Schnee

On 2010.11.22 5:52 PM, Lenard Lindstrom wrote:

Hi,

On 20/11/10 02:04 PM, Matthew Maniaci wrote:

I ran 2to3 on setup.py and it didn't quite get all of the raw_inputs.
A quick find-and-replace fixed that and I was able to install pygame
from source using Python 3.1. I haven't tested it yet, so use at your
own risk.

Why? Pygame already builds from source for Python 3.1, and 3.2.


Is it fair to say that Py2EXE works yet for versions of Python beyond 2.5?


Re: [pygame] peer-to-peer networked games

2010-11-06 Thread Kris Schnee

On 2010.11.5 8:09 PM, Miriam English wrote:

Okay, I've found some stuff that I hadn't heard of before that some of
you folks might be interested in:


http://en.wikipedia.org/wiki/Croquet_project
The Croquet Project seems to be similar to that. The indie game 
Minecraft is apparently going to have servers linked so that a character 
can walk from one server's world to another.


A question that Croquet brings up is how to spread out the computation 
between computers. There's a project called OpenSimulator that sets up 
independent servers for the game Second Life, but I believe that works 
on a more standard client/server arrangement. Croquet is set up so that 
the calculation is done on every machine, which is inefficient but 
ensures every machine does the same thing... at the cost of the system 
being as slow as the slowest PC, if I understand right. At the other end 
of the scale, with Minecraft it'd probably be possible for one server to 
let players easily get hoards of valuable items, then try to walk onto a 
higher-difficulty server with items intact. So for a game you'd have to 
think about which machine enforces the rules against cheaters, and the 
more centralized it is, the more it's like the client/server setup.


If someone wants to test out building a Python P2P gaming system, don't 
assume it has to be for real-time 3D games! Why not try making a P2P 
text MU?


Re: [pygame] Game art / icons

2010-10-31 Thread Kris Schnee

On 2010.10.31 1:23 PM, Mark Reed wrote:

Hey guys,

I lost my links to free art websites, where do you get your stuff from?

I forget the english for it so am having trouble googling (icons?) but
I was using a site that was geared towards UI work - buttons / icons
for theming your desktop.  It had lots of users contributing good
stuff.


One of the sites you might like is http://www.lostgarden.com/ , which 
has several sets of free graphics suitable for games. Specifically see 
http://www.lostgarden.com/search/label/free%20game%20graphics .


Re: [pygame] pygame2exe

2010-10-24 Thread Kris Schnee

On 2010.10.23 11:20 PM, Matt Riche wrote:

I just struggled with this one myself, literally barely 48 hours ago,
and I finally got a solution.



Next I got some error about a failure to initialize "mixer_music".  I
read a lot of discussion on how to fix this, but most people's ideas
didn't work for me.  Someone finally said to roll back to Python 2.5,
and the version of Pygame for it.  That fixed that problem.  Not sure
if there's a better way, or really why that was a fix, but it worked.
Maybe research more before you try that if you don't wanna roll back?
Or more likely, your program doesn't use audio and there won't be
calls to this.


I've had trouble with similar problems like the DLLs, and have settled 
some of them by (1) never using the default font in a compiled program 
and (2) sticking to Python 2.5 and matching Pygame. I've tried relying 
on a simple setup.py rather than some of the fancier workarounds some 
people have been able to use. The latest version I've been able to dig 
up from my code looks like this (and reminds me how long it's been):


# setup.py
from distutils.core import setup
import py2exe
setup(author="Kris Schnee",
  author_email="ksch...@xepher.net",
  version="2009.9.26",
  license="GPLv3 or MIT",
  windows=[{"script":"morningside_server.py",
"icon_resources":[(0,"beach.ico")],
}])


That might be a useful template.


c:\users\christ~1\appdata\local\temp\tmplkizod.py


Wow, I didn't know _He_ used Python! =)


Re: [pygame] Quit pygame

2010-09-30 Thread Kris Schnee

On 2010.9.30 12:01 PM, Massimo Di Stefano wrote:

I tried the following code in a standard python shell :


from pygame.locals import *
import pygame
pygame.init()

Leopard libedit detected.
(6, 0)

for event in pygame.event.get():

... if event.type == QUIT:
... running = False
...

pygame.event.pump()
pygame.quit()


Different note: isn't pygame.event.pump redundant here, since you're 
already clearing the latest events by calling pygame.event.get()?


Re: [pygame] frame independant movement

2010-08-28 Thread Kris Schnee

On 2010.8.28 1:42 AM, R. Alan Monroe wrote:



In other words, use a small enough time step that the difference
is not big enough to be a problem. But if you're doing that, you
might as well pick one sufficiently small time step and use a
variable number of them per frame, so that the physics is
always predictable whatever the frame rate.


While we're on the time topic, is there an easy way to do slo-mo, a la
Peggle Extreme Fever or a Burnout multi-car pileup?


Hmm. If your standard physics time-step is small enough that you can 
avoid problems like collision, making the time-step smaller than that 
doesn't seem like it'd hurt anything. (Though I might misunderstand some 
of the argument earlier.) And if it did, maybe it's enough that you 
don't need to care. Or if you were _really_ concerned, you could even 
back up the world objects' status at time 0, simulate times .1, .2, .3 
&c instead of your usual 1, 2, 3, &c, and when you were done showing 
off, revert to time 0 and do a 1-unit time-step to eliminate any 
deviation from your usual physics.


Re: [pygame] frame independant movement

2010-08-27 Thread Kris Schnee

On 2010.8.27 11:43 AM, Brian Fisher wrote:

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

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




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


Makes sense. Another example would be collision detection. If you've got 
a platform .1 unit thick and your 1-unit-tall character falls 2 units in 
one frame due to low framerate, then they'll fall through the platform.


Re: [pygame] frame independant movement

2010-08-27 Thread Kris Schnee

On 2010.8.27 10:36 AM, B W wrote:

Howdy,

Reviving this old thread. The comments by Patrick and Brian really
intrigued me, so I pursued the topic. Found a few interesting articles
and one great article. My study has resulted in a recipe for those of us
continually nagged by the question, "how can I get constant game speed
independent of frame rate?". The demo requires Pygame, but the clock
module only requires Python.


Isn't it simply a matter of creating a Pygame Clock object and calling 
clock.tick() to delay until the appropriate time to maintain some max 
framerate?


Re: [pygame] Spam on Tutorials page

2010-08-05 Thread Kris Schnee

On 2010.8.5 2:29 PM, James Paige wrote:

I think I have mentioned this before, but I will bring it up again.

If you auto-block posts that contain a url, you block 99.?% of spam.

This doesn't interfere too badly with normal comments. Only a minor
inconveneince for legit users, really. Even anonymous legit users!

There could be a whitelist of users who are allowed to post urls, or you
could send comments that contain urls to a queue for moderation fi you
want to get fancy.


The project pages have some form you can fill in to include a URL, 
right? Seems like a way to let people post those (if they're registered 
users) while banning them from the body of a post. Using a form field as 
the only way to include a URL might make life harder for people trying 
to increase our Python size. I've seen spammers disguise a URL to be 
something like "I got great dealz from s p a m d ot r u", so no system's 
going to be perfect.


Re: [pygame] "Node Based Visual Programming Language"

2010-07-19 Thread Kris Schnee

On 2010.7.19 9:05 AM, linedicons...@gmail.com wrote:

On Sun, Jul 18, 2010 at 9:03 PM, Bill Coderre mailto:b...@mac.com>> wrote:

I want to write a game where there's some "critters" living on a
plain, wandering around, fighting with each other, eating grass,
etc.


I've got a basic tile-based environment where programs can walk around 
and pick up objects, as well as an incomplete upgrade to that. This kind 
of thing:

http://kschnee.xepher.net/pics/morningside/090918morningside_random.jpg


Re: [pygame] Referencing instances by memory address

2010-07-12 Thread Kris Schnee

On 2010.7.12 7:09 PM, 音本四 wrote:

I was storing them by id() because it was an easy unique number to use
and meant that I wouldn't need to dynamically generate unique numbers
for each instance. The main thing I need them for is referencing
individual bullets for collision detection. I also need to delete the
dictionary reference, because otherwise, collision detection with no
longer "existing" bullets continues, causing a sort of invisible barrier
for bullets in the future.


Have you considered using a list rather than a dictionary? It'd work 
like this:


for bullet in list_of_bullets:
  bullet.keep = checkforcollision() ## Sets a flag on each bullet
  if bullet.time_left == 0:
bullet.keep = False
list_of_bullets = [b for b in list_of_bullets if b.keep]

The last line there would be needed because you can get errors if you 
remove entries from a list while iterating through it.


Re: [pygame] Referencing instances by memory address

2010-07-12 Thread Kris Schnee

On Mon, Jul 12, 2010 at 9:25 AM, 音本四 mailto:onp...@gmail.com>> wrote:

In my game that I'm working on, Senso (which is my first game in
Pygame), there is a main game class, Game, which handles things on
the global level. One thing it does is store each instance of game
objects in dictionaries, with the dictionary keys being each
instance's memory address, grabbed with id(). When an instance needs
to be removed, part of the process involves removing the dictionary
reference of the instance, by calling "del
game.myclassdict[id(self)]" (replacing "myclassdict" with the actual
name of the correct dictionary). This seems to cause a problem:
sometimes, this action seems to reference a nonexistant key in the
respective dictionary. I've only experienced it with bullets. I've
checked and double-checked the code, and it doesn't seem that at any
point I forget to add an instance to the dictionary.


Like Brian Fisher wrote, you probably shouldn't be storing references 
this way, since there doesn't seem to be a good reason for it. (We got 
into a fun discussion once about "bullet theology". Should bullet 
objects be destroyed or recycled when their time runs out?)


My guess is that you're experiencing a problem with Pygame's "garbage 
collection" system, which destroys objects once there are no more 
references to them. Maybe Python is destroying your object's ID 
reference before the deletion command is fully carried out, causing the 
id() command to fail?


Re: [pygame] Creating surfaces

2010-06-14 Thread Kris Schnee

On 2010.6.14 7:44 PM, 音本四 wrote:

Traceback (most recent call last):
   File "C:\Users\Jaychant\Documents\Games\senso.py", line 111, in 
 game = Game((640,480), (0,0,0), (0,200,0))
   File "C:\Users\Jaychant\Documents\Games\senso.py", line 54, in __init__
 self.p1 = Player(0,0,(100,100),lncolor,0,(8,64),(16,8))
   File "C:\Users\Jaychant\Documents\Games\senso.py", line 93, in __init__
 self.sprite =
pygame.Surface(size[0]+gunsize[0],max(size[1],gunsize[1])).convert()
ValueError: size needs to be (int width, int height)

Here is what the important variables end up being:
size: (8,64)
gunsize: (16,8)

What I gather from this is that I'm not specifying an integer where I
should be. But I've checked the arguments; The first becomes 8+16=24,
while the second becomes 64.

Can anyone see what's wrong? Am I misinterpreting the error?


I think the key is that the size must be given as _one_ variable which 
is a two-part tuple. So, change the line:

pygame.Surface(size[0]+gunsize[0],max(size[1],gunsize[1])).convert()
To:
pygame.Surface( (size[0]+gunsize[0],max(size[1],gunsize[1])) ).convert()


Hope this helps.

Kris


[pygame] Audio Manipulation: "The Swinger"

2010-06-06 Thread Kris Schnee

http://musicmachinery.com/2010/05/21/the-swinger/

I came across this project, but don't see source code for it. It changes 
a sound file to give music a "swing" effect: lengthened and shortened 
parts of notes. Anyone know if this done with Pygame or just raw Python?


Re: [pygame] online game?

2010-05-23 Thread Kris Schnee

On 2010.5.19 4:14 PM, Enrico Kochon wrote:

Kris Schnee schrieb:
...

One question for others: I'm finding that even though I'm using the
socket.select function to make sure a socket has data waiting, I can't
seem to transmit large amounts of data (more than around 5 KB) without
one side or the other hanging. (I'll have to look at the code more
closely later to be more specific.) Any suggestions? My goal was to have
a server part of my program run independently from both the player
clients and a display client, but this bug seems to force me to develop
some annoying protocol for things like sending a list of objects.
"Prepare for N sending rounds on data for N objects..." rather than
"here's the complete list of objects and their data all at once."


Hi Kris,

Sending more than 5 KB works like a charm if you take care of the amount
of data you want to send...


Okay. Using the code you supplied, I was able to change my server/client 
module "Toomi" to handle long pieces of data, and still correctly handle 
short inputs. Having a 6-byte header isn't efficient for short inputs, 
but since the point of this exercise was to handle long ones, it's a 
good system, and simpler than I feared it'd be. (And as you noted, the 
header length can easily be changed.)


Thanks! The revised code is posted for all to use at:
http://kschnee.xepher.net/code/sockets/

Now I have one less excuse for not working on a particular project. =)

Kris


Re: [pygame] online game?

2010-05-18 Thread Kris Schnee

On 2010.5.18 10:26 PM, Alex Hall wrote:

Hi all,
Before I continue into the strange world of pretty graphics, I want to
check that Pygame can support some sort of online multi-player
implementation. I expect no more than two players at a time. Is it



Is this possible? If so, how (as in where do I want to look)? If not,
is there another library, maybe even one that would tie into pygame,
that would let me do this? Thanks!


The Mastermind library is probably better developed, but you're also 
welcome to use my own module Toomi:

http://kschnee.xepher.net/code/sockets/toomi.py.txt

It's built using the tutorial at http://www.amk.ca/python/howto/sockets/ .

One question for others: I'm finding that even though I'm using the 
socket.select function to make sure a socket has data waiting, I can't 
seem to transmit large amounts of data (more than around 5 KB) without 
one side or the other hanging. (I'll have to look at the code more 
closely later to be more specific.) Any suggestions? My goal was to have 
a server part of my program run independently from both the player 
clients and a display client, but this bug seems to force me to develop 
some annoying protocol for things like sending a list of objects. 
"Prepare for N sending rounds on data for N objects..." rather than 
"here's the complete list of objects and their data all at once."


Re: [pygame] Working with maps

2010-05-18 Thread Kris Schnee

On 2010.5.18 7:43 PM, Khono Hackland wrote:

After reading all these posts, it seems to me the simplest way to do
it, assuming you have to draw out all the countries anyway, is to draw
a layer on the original image with each country being its own RGB
value.  So just draw solid colours of the countires, being as precise
or vague as you care to be, not worrying about keeping to specific
geometric shapes.  The differences could be on just one of the RGB
colour values, so (255,255,100), (255,255,95).  Easy to fit them all
on if you're not really worried about having high-contrast colours.
The layer could be invisible to the player, so, two surfaces.  One
that's blitted to screen and the other with the colours that isn't.
When checking for which country the mouse clicked on, as Henrique
Nakashima said, just check the colour value of the modified-colour
surface.  Based on what colour it is, the program will know which
country.  You could even assign the colours simply based on
alphabetical order of the countries.  So country 1 = (255,255,255), 2
= (255,255,250), etc.  Thus vastly simplifying the testing.  And if a
mouseclick is not on a country but on an ocean or something, the
modified-colour surface won't have a colour there so you don't need to
do any further processing on that click.



But I'm just a newb. so maybe this has huge pitfalls I don't see.


No, that's a known and good technique. Works well with irregular shapes 
or in 3D situations like isometric tiles. One point to emphasize is that 
you don't need to actually show this layer to the player, so it doesn't 
matter if you're using near-identical colors. Eg. just to make a cool 
screenshot (er, properly debug), I drew some isometric tiles with color 
(0,X*10,Y*10) based on their X/Y coordinates, limiting me to 25x25 maps, 
but for actual use I went to (0,X,Y) instead.


Just draw each tile/country/whatever a solid color to some surface 
mirroring the screen the player is seeing, ask "what color is the pixel 
the player clicked on?", then throw away or redraw the surface with your 
real graphics.


Re: [pygame] Rect Behavior

2010-05-16 Thread Kris Schnee

On 2010.5.16 3:25 PM, Ian Mallett wrote:

Hi,

So, I've noticed that, when trying to draw a n*1 or 1*n rectangle (yes I
know a line does the job too) with pygame.draw.rect(...), the behavior
is different for different fills.  When the fill is 0, nothing draws!
When the fill is 1, the desired rectangle is drawn.  Is this the
expected behavior of pygame.draw.rect(...)?

Thanks,
Ian


Probably because the rect function assumes a variable-width border. ( 
http://www.pygame.org/docs/ref/draw.html#pygame.draw.rect ) There's no 
"fill" argument, only a "border width" argument. So if that's 0, Pygame 
probably gets confused and draws 0 pixels of border, 0 of interior.


Why not use pygame.draw.line if you only want one pixel width anyway?


Re: [pygame] Enter name before game starts

2010-04-27 Thread Kris Schnee

On 2010.4.27 3:01 AM, Alex Nordlund wrote:

Basically, I'd like to have the game start, present a screen for the user
to enter their name, then move to the main game loop.



I solved this by having a state variable in my game's mainclass, one
that keeps track of where the game is.
Thanks to sjbrown I have a very nice way of handling input so it was
easy as pie!


I do state management with a homemade module called "ringtale" ( 
http://kschnee.xepher.net/code/ringtale.py.txt ). The idea is that 
there's a main loop that handles Pygame events (including QUIT), and 
calls self.Logic() and self.Draw(), where those two functions are 
redefined based on a current state. Eg. if it's told to push a state 
called "Spam" onto its stack of states, it'll look for functions named 
SpamDraw and SpamLogic, and say self.Logic = self.SpamLogic until 
further notice. So that's one way of doing things like a name-entry 
screen, even in the beginning or middle of another set of functions.


[pygame] RPG Engine

2010-04-17 Thread Kris Schnee

http://kschnee.xepher.net/code/liberty/

I've put up a draft of a new game engine, based on my previous program 
"Morningside". It can serve as the basis for an RPG engine. It offers 
tile-based movement and items, with the logic needed to create items and 
characters, pick things up, move around, and load levels from text 
files. You get a "Zone" class that holds a potentially large area 
(100x100 tiles for an example). For a larger game you could add a means 
of switching to a new zone, or loading more than one at a time. It's set 
up as a 2.5D system in the sense that there's a 2D plane with a 
heightmap. It's meant to be separate from any graphics system (just a 
"model" in the MVC concept), but there's a demo class that turns the 
data into an image, and you could easily extend that (or even adapt the 
Morningside code) to show actual graphical tiles.


This project came about because I'd been wanting to improve on the 
little sim-world I was using for AI stuff, and I tried a Roguelike 
called "Elona" that was too frustrating for me, but with some nice 
graphics and some interesting gameplay.


Re: [pygame] Game engine?

2010-04-16 Thread Kris Schnee

On 2010.4.15 11:49 PM, Mark Reed wrote:

Hey guys, I'm looking for something perhaps where you can specify a
gamefield like:


You might be interested in the code at:
http://kschnee.xepher.net/code/squirrelgame/
Screenshot: http://kschnee.xepher.net/pics/squirrel_game/100202squirrel.jpg

which uses a 2D tile engine and basic physics. You're welcome to use or 
imitate the code.


Re: [pygame] Multiplayer

2010-04-14 Thread Kris Schnee

On 2010.4.13 2:43 AM, Ian Mallett wrote:

Hi,

Not to self-advertise, but I humbly present my networking library,
Mastermind .  It's fairly
lightweight, but it's easy to use and get working immediately and
contains tutorials and documentation.  The underlying code is not
dissimilar from the toomi.py code.



Oh, I should mention that my code is loosely based on the very helpful 
tutorial at http://www.amk.ca/python/howto/sockets/ .


Re: [pygame] Multiplayer

2010-04-12 Thread Kris Schnee

On 2010.4.13 1:21 AM, Daniel McNeese wrote:

I want to make an open source multiplayer game roughly along the lines of 
M.U.L.E.  I've made games before but never done online multiplayer, so I want 
to ask for a nudge in the right direction.  I'd like to spare players behind 
routers the trouble of dealing with port forwarding (I didn't have to do it 
when hosting Alpha Centauri games, so I know it's possible).  Unless pgreloaded 
is far enough along and tools exist for Python 3 (which I'd prefer), I'll 
probably have to use the older stuff.

What's out there for Python that would be suitable?  Any off-the-shelf 
solutions?


You might get some use out of the server/client code here:
http://kschnee.xepher.net/code/sockets/toomi.py.txt


Re: [pygame] GSoC project proposal: A new draw module

2010-04-05 Thread Kris Schnee

I tried to use OpenGL and found that drawing anything in 2D was very hard.
For instance, I couldn't simply build a 3D set of shapes and then draw onto
the screen in 2D, using existing Pygame functions; I had to muck around with
textures instead. And drawing text in OpenGL -- just 2D text on a 2D surface
-- is a nightmare. If people are looking for projects, how about an easy way
to switch to a "Pygame mode" of drawing while using OpenGL, so that we can
use existing UI and drawing libraries?


There is the Lamina module, that provides you a pygame surface within
an OpenGL display, that you can draw on using Pygame drawing libraries
and GUIs.

I have not used it for a year or so, but if you are using
PyOpenGL/OpenGL 2, it should work fine.

http://pitchersduel.wordpress.com/2007/07/13/lamina-v-02/

David Keeney

I am the author, so feel free to email me for assistance, if you
decide to use it.


Neat! Thank you.


Re: [pygame] GSoC project proposal: A new draw module

2010-04-03 Thread Kris Schnee

On 4/3/2010 12:58 PM, jug wrote:

Marcus von Appen wrote:


What would be interesting here is, what the Pen class would offer except
from the drawing functions wrapped up in a class and som additional
shapes.

What about e.g. an aa-property to keep the argument amount low,
transformation and rotation angles for the x- and y-axis (implicit
transformation done upon drawing) or even vector support (e.g. for
faster 2d, 2.5d, 3d operations on the shapes) using the math module?

What do you think about working out some basic Pen (and utility)
class(es) as an example (no need to implement any function or property,
just a stub of the class, we can examine and design)?


I tried to use OpenGL and found that drawing anything in 2D was very 
hard. For instance, I couldn't simply build a 3D set of shapes and then 
draw onto the screen in 2D, using existing Pygame functions; I had to 
muck around with textures instead. And drawing text in OpenGL -- just 2D 
text on a 2D surface -- is a nightmare. If people are looking for 
projects, how about an easy way to switch to a "Pygame mode" of drawing 
while using OpenGL, so that we can use existing UI and drawing libraries?


Re: [pygame] Control Systems

2010-03-30 Thread Kris Schnee

On 3/30/2010 12:41 PM, Cameron Jeffries wrote:

Hi there,
  I became interested in pygame because I have been doing a little
research into building a custom interface for a control system I want to
build.  This would basically just be something that turns on and off
monitors, projectors, controls lighting, etc.  I would like to do this
for a museum I work in, and then distribute freely afterwards because
the control software out there right now is less than optimal.  Has
anyone seen any sort of custom UI built with pygame that would resemble
any sort of a good framework for this?  Is there much of a community for
using pygame as specifically a UI development platform?  Thanks!


There are a couple of interface systems available on the Pygame site. My 
own effort looks like this in a game: 
http://kschnee.xepher.net/pics/080710trade.jpg


So basically there are a bunch of UI projects already, and it's just a 
question of how easy to use, good-looking or otherwise helpful people 
find them.


Re: [pygame] newbie

2010-03-25 Thread Kris Schnee

On 3/25/2010 6:03 PM, sne...@msn.com wrote:

Ah, yes I see what's happening, the last time I was doing it I was using:
...KEYDOWN:
if event.key == K_LEFT:
foreward = True
...KEYUP:
if event.key == K_LEFT:
foreward = False
meaning it was staying true, until key up but now it's not keeping the
output next time round & waiting for it again.
could you elaborate on this bit 'You could make the character move every
frame (eg. setting a speed and
moving by that speed per frame) until a KEYUP event happens', or is that
pretty much what I 'was' doing?


If you said, "On a KEYDOWN event, set speed to N and set direction to 
whatever; and on a KEYUP event, stop," then the result should be that 
the character keeps moving until you let go of the key. If you said, "On 
a KEYDOWN event, move," then you should get one frame of movement each 
time you press (not hold) the key.


My advice is to figure out what the player's trying to do first, like 
"move right", and then actually execute the movement in a separate bit 
of code ("if moving right..."). That's useful for things like replacing 
what keys do what, or having some non-interactive event steer the character.



Could I use "keys_down = pygame.key.get_pressed" then
"if keys_down[K_RIGHT] ## move right",

in this way:
class character():

def update(self, d, sp):
if d == 6:
self.x += sp
elif d == 4:
self.x -= sp
elif d == 8:
self.y -= sp
elif d == 2:
self.y += sp


Why use this odd numeric-keypad code for the direction? Other than the 
variable names and that code, this looks usable. But think about what'd 
happen if I pressed RIGHT and UP at the same time: the code would see 
the RIGHT, set the direction to right, then probably see the UP 
(depending on which was mentioned last in the code) and change the 
direction to up.


A different way to handle the movement would be something like:
player.coords = [42,100] ## some starting value
## In a loop:
movement = [0,0]
if keys_down[K_RIGHT]:
  movement[0] = speed
...
if keys_down[K_UP]:
  movement[1] = speed
...
player.move(movement)

def Move(movement):
  self.coords[0] += movement[0]
  self.coords[1] += movement[1]

You'd then get diagonal movement, and not have to specify the direction, 
and could apply effects like muddy ground multiplying the X and Y 
movement by .5 or something. The actual diagonal speed would be sqrt(2) 
* speed though, which might matter.



def controls():

output = 0
keysDown = pygame.key.get_pressed():


Why is there a colon after the function call? That's only for defining it.

Are you familiar with the "Model/View/Controller" style of organizing a 
game, by the way? It's similar to what you're doing, and pretty useful.


Re: [pygame] Python 2.5.4 or 2.6

2010-03-25 Thread Kris Schnee
On Thu, 25 Mar 2010 12:38:51 -0700, James Paige 
wrote:
> IDLE != python

I should add that my EXE trouble happened while using Py2EXE, which is also
not Python. It could be that Py2EXE simply isn't compatible with Python
versions above 2.5, or with the matching version of Pygame, for whatever
reason.

Re: IDLE, the first thing I do after installing Python (which I've done a
lot lately due to a lemon of a netbook =p ), is to make a shortcut to
"idle.pyw" which is buried in the Python directory structure and really
ought to be better advertised.



Re: [pygame] newbie

2010-03-25 Thread Kris Schnee
On Thu, 25 Mar 2010 19:10:22 -, sne...@msn.com wrote:
> Hi guys.
> 
> I'm new to python and programming in general so expect noob questions :.)
> 
> I've got up to classes & functions & having problems getting round a
little
> input problem.
> 
> I've put my keyboard controls in a separate module from the pygames main
> loop and my 'character' in another module.
> When I was putting it all in one file, if I held left my 'character'
> carried
> on moving left, but now it will only move the specified amount of pixels
> then stop.

I think part of the problem is that you're looking at KEYDOWN events. Those
only happen when a key is pressed, meaning there's only one no matter how
long you hold the key. So the code would make your character move for one
frame, then stop.

You could make the character move every frame (eg. setting a speed and
moving by that speed per frame) until a KEYUP event happens. A different
way to handle things is to use pygame.key.get_pressed() (see
http://www.pygame.org/docs/ref/key.html ), which tells you what keys are
down at the moment you ask. You then say, "keys_down =
pygame.key.get_pressed" then "if keys_down[K_RIGHT] ## move right", and so
on.

One example is in my messy code at
http://kschnee.xepher.net/code/squirrelgame/squirrel4.py.txt , under
"Controls".



Re: [pygame] Python 2.5.4 or 2.6

2010-03-25 Thread Kris Schnee

On 3/25/2010 1:41 PM, B W wrote:

Pygame download page claims "python2.5.4 is the best python on windows
at the moment".
Why should I prefer Python 2.5.4 on Windows?


I've found that when I tried to build a Windows EXE of a program I'd 
written, I got inexplicable errors when I tried to use the latest 
version of Python and Pygame. Only 2.5.4 and the matching Pygame worked 
for EXEs. The experience was frustrating enough -- fatal errors just 
when I thought the project was ready to show off! -- that I've not tried 
since then to use a newer version.


Re: [pygame] super surface... a surface made up of many smallersurfaces

2010-03-10 Thread Kris Schnee
On Wed, 10 Mar 2010 12:38:46 -0600, "RB[0]"  wrote:
> The biggest problem with that is that pygame limits the size of any one
> surface - at least for me.
> I can't remember what it was but somewhere around 16k x 16k pixels?
> 
> On Wed, Mar 10, 2010 at 7:19 AM, Nikhil Murthy 
> wrote:
> 
>> This is not in the least meant to be a serious solution for super
> surfaces,
>> it is just an idea I had and tried out for the fun of it.

It looks like Murthy's solution involves blitting the smaller surfaces onto
a single larger surface. That's a straightforward way to build a composite
surface, but as RB[0] notes it doesn't do anything to save RAM versus
making a giant surface in the first place. I figured we were talking about
ways to get the effect of a giant surface without actually making a canvas
with that many pixels.

Eg., if you want a game level that's 1000x1000 tiles where each tile is
50x50 pixels, making one big surface means a single 50,000x50,000 surface,
2,500,000,000 pixels, times several bytes per pixel depending on color
mode. Ie. several Gb of memory. Not practical! If instead you store each
type of tile as a single 50x50 surface and just reference them with a
list-of-lists (so you can say "draw the tile referenced at
self.tiles[x][y]"), you instead have a 1000x1000 array (1,000,000 entries
times a few bytes) plus the memory usage of (probably) at most a thousand
50x50 tiles (2.5 Mb * bytes_per_pixel). So, a few megs versus a few _gigs_
of memory.

It's the speed and ease of use of this kind of tile-based engine that we've
been talking about optimizing, right? Or do I misunderstand what people
mean by a supersurface?



Re: [pygame] super surface... a surface made up of many smaller surfaces

2010-03-07 Thread Kris Schnee

On 3/7/2010 1:47 PM, B W wrote:
[Me:]

I've done several projects using a full-screen scrolling tilemap.
That is, sprites walking around on a blanket of 2D tiles drawn from
an array as big as 1000x1000 referencing a set of 50x50 tiles.



I did something very similar with Gummworld. The supersurface was not a
single Pygame surface, rather a virtual surface made of a 2D array of
sprites each with its own image. The Pygame drawing surface was the
visible display; only I found that Group.draw()-ing all the terrain
sprites and allowing Pygame to automatically crop them was in larger
cases more efficient than cropping the drawing scope in Python.


Interesting. My method was the obvious one of saying that if the 
player's at tile (100,100), and the screen's 20 tiles wide, then we draw 
a range of 20+ tiles from about 90 to 110. The math _should_ be pretty 
efficient for what it does, so my guess is that the Group.draw() logic 
is something Pygame has pre-optimized with a bit of C code. Maybe I 
should've used Psyco or learned enough C to write my own optimization, 
if it became that important.



if the map is irregular then large portions of the supersurface could
possibly have many unused sprites; which led to a crude sparse map
implementation, where an array cell with a None value would be ignored.


That's what I ended up doing with the recent "squirrel demo": having a 
map with many "None" entries and drawing a tile only if it's not None. 
That seemed to help the speed, but wasn't suitable for the original 
landscape thing I did.



Though the room paradigm seems elegant to me and potentially
memory-efficient, it presents its own significant challenges: resource
management (real-time loading and garbage cleanup); game hiccups from
resource management; spacial relationship of rooms and exit "hot spots";
interacting with objects through an exit; room linkage errors.


Even the professional "Elder Scrolls" games ("Morrowind", "Oblivion" &c) 
had trouble with that. They ended up treating building interiors as 
separate spaces such that you could never look into or out of a 
building, and there were other kludges. In "Oblivion" levitation spells 
ceased to exist, so that cities could become separate world-spaces and 
other areas could be walled off by conveniently placed mountains. 
Another detail was that NPCs could follow you between spaces in 
"Oblivion", but only through an obvious fade-in teleportation method. 
Interestingly, the game engine in "Oblivion" doesn't totally rely on the 
cities being separate spaces; fans have made "Open Cities" mods.



But not for the first time I am thinking it would be awesome to have
some higher level toolkits, somewhere comfortably between Pygame and a
full-blown game engine. It seems many of us have put a lot of time and
effort into such toolkits, with varying degrees of success. I am
wondering if the supersurface would fit better as an "official-like"
Pygame add-on. It might even trigger a series of integratable toolkits
that offer standard ways of solving higher level problems like I've seen
suggested: scenes, tiling, transitions, map scrolling, path-finding. =)
*cough* Me and my grand schemes...


Hmm. I'd be interested in those things too. I've got code for sprite 
animation and A* pathfinding as well as the tile engine, so I'd be 
interested in talking about these and better ways of doing them.


Re: [pygame] super surface... a surface made up of many smaller surfaces

2010-03-06 Thread Kris Schnee

On 3/5/2010 10:40 AM, René Dudfield wrote:

Hello,



pygame already has a subsurface, which is part of a larger surface.
It refers to the same pixels as the surface it comes from.

However, sometimes we would like to operate on a whole bunch of
smaller surfaces stuck together.


I've done several projects using a full-screen scrolling tilemap. That 
is, sprites walking around on a blanket of 2D tiles drawn from an array 
as big as 1000x1000 referencing a set of 50x50 tiles. That wasn't 
practical to do using a Pygame Surface, due to the size, so each frame 
the system figured out the range of all visible tiles (based on the POV 
character's location) and drew those. It wasn't very efficient, but it 
did work, and it's an example of a surface built from many actual 
Surface objects. (Will link to code if you want.)


Years ago, someone posted a demo of a faster scrolling-tile engine, but 
I forget how it worked; if it relies on a Pygame surface that limits the 
practical size of the level.


The pygame.sprite module has never seemed useful to me, because it seems 
like a simple container object (it doesn't have drawing functions) and 
because it assumes that the sprite's pixel size is the same as the size 
of the object it represents. I try to think in terms of a physical unit 
system so that I'm not bound to a particular sprite/tile pixel size. 
Similarly, I always seem to have some reason to redraw everything on the 
screen (maybe wrongly), so I end up treating the whole screen as "dirty" 
and missing any optimization there.


Re: [pygame] DMs, what are you doing?!

2010-02-19 Thread Kris Schnee

On 2/19/2010 6:33 PM, Henrique Nakashima wrote:

The library I've been working on might be useful, if the project is a 2d
tiled RPG:

http://www.pygame.org/project-LibRPG-1293-2321.html

I haven't worked on
it for about two months, but the map part is working nicely, what is
halfway done are menus.


You could use my simple UI library "Driftwood", seen here:
http://kschnee.xepher.net/pics/080710trade.jpg


Re: [pygame] DMs, what are you doing?!

2010-02-15 Thread Kris Schnee
On Sun, 14 Feb 2010 15:27:19 -0800, B W  wrote:
> I'm curious. :)
> 
> Is anybody out there working on a dungeon crawler?
> 
> My interests travel specifically along this line:
> 
>- RP with a storyline and character building
>- PVE
>- real-time combat and movement (not turn-based)
>- melee-range-magic
>- not too deep in stats or skills
>- plans for network co-op a plus
> 
> Gumm

I've wanted to make an RPG for many years, but never went farther with my
own code than building elements like sprite/tile engines, RPG data
structures and experimental battle systems.

(Examples:
http://kschnee.xepher.net/code/080126tactics.zip and
http://kschnee.xepher.net/code/080126tactics_source.zip -- tactical RPG
http://kschnee.xepher.net/code/080301colony.zip and
http://kschnee.xepher.net/code/080301colony_code.zip -- colony-themed RPG
http://kschnee.xepher.net/code/dungeon_maker/ -- procedural dungeon map
maker
http://kschnee.xepher.net/code/mission.py.txt -- RPG teamwork & foraging
mechanics
http://kschnee.xepher.net/code/070629ShiningSeaDemo.zip and
http://kschnee.xepher.net/code/070530ShiningSeaSource.zip -- Real-time
walk-around-a-big-tiled-map system )
http://kschnee.xepher.net/code/080604trade_game.zip and
http://kschnee.xepher.net/code/080610tradegame_source.zip -- trading game )

My problem is that end up flailing on each attempt, because I'm bored with
the mechanics of the "Final Fantasy" games I grew up with (and to some
extent even the sandbox "Elder Scrolls" games). I keep wanting to do
something with more innovative gameplay than a Roguelike or FF game. My
wish list would include:
-Well-integrated story and gameplay, as opposed to non-interactive
cutscenes interspersed with pointless battles
-Battles you won't win by mashing one button; maybe imitate the best
console RPG engines like "Grandia" and "Final Fantasy Tactics"/"Disgaea"
-NOT an MMORPG, because those are overdone, riddled with grinding, and
ludicrously hard to program
-Characters that're unusually interactive and intelligent, bearing in mind
that game AI seems to be a very different field than true AI; Bioware's
games are a step in the right direction

And anyway, RPGs are complex enough that they're hard to do solo, even for
something like a Roguelike. So I've got a bunch of ideas (I write better
than I code) and a bunch of half-baked demos of RPGish things.



Re: [pygame] Problem with simultaneous key presses

2010-02-09 Thread Kris Schnee
On Tue, 9 Feb 2010 07:52:07 -0800, B W  wrote:
> Well crap. I was hoping that it was not woven into the fabric of
> space-time.
> 
> Thanks for the article, René. An explanation is the next best thing to a
> solution. :)

Yeah, it's a problem some of us have encountered before, and it seems to
vary by keyboard so you can't easily plan around it. How about reading a
text file on startup, of the form:
"move_l: k_leftarrow
jump: space"...



Re: [pygame] Squirrel Game Demo

2010-02-04 Thread Kris Schnee

Brian Fisher wrote:
On Thu, Feb 4, 2010 at 12:11 PM, Kris Schnee <mailto:ksch...@xepher.net>> wrote:


<http://kschnee.xepher.net/code/squirrelgame/>I'd appreciate
thoughts on making the movement more satisfying.

Animation can actually make a huge difference on the feel, but there are 
a few things I think would help that are just mechanical.
 
You have decceleration on stopping, which is nice, but you don't have 
acceleration on starting movement...


Also, it would feel a lot more satisfying if the squirrel felt smarter 
when it came to edges of platforms...


Finally, it might be nice to do a little action on jump landing - in 
particular, detect whether I am asking for movement when I land...


http://kschnee.xepher.net/code/squirrelgame/

I was tinkering with the code before seeing this message, so there are 
minor changes already:
-Level size is determined from the level.txt file, so you can make 
arbitrarily large ones. I guesstimate that Python should be able to 
handle *much* larger levels on an ordinary computer.
-Improved wall-grabbing and wall-jumping: You automatically grab walls 
when jumping at them, and don't have to hold any key to hang on. If you 
jump while on a wall, you jump off of it. If you step a bit rightward 
from the start, then leap towards the left wall, you can then reach the 
top platform just by wall-jumping.

-Gliding. Hold Z (which now does nothing else) to fall slower.
-X should also make you jump, if Space isn't working due to that 
keyboard problem.

-Music (gratuitously). Plays the first OGG file it finds in \music.

Based on your suggestions I added acceleration on walking/running. 
"speed = min(current_speed+accel, max_speed)". The difference is subtle 
but really seems to help fine movement. The other ideas sound useful 
too, if I can implement them -- but enough for one night. Thanks!


Currently, holding LeftShift gives you that four-footed pose (with no 
effect on your bounding box yet) plus higher speed. A possible way to 
handle edges better is to resist going over them if you're "walking", 
ie. in the non-shifted upright pose. (The art is of course just a 
placeholder.)


New version uploaded (definitely with source code) to:
http://kschnee.xepher.net/code/squirrelgame/

There's an optional music file from Celestial Aeon Project (jamendo.com) 
that you can put in the music directory if you'd like.


Yesterday I tried out the 2D flash version of "Mirror's Edge" for 
comparison. It ran poorly on my laptop, so it's hard to give it a fair 
judgement, but I found the animation nice but the movement... a little 
off, somehow.


Re: [pygame] Squirrel Game Demo

2010-02-04 Thread Kris Schnee

Thadeus Burgess wrote:

not messy if there is no source to look at :)
-Thadeus


That would help, wouldn't it? Try:
http://kschnee.xepher.net/code/squirrelgame/squirrel3.py.txt


[pygame] Squirrel Game Demo

2010-02-04 Thread Kris Schnee

http://kschnee.xepher.net/code/squirrelgame/
http://kschnee.xepher.net/pics/squirrel_game/
Here's a demo (5 MB EXE w/source) of the little squirrel-game engine
mentioned earlier. The sample level is 100x25 tiles (50x50 pixels each).
Though the code's messy it's actually a partial improvement on my
earlier scrolling-tile engine, due to a steady "camera" that always
draws the PC at a specific pixel location.

I'd appreciate thoughts on making the movement more satisfying.
Possibilities include:
-Gliding: hold Jump when falling to reduce terminal velocity
-Wall-grabbing without holding left/right
-Checking more points below the player, to land on the edges of platforms
-Jumping off walls



[pygame] Squirrelly Movement Physics

2010-01-23 Thread Kris Schnee
I saw a fun demo of an action game where the hero is a bomb-chucking 
squirrel. Though it was fun to run and jump around with that (similar to 
the "Megaman X" series), I wanted to try building movement physics that 
would feel more agile. So here's an experiment using Pygame, using just 
hard-coded blocks for graphics:


Here's the code, declared public-domain:
http://kschnee.xepher.net/code/100123squirrel_demo.py.txt
You'll need the level.txt file in the same directory:
http://kschnee.xepher.net/code/level.txt
The game that got me thinking about this:
http://www.artspots.com/forum/topic/1829/midi-the-squirrel-game-demo

It's kind of fun to move around like this, but doing this sort of game 
would depend more than anything else on getting the movement physics 
*just right*, and it's not there yet. (And second priority would be good 
animation, as with the Apple II-era "Prince of Persia".) I'm not used to 
doing action games, so this kind of code is unfamiliar for me, and often 
turned into an exercise in how many ways you can get a character 
embedded in a wall.


This code got as far as letting you run (arrow keys), dash (hold 
left-shift), jump (space), slide on ice (white blocks), and wall-jump 
(jump while pressing against a wall).


I imagine a game where you're a squirrel-like character with a staff, 
doing a lot of jumping and climbing.
-Maybe a dedicated "grab" button for climbing walls, some of which might 
be in the background.
-Crouch button that would change the character's bounding box, making it 
possible to run/slide through narrow spaces?
-Physics should be biased toward make the character seem agile. Eg. I 
made the "check for a floor beneath player" code check points at both 
bottom edges of the player, which means you can land on the very edge of 
a platform and still balance.
-Air control during jumps is generally good in video games, but I had to 
disable it for several frames during wall-jumps. Maybe when wall-jumping 
from a left wall, temporarily treat holding left as though the player 
were holding right?
-In the "Midi" game I referenced, the hero tends to stop when attacking, 
which doesn't feel right. A staff also feels like a more appropriate 
weapon. Some kind of run-and-whack attack?
-The Midi game also has smooth slopes you can run up/down instead of 
jagged stairs like in my code. I'm not sure how to implement that, 
especially since the Midi game doesn't handle the physics of that 
running quite right. (You visibly fall with each step downhill.)
-Thought about using ODE for physics, but since ODE doesn't do friction 
and would require special cases for stuff like wall-jumping, it might be 
more trouble than it's worth.


Any thoughts or suggestions on this?


[pygame] Keyboard Problem

2010-01-07 Thread Kris Schnee

I'm having a problem with pygame.key.get_pressed(). Any ideas? Sample code:



import pygame
screen = pygame.display.set_mode((100,100))
pygame.init()

def Go():
while True:
keys = pygame.key.get_pressed()
if keys[ pygame.K_SPACE ]:
return
pygame.display.update()

Go()



Result: Program doesn't react to hitting Space, and won't quit till forced.


Re: [pygame] which python and pygame versions?

2009-12-14 Thread Kris Schnee
I had a lot of trouble trying to build an EXE when I used the latest
version of Pygame. What I have installed and working now is Python 2.5,
plus Pygame 1.9.1 (listed on the Pygame download page as the "best
version"). So I recommend those versions.
http://pygame.org/download.shtml


On Mon, 14 Dec 2009 14:24:40 +0800, jun lin  wrote:
> I prefer python 2.6 + pygame.
> 
> On Mon, Dec 14, 2009 at 1:28 PM, Jake b  wrote:
> 
>> I'm installing python + pygame on my new computer, however I'm
> overwhelmed
>> by the choices.
>>
>> Should I do python 2.5, 2.7a, 3.0, 3.1.1, or something else?




Re: [pygame] How do you do the sound?

2009-12-10 Thread Kris Schnee
On Thu, 10 Dec 2009 21:36:10 +0100, inigo delgado 
wrote:
> Hi all:
> 
> And sorry but my not to good english
> 
> I'm pretty new in pygame, and in my freetime i'm doing a shooter based en
> star wars -sh!!! don't tell it to George, he don't know nothing-.
> 
> Well, that's my problem. I'd and pretty xwing firing lasers and frying
> ties,
> so I decided to do the sound with pygame.mixer and...
> 
> #~@|!#¬[ ! It's and incredible lag between the 'key is pressed' and
> 'the
> sound is played' (about one second)
> 
> I have a Ubuntu 9.10, so I googled and saw that the problem should be
(and
> is) in SDL's interaction with pulseaudio (or in pulseaudio itself... i
> don't
> know). Well, I solved it unistalling pulseaudio and installing esound...
> but
> I think thats not the best solution... How do you do ubuntu
compatibility?
> 
> I've ear about pyaudio but I don't know... I'll prefer to ear your
> experiences before learning a new API
> 
> How do you do the sound?

It might help to give more detail about what you're doing, and how.

But you might want to look at where in your program's main loop you're
playing the sound. For instance, is the sound getting called only after
some complex processing of other game events? That would delay the sound.



Re: [pygame] Limited Range?

2009-11-04 Thread Kris Schnee
Oops, yes, I forgot the "abs", but as noted, the speed difference is
negligible.

On Wed, 4 Nov 2009 11:01:53 -0800, James Paige 
wrote:
> part of the overhead comes from looking up "sqrt" in the "math"
> namespace. That can be avoided by doing "from math import sqrt"
> 
> But even then, sqrt() is still slower because it links to the sqrt() C
> function, whereas x**0.5 uses python's own implementation.

Looks like another quirk of Python exposed. Someone on this list also
helped figure out that Python recycles short strings as the same object, so
that for strings less than around 20 characters:
>>> a = "spam"
>>> b = "spam"
>>> a is b
True



Re: [pygame] Limited Range?

2009-11-04 Thread Kris Schnee
On Wed, 4 Nov 2009 09:21:58 -0800, James Paige 
wrote:
> A quick test with the timeit module suggest that the ** operator is not
> slower.

> Here is how I would write the distance check:
> 
> def is_in_range(enemy, tower):
>   return (enemy.x-tower.x)**2 + (enemy.y-tower.y)**2 <= tower.range**2

If speed is important, how about trying a cruder orthogonal method?

def IsInRange(enemy,tower):
return (enemy.x-tower.x) + (enemy.y-tower.y) <= tower.range



Re: [pygame] Strangest thing..

2009-10-24 Thread Kris Schnee

Brian Fisher wrote:
Your script is not creating a window - various things may not work right 
without a window on windows.


If that's the reason, maybe it has to do with SDL itself not being 
properly initialized?


Re: [pygame] Function Inheritance

2009-10-14 Thread Kris Schnee

Kevin wrote:
Don't forget Python supports multiple inheritance as well, which can be 
very useful.


So that'd be like so:

class Basic:
  def __init__(self):
pass
  def DoStuff(self):
print "Hello World"

class Advanced( Basic, SomeOtherClass ):
  def __init__(self):
Basic.__init__(self)
SomeOtherClass.__init__(self)

Basically, putting my basic functions into a class just for the sake of 
copying them all over into a new class at once. I thought multiple 
inheritance was kind of frowned upon...? But it does sound like the best 
route to do what I'm doing in a tidy and reliable way. Thanks to everyone.


[pygame] Function Inheritance

2009-10-14 Thread Kris Schnee

This is more of a general Python question.

I've finished testing a class with some functions I like. I want to use 
those functions in a new class, but not to use the module I just built. 
(Because I might end up with several such classes.) So I'm thinking of 
doing this:


-Make a new module.
-Give it a class that starts with no functions defined.
-Write a module containing the tested functions without their being part 
of a class. Eg.


def DoSomething(self,**options):
  pass

-Import the tested functions as a module called "spam"
-Have the new module's class manually say, "self.DoSomething = 
spam.DoSomething".


Seems cumbersome, doesn't it? I'm basically trying to give my new class 
access to the neat functions while putting them into a separate module, 
so that the main module isn't cluttered by them. Or should I rely on a 
linear chain of inheritance, so that FancyClass is a subclass of 
BasicClass from another module?


Re: [pygame] Python IDE for windoz

2009-10-10 Thread Kris Schnee

What's wrong with the built-in editor, IDLE?


Re: [pygame] Whats wrong in events?

2009-10-07 Thread Kris Schnee
Oh, _that_ error again. I encountered that before. Some keyboards just
aren't able to register certain key combinations like Up+Left+Space. Best
way to deal with it: Just use different keys.

On Wed, 07 Oct 2009 22:34:15 +0200, DR0ID  wrote:
> http://www.sjbaker.org/wiki/index.php?title=Keyboards_Are_Evil
> 
> ~DR0ID
> 
> inigo delgado schrieb:
>> Hi:
>>
>> I have a problem capturing K_SPACE keydown events with pygame.



Re: [pygame] On walking animations...

2009-10-07 Thread Kris Schnee
On Wed, 7 Oct 2009 15:27:08 -0500, Guy Anderson 
wrote:
> I was wondering how one could do walking animations with sprites in
pygame.
> I know that it has been done before, and it probably involves utilizing
> the
> key.pressed function in the Vector2 module, where when you press a key
the
> command retrieves a series of images for the sprite based on certain
> values
> given. I have no idea how to implement this, though, and my theory could
> be
> very wrong. All I know is that it has been done before, so I have hope.
> 
> Yeah.

The Pygame Sprites module doesn't seem to have animation (or much else)
built into it. The general idea of one way to do it is:
-Store the current action a character is performing.
-When a character starts walking, note that it's doing the "walking" action
with some direction.
-Each tick of the game, look at each sprite and set its current image to be
one of several loaded for it. Which? Refer to a dictionary of actions,
where each entry lists a numeric series of frames and how many ticks each
one should be drawn for. Maybe with other information like, "Should I start
this animation over when I reach the end?"

You'd be thinking of the sprites as characters that are doing some action,
with "what frame of animation should actually get drawn?" being secondary.

Code for part of a sprite class:

self.animations =
{"walk_east":{"sequence":[0,1,2,3],"ticks_per_frame":[1,1,1,1],"repeat":True,"animation_to_do_when_this_ends":None}
self.animation_frames = [ """List of Surface objects""" ]
self.current_animation = "walk_east"
self.position_in_anim_sequence = 0
self.current_animation_ticks_within_frame = 0
self.actual_frame_to_draw = 0

def FunctionThatGetsCalledEachTick(self):
self.current_animation_ticks_within_frame += 1
if self.current_animation_ticks_within_frame ==
self.animations[self.current_animation]:
self.position_in_anim_sequence += 1
if self.position_in_anim_sequence ==
len(self.animations[self.current_animation]["sequence"]): ## Go to next
animation or start this one over.

## Finally, set my actual frame drawn.
self.actual_frame_to_draw =
self.animations[self.current_animation]["sequence"][self.position_in_anim_sequence]

Some old code of mine, at
http://kschnee.xepher.net/code/070530ShiningSeaSource.zip , has a module
called "Nixie" that handles sprites by this method. It doesn't bother to
use the built-in Sprite class, because again that class basically does
nothing.

Hope this helps!



[pygame] "Ringtale" Game Framework

2009-09-21 Thread Kris Schnee

http://kschnee.xepher.net/code/ringtale.py.txt

Here's my solution to the problem of organizing the different screens of 
a game. You can use it if you like.


It has states defined by a state name, which is used to find matching 
functions called [name]Setup, [name]Logic and [name]Draw. It runs a loop 
of calling those functions, and maintains a stack of states that can be 
pushed and popped.


This version uses Pygame to allow for music and keyboard event handling.

Demos included.


[pygame] "Morningside" AI Testbed

2009-09-20 Thread Kris Schnee
I was finally able to build a working EXE by once again uninstalling all 
Python versions and installing 2.5.


Here's my program: "Morningside", a little graphical world for external 
programs to interact with. It's a test environment for AIs, to give them 
something to talk about.

http://kschnee.xepher.net/code/morningside/ [EXE]
http://kschnee.xepher.net/pics/morningside [Additional screenshots]
I haven't uploaded the source for the main sim yet, but will do that 
soon, into the same directory as the EXE.


Re: [pygame] EXE: Narrowing Down the Problem

2009-09-18 Thread Kris Schnee
On Fri, 18 Sep 2009 08:10:06 +0100, René Dudfield 
wrote:
> did you read the previous reply to your post?  There's a link in there
> to a working setup.py for python2.6 + pygame.
> 
> cheers,

Yes, thanks. The link to
.

I tried the advice at the top of that page -- copying DLLs -- and that
didn't help. I tried the setup.py and that crashed. “can’t copy
‘installer.nsi’: doesn’t exist or not a regular file”. Odd
considering that installer.nsi isn't on the computer at all. I even got a
Tkinter warning at some point in running that, which is doubly odd because
I don't use Tkinter in my code, haven't used it since installing Python,
and deleted the build directory from previous attempts at this. I tried
asking around on a forum as well, but the advice consisted of that same
link.

This is all with a minimal Pygame program, with a freshly installed copy of
Python, Pygame and Py2EXE, on two different computers, one of which has
built EXEs fine before. And I did manage (when experimenting on the other
last night) to make an EXE if I hacked the entire widget interface out of
my program to eliminate font module references.

Could it be that I'm doing something wrong with the basic steps involved?
-Copy the .py files used in the program to C:\Python26
-Have a setup.py in that directory too
-Open a command prompt and go to C:\Python26
-Type "python setup.py py2exe"
-Go to C:\Python26\dist
-Copy relevant graphics &c. directories into C:\Python26\dist; N/A for test
program
-Type the program's name as an EXE
-Copy *.dll from C:\Python26\libs\site-packages\pygame when that doesn't
work, along with freesansbold.ttf, and try again.

Or could there be some interference caused by other software on my laptop
*and* on a just-bought netbook? I'm trying to find an explanation here as
to whether I'm doing something basically wrong in the process of building
this, or whether I'm genuinely running the same software with the same
commands and getting a completely different result from everyone else.



[pygame] EXE: Narrowing Down the Problem

2009-09-17 Thread Kris Schnee
I've done more testing of Py2EXE and narrowed down my problem with it. I 
can build a working EXE using a minimal Pygame program, so long as I do 
nothing with the pygame.font module, ie. never loading or using a 
font.Font object.


It's been suggested that what an EXE using Pygame needs is to have 
SDL.dll and SDL_ttf.dll copied over to the dist directory, and I used to 
need to copy freesandbold.ttf as well. (I've also tried using arial.ttf.)


Still I get that error on running the EXE:
"pygame_\__init__.pyc", line 70, in __getattr__
NotImplementedError: font module not available
(ImportError: DLL load failed: The specified module could not be found.)

It appears that Pygame has a bug that makes it unusable if you want to 
build an EXE and have text displayed in it.


Is anyone else able to build a working EXE with my minimal Pygame test 
program, and if so, how?


Code:

## pygame_test.py
import pygame
pygame.init()
pygame.font.init() # EXE crash references this line
screen = pygame.display.set_mode((640,480))
screen.fill((0,0,128))
f = pygame.font.Font(None,24) ## Or "arial.ttf"
t = f.render("Here you can see a nice ice key which you can have for 
free.",1,(255,255,255))

screen.blit(t,(10,50))
screen.set_at((10,100),(255,255,0))
screen.set_at((110,100),(255,255,0))
screen.set_at((60,100),(255,255,0))
pygame.display.update()
import time
time.sleep(1.0)

## setup_py
## Command line: python setup_py py2exe
from distutils.core import setup
import py2exe
setup(console=["pygame_test.py"])


Re: [pygame] EXEs: Different Approach

2009-09-15 Thread Kris Schnee

Eric Pavey wrote:

I was having a real hard time, ran across this post:
http://blog.thadeusb.com/2009/04/15/pygame-font-and-py2exe/

Talked with the author, and he provided his setup.py script (available 
from the comments of that post) which I modified, and have been making 
.exe's with ever since, using Python 2.6.2, PyGame 1.9.1


Uninstalled Python, Py2exe and Pygame and did a fresh install of Python 
2.6.2 and matching Py2exe and Pygame.


When I run the script linked to above, it immediately says:
[
Exception in Tkinter callback... Tkinter.py, line 2860, in compare... 
TclError: expected boolean value but got ""

]
And then it seems to run fine, gets to *** copy data files ***, and 
crashes on line 164. "can't copy 'installer.nsi': doesn't exist or not a 
regular file".


As comment #4 on that link says, I get a "font module not available" 
crash if I build an EXE using a simple setup.py (below) and copy 
SDL_ttf.dll and freesansbold.ttf into the dist directory.


# setup.py
from distutils.core import setup
import py2exe
setup(console=["MyProgram.py"])

And the provided script doesn't work either. So, still no working EXE.


[pygame] EXEs: Different Approach

2009-09-15 Thread Kris Schnee

Let me try asking a different and much shorter way:

Has anyone successfully built a working EXE using Pygame and Python 2.6? 
If so, how?


[pygame] EXE Problem

2009-09-13 Thread Kris Schnee
Hello. Rejoining the list for a little while at least. [Re-sending this 
now that I'm actually on the list.]


I'm working on a Pygame project. It works fine in IDLE and running
directly from Windows (double-clicking on the .py file). I'm using 
WinXP, Python 2.6 and/or 2.5.


I want to build an EXE to distribute. I've done this before, using
py2exe, probably back around the time I had Python 2.3. Now, I can build
an EXE, but it crashes on running. This happens no matter what program
or method I use, so I'm getting frustrated. Below are details of my
problem. What am I doing wrong? I'm totally unable to distribute my
programs, even a minimal one designed to test this problem. Should I try
reverting to an earlier version of Python and Pygame?

Short version: Py2exe builds an EXE that crashes due to something about 
a missing mixer and font module. Pygame2exe does the same, but nicely 
packaged. BBFreeze installed with much difficulty, then complained about 
one of its own files/modules being missing.


Details:

Using Py2exe with the command line "python setup.py py2exe" and the 
setup.py:


[
# setup.py
from distutils.core import setup
import py2exe
import pygame.mixer
setup(console=["morningside_server.py"]) ## My main program's file
]

I get this error:

[
C:\Python26\dist\morningside_server.exe\ringtale.py:65: RuntimeWarning:
use mixer: MemoryLoadLibrary failed loading pygame\mixer.pyd
(ImportError: MemoryLoadLibrary failed loading pygame\mixer.pyd)
Traceback (most recent call last):
  File "morningside_server.py", line 30, in 
  File "zipextimporter.pyo", line 82, in load_module
  File "ringtale.pyo", line 65, in 
  File "pygame\__init__.pyo", line 70, in __getattr__
NotImplementedError: mixer module not available
(ImportError: MemoryLoadLibrary failed loading pygame\mixer.pyd)
]

This error can be corrected by copying the file "libogg-0.dll" into the
dist directory where the EXE goes. Now the error becomes:

[
C:\Python26\dist\morningside_server.exe\art.py:119: RuntimeWarning: use
font: MemoryLoadLibrary failed loading pygame\font.pyd
(ImportError: MemoryLoadLibrary failed loading pygame\font.pyd)
Traceback (most recent call last):
  File "morningside_server.py", line 32, in 
  File "zipextimporter.pyo", line 82, in load_module
  File "art.pyo", line 119, in 
  File "pygame\__init__.pyo", line 70, in __getattr__
NotImplementedError: font module not available
(ImportError: MemoryLoadLibrary failed loading pygame\font.pyd)
]

I also tried this setup.py file:
[
# setup.py
from distutils.core import setup
import py2exe
import pygame.mixer
setup(console=["morningside_server.py"],
  options={
  "py2exe":{
  "includes":["pygame.mixer"]
  }
  }
  )
]

I guessed that maybe it was now just missing "libttf.dll", so I tried
copying that as well. But it's already present.

I tried the alternative program "bbfreeze", and after a great deal of
difficulty installing it, got this error:
[
File "C:\python26\scripts\bbfreeze.egg\bbfreeze\freezer.py", line 384,
in _entry_script
IOError: [Errno 2] No such file or directory: 'bdist_bbfreeze'
]

Using this script for it, based on the program's own description page:
[
from bbfreeze import Freezer
f = Freezer("morningside_server")
f.include_py = False
f.addScript("morningside_server.py")
f()
]

I tried a minimal Pygame program just now with Py2exe, viz:
[
## Test program
import pygame
pygame.init()
screen = pygame.display.set_mode((640,480))
f = pygame.font.Font("EagerNaturalist.ttf",32) ## I put this font into 
the dist directory -- works fine in IDLE

text = f.render("Some Text",32,(255,255,255))
screen.blit(text,(100,100))
pygame.display.update()
]

And the same thing happens:
[
NotImplementedError: font module not available
(ImportError: MemoryLoadLibrary failed loading pygame\font.pyd)
]
So it's not due to the complexities of my particular project.


Any help would be appreciated.


[pygame] Re: [pygame] Implementing the A* finder algoritm in a non tile-based game

2009-02-01 Thread Kris Schnee
On Sun, 1 Feb 2009 13:47:04 +0100, Luca  wrote:
> Hi all.
> 
> I'm writing a game where I need to give to enemies a strong AI. This
> will lead me to obtain a path finding algoritm to reach target
> location.

Oh, yeah: another thing to consider is that your pathfinding algorithm
doesn't have to be based strictly on movement costs. In a wargame, for
instance, a weak unit might want to assign a high cost to any areas that
are near visible enemies. In a stealth game, a unit should favor dark
terrain when sneaking.

It's also possible to divide a map into invisible (to the player)
waypoints. FPS games like "Unreal Tournament" seem to use these to guide
characters between map regions.

If you want a thorough discussion of pathfinding methods, including group
behavior and alternatives to A*, you might check out this book:
http://www.amazon.com/Game-Development-Essentials-Artificial-Intelligence/dp/1418038571/ref=sr_1_5?ie=UTF8&s=books&qid=1233539185&sr=1-5



[pygame] Re: [pygame] Implementing the A* finder algoritm in a non tile-based game

2009-02-01 Thread Kris Schnee
On Sun, 1 Feb 2009 13:47:04 +0100, Luca  wrote:
> Hi all.
> 
> I'm writing a game where I need to give to enemies a strong AI. This
> will lead me to obtain a path finding algoritm to reach target
> location.
> 
> All example I can find on the web are related to games based on tiles.
> Anybody has experience on this problem and can help me, or point me to
> a good documentation somewhere?

Yes, looking at that recent thread would be a good idea.

As was noted there, A* isn't dependent on tiles. With a smooth, tileless
map for instance, you could instead sample points N distance units apart.
Or you could treat the map as a set of nodes that has little or no relation
to normal geography; eg. a network of hyperspace routes in a sci-fi game.
The algorithm should work in exactly the same way.



[pygame] Re: [pygame] Sync with vertical refresh does not work(?)

2009-02-01 Thread Kris Schnee
On Sun, 1 Feb 2009 15:37:07 +0100, Matthias Treder
 wrote:
> However, with these settings a new problem arises: Graphics are only
> properly displayed if I use pygame.flip(). When I use pygame.update()
> either nothing appears or the animation is not as intended. Does only
> flip() but not update() wait for a vertical retrace, as it seems to be
> indicated in the docu?
> Does it mean I have to change all my update()s to flip()s now?

I'm surprised that vertical retrace synching is even available anymore, now
that many computer users have stopped using CRT-type monitors. Is the
retrace now being emulated in software in some way?



Re: [pygame] Pathfinding

2009-01-26 Thread Kris Schnee

Yanom Mobis wrote:

1) How is pathfinding done?
2) How do you prevent a moving sprite from being caught in a v-shaped rut made 
of obstacles?  Like this:
   __
A  ->  # |  B
   __|  


Others have already talked about the A* Algorithm 
().


Here's my implementation of it:
http://kschnee.xepher.net/code/080721a_star_pathfinding.zip
Screenshots:
http://kschnee.xepher.net/pics/080720a_star.jpg
http://kschnee.xepher.net/pics/080721a_star.jpg

In English, you have the AI look at a map of costs to enter each area, 
and compute a minimum-cost path. A* automatically handles escaping from 
ruts, by terminating the paths it's considering when they prove too 
expensive. (You can treat walls as having an infinite entry cost.) One 
interesting feature of A* is that it assumes the AI has perfect 
knowledge, something fine for games but flawed for "real" AI.


XKCD's comment on this sort of cost-computation method:
http://imgs.xkcd.com/comics/genetic_algorithms.png


Re: [pygame] recommended network API or game examples?

2009-01-10 Thread Kris Schnee
On Sat, 10 Jan 2009 11:47:23 -0800, "Ian Mallett" 
wrote:
> My networking library on pygame.org has a working chat example.  It works
> both on localhost and over the internet, but the latter requires a
> server-side Python processing--the example of which is currently down. 
It
> should work on localhost "right out of the box" though.
> Ian

Do you mean that it requires a server other than those of the players, or
that one computer must run a dedicated server program, or what?



Re: [pygame] Controlling Display Location on screen

2008-12-18 Thread Kris Schnee
On Thu, 18 Dec 2008 07:44:21 -0800, "Lin Parkh"  wrote:
> Is it possible to set where on the monitor the display will appear? For
> example I would like the pygame display to appear on a second monitor I
> have. I see how to control resolution and size but not this. I am using
> windows btw,

There was a command to center the SDL window, but in a recent version of
Pygame this command just didn't work. The window would appear in a random
place, often hanging over the screen's edge so that the program couldn't be
properly used until the window is moved. I'm not sure whether the problem's
been fixed yet.

I think you need to "import os" and then set an environment flag
("os.setenv"?), and that the flag is "SDL_VIDEO_CENTER", in quotes.



Re: [pygame] "Crazy Machine" type game?

2008-12-01 Thread Kris Schnee
On Sun, 30 Nov 2008 22:57:19 -0200, "claudio canepa" <[EMAIL PROTECTED]>
wrote:
> On Fri, Nov 28, 2008 at 2:44 PM, Joe Strout <[EMAIL PROTECTED]> wrote:
> 
>> Hi all,
>>
>> I'm new to pygame, and only recently returned to Python after nearly a
>> decade in the REALbasic world.  So I hope you'll speak slowly and use
> small
>> words.  :)
>>
>> I've got the bug to create a game similar to the classic games
> "Incredible
>> Machine" and "Crazy Machine".  For those not familiar, it amounts to
> giving
>> the player a palette of pieces that they can arrange in a 2D grid to
> make
>> Rube Goldberg-style machine that accomplishes some goal.  Pieces include
>> weights, balls, balloons, electrical components, fans, candles, rockets,
>> ropes, pulles, gears, monkeys on bicycles, and so on.  It's a little
> like
>> the Flash game "Fantastic Contraption" [1], but with far more (and more
> fun)
>> parts.
>>
>> As an open-source networked game, it could be especially fun, as anyone
>> could contribute their own challenges, and we could keep stats online
>> regarding how many people have attempted or solved each one.
>>
>> Is there already anything like this started in Python?  (I searched the
>> pygame archives, but didn't see anything.)
>>
>> If not, have you any advice on how to approach it in the Pygame world? 
> I
>> was thinking of trying PyODE for the physics simulation (hopefully that
> will
>> run cleanly on all platforms, and not just Windows, as that is a firm
>> constraint for me).  For the graphics, all I need is basically 2D
> sprites
>> that can move, rotate, and change their image -- from the Pygame
> examples
>> I've seen, that should be no problem.  But what do y'all think?
>>
>> Thanks,
>> - Joe
>>
>> [1] http://fantasticcontraption.com/
>>
>>
> 
> There is an old clone like in pygame site, look at
> 
> http://www.pygame.org/projects/21/139/


You might also want to look at "Assembly Line":
http://www.pygame.org/project/735/



Re: [pygame] my rpg game (so far)

2008-11-07 Thread Kris Schnee
On Fri, 7 Nov 2008 15:39:49 -0500, Michael Fiano <[EMAIL PROTECTED]>
wrote:
> Thanks, I got it. However, by having the map drawn to the screen before
> the player, the player is always on top of tiles even when it should be
> behind it. Therefor I still need some kind of foreground layer. I'm not
> sure what the best way to do this is? A subsurface, copy, new surface
> with same dimensions? also how am i going to link both layers together
> and have the player draw in between? Any help is appreciated.

That's a common problem. You're talking about situations like the hero
standing on grass (which should be drawn before him) and behind a tree
(which should be drawn after him), right?

One solution is to make a new layer of tiles that's drawn in a second pass.
Another is to mess with the game's perspective so that this never happens,
eg. you can never walk behind a wall. There are a couple of possible ways
to store a second-layer set of data; either use a second list of what tile
goes where (where most will say "nothing"), or a list specifying only the
spots where there is something (eg. "tree at 42,0"). With the second method
you could treat the in-front-of-player objects as being like sprites in
that they're large things drawn separately from the tiles.



Re: [pygame] Shooting an image

2008-10-13 Thread Kris Schnee
On Tue, 14 Oct 2008 02:49:11 +0800, "yanom @linuxmail.org"
<[EMAIL PROTECTED]> wrote:
> I have this chunk of code that's should make the player shoot a torpedo,
as
> long as their isn't another torpedo on the screen and the player has the
> space key down. Why dosen't this work:
> 
>   
> 
> if key[K_SPACE] and torpedorect.top < -600:
>   torpedorect.left = playerrect.left
>   torpedorect.top = playerrect.top
>   else:
>   torpedorect = torpedorect.move(0,-7)##

Could you please post more context, such as the specific error message or
what you see?
 
I surmise that you've got a "torpedo" object whose location is defined by
"torpedorect," and that you're getting "key" by calling "key =
pygame.keyboard.get_pressed()" to get a table of what keys are currently
being held down. You seem to be recycling the same torpedo by just changing
its location when it's re-fired rather than spawning a new one, which was
the topic of some jokes earlier about "bullet theology."

Not sure why you're doing it this way. Why should you have to hold the key
down to fire instead of just pressing it? And doesn't this code move the
torpedo to be right on top of the player, causing a collision if it's
checked for, and probably a moment of weirdly overlapping graphics?



[pygame] Trade Game

2008-06-11 Thread Kris Schnee

I've built a simple game involving trading. You click on various ports
and offer sets of goods to local traders, trying to get a good deal.
Hit Escape repeatedly to exit (past the map and outro screens).
ZIP w/source: 
Screenshot: 

I'd appreciate suggestions here, because I'm not sure whether this is
actually fun. As usual I can picture this trading thing being part of a
more complex project, or more modestly, as a game where you sail around
trying to get a better ship, more stuff, and the respect of the locals.
But is this little thing something enjoyable? How can it be improved?

An interesting feature of this game is that each NPC merchant has an
estimate of how much they value each product, and a separate estimate of
how much they think _you_ value each. If you offer something, they'll
believe that you value it less. You can hit N during trading to toggle
between verbal comments and a numeric display of traders' estimates.
This system is probably open to abuse. The code at the moment definitely
has a cheat available in that you can withdraw your goods and then
accept the goods the other guy offered.

What's not implemented is the idea of "potlatch," that you rise or fall
in social status with the trader's "tribe" if you're seen as giving a
generous deal. If the game had you interacting with tribes in other ways
than trading, this could be important.

There's some tension here between wanting to make a game of trying to
get a good deal, and having reasonable, realistic behavior from being
able to ask outright for what you want. There's a rudimentary system for
saying "give me some of that and not this," but you're still limited in
what you can express.

Oh, and the code includes a couple of standard modules I've been working
on that might be of use to others. I know the "art" one needs revision;
"ringtale" (program flow) and "driftwood" (UI) may be useful.



Re: [pygame] Re: Assembly Line Game

2008-05-21 Thread Kris Schnee

Greg Ewing wrote:

It seemed that I would load and find that my latest factory
had vanished.


That's a bit of a worry -- let me know if you find a
way of reproducing it.


Aha, I think I've located the problem. I tried loading my game just now,
swept up some parts from the factory floor, looked at a few things, then
hit Escape to save. My game was K2.alg, so I clicked on the line saying
"K2", and said yes, I want to overwrite that save. The game quit
unexpectedly, suggesting that it had crashed. Loading again confirmed
that my game had not been saved.

I ran it in a DOS box (I notice that running it in IDLE instead of just
double-clicking on run_game.py crashes with "no module named main"). I
loaded, then tried saving again, and saw this error (abbreviated):


...in run... handle_mouse... call_handler... mouse_up...
widget.py, line 338, in call_handler...
shell.py, line 124, in save_name
  os.path.basename(new_path), mess))
NameError: global name 'mess' is not defined


By the way, the Supply Hopper is surreal because it drops material
"down" when other devices assume that the factory floor is horizontal.
How about treating it like the Transverse Saw and making its direction
of output be to the right?



[pygame] Assembly Line Game

2008-05-20 Thread Kris Schnee

Hello. I just tried your Assembly Line game and had fun with it. It
makes a nice educational tool, too, forcing you to think about exactly
how to arrange and time the manufacturing processes without imposing a
single right way to build something.

I noted that the tutorial was inaccurate, because in the Mojo Mallet
setup it said to buy 40x10 sheets of material, when in fact you couldn't
buy that size. I was using 50x10 sheets and wasting a lot of precious
veridium, making production unprofitable, but found a somewhat more
efficient method using 50x5 and 50x1 sheets.

Sales of Funky Frisbees seem to fall off dramatically after a few
months. Is this intentional? If so, it's a good idea, forcing you to
develop new products to stay profitable.

The factory animations look buggy when speed is set to high, but this is
probably due to identical parts moving so fast that they seem to be
going backwards.

I had some trouble loading saved games, but didn't manage to pinpoint
the error. It seemed that I would load and find that my latest factory
had vanished. The problem might have been that I was typing in, say, "K"
for the saved game name, rather than "K.alg"... but that theory didn't
hold up when I tested it.

I placed a Packing Station, hit "On," got a "not configured" warning,
then deleted the Packing Station, but the warning icon above where the
machine was stayed on the screen.

In any case, thanks for showing this game off!

Kris



Re: [pygame] full keyboard control

2008-04-09 Thread Kris Schnee
The goal is to have a one-year-old banging on the keyboard for fun? 
Here's a different possible solution: get a different keyboard and find 
a way to manually pull off/break the Windows and Tab keys! You can 
probably get a cheap one, and that saves you from wear/spills/etc on 
your main keyboard.


[pygame] Screen Centering Trouble

2008-03-17 Thread Kris Schnee

os.environ["SDL_VIDEO_CENTERED"] = "1" ## Center the graphics window.

This line used to work for putting the SDL window at the screen's 
center, but now it doesn't. I see that there was a recent thread about 
this, but I'm not sure what I'm doing wrong here.


Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit 
(Intel)] on win32

>>> import pygame
>>> pygame.ver
'1.7.1release'

I installed the latest Python 2.5-based edition of Pygame straight from 
pygame.org, so this shouldn't be a problem.


[pygame] Angle To Target Function

2008-03-12 Thread Kris Schnee

Just thought I'd offer this function, which might be useful for
characters with following behavior. It finds the angle from one point to
another, in degrees, with 0 being "up" and 90 being "right." It's
therefore useful for deciding whether a target is to a character's right
etc., and it's easily changed if you don't like the scale I used.

--

import math
def AngleToTarget(dx,dy):
"""Returns the angle to a point (dx,xy) in degrees.

0==up/north, 90==right/east, 180==down/south, 270==left/west.
"""
if dx == 0: ## Special case to prevent zero-division
if dy > 0:
return 180
elif dy < 0:
return 0
else:
return None

oa = float(dy)/float(dx)
theta = math.degrees(math.atan(oa)) + 90.0

if dx > 0:
return theta
else:
return 180+theta

return theta


## Demonstrate the function graphically: show angle from a "sun" to your
cursor.
import pygame
pygame.init()
from pygame.locals import *
s = pygame.display.set_mode((500,500))
font = pygame.font.Font(None,36)
done = False
while not done:
for event in pygame.event.get():
if event.type == KEYDOWN:
done = True

x, y = pygame.mouse.get_pos()
dx, dy = x-250, y-250
theta = AngleToTarget(dx,dy)
s.fill((0,0,0))
pygame.draw.circle(s,(255,255,64),(250,250),10)
t = font.render(str(int(theta)),1,(255,255,255))
pygame.draw.line(s,(128,128,128),(250,250),(x,y))
s.blit(t,(0,0))
pygame.display.update()



Re: [pygame] Sticky Variables: Terrain Loading

2008-03-11 Thread Kris Schnee

Dave LeCompte wrote:

I did notice that you were using "y" as both a coordinate and as a flag
for whether the current pixel is yellow. Do you still have trouble if you
don't reuse "y" in this way?


Oops. I tried calling it "yellow" instead, and it suddenly works. I 
don't understand _why_ it works though, and this bothers me. Re-using 
variable names like that is bad, of course, but in this case the first 
version of "y" is being used to get the color of the test image at a 
certain pixel, and then "y" is used to represent whether that pixel is 
yellow. Since the color is already gotten by the time "y" is changed, 
using "y" for "yellow" should have no effect -- and I don't see why it 
would lead to the "sticky variable."


The loop says "for y in range(something)." I thought that loops used 
each value in the list produced by the range statement, so that Python 
would be unaffected if I changed y during the loop.



Douglas Bagnall wrote:

There is no point deleting the terrain label.  The trouble is you're
trying to do things the wrong way. Perhaps you should explain why it
matters, and we can show you a different way to deal with that.


My intent was to have a list of N*N entries representing the terrains 
stored at each spot in an N-size terrain map. I have code that reads 
those entries and picks graphical tiles based on those. If the entries 
are recorded according to the pixels of a map file, I can load an image 
and use that as a set of game terrain. If (as happened here) the act of 
adding entries to the terrain list just adds the same thing over and 
over despite my trying to tell it "no, add this new value," then map 
loading won't work.


In this case the exact thing I was doing doesn't much matter because I 
wanted to test loading from a particular image, and realistically I plan 
to use fixed colors (eg. grass is always (0,255,0)) or not use 
image-loading at all. Still, I'm curious as to what went wrong.


[pygame] Sticky Variables: Terrain Loading

2008-03-11 Thread Kris Schnee

I've encountered another case of variables being taken as references
rather than values. In trying to load an image and use its colors to
decide which of several terrains to add to a growing list, I did this:

for y in range(self.size):
for x in range(self.size):
rgb = the_map.get_at((x,y))
r = rgb[0] > 100
g = rgb[1] > 100
b = rgb[2] > 150
y = r and g
if b:
terrain = "water"
elif y:
terrain = "sand"
else:
terrain = "grass"
self.land.append(terrain)
del terrain

Ie., look at pixel (x,y) in the_map and pick a terrain based on the
colors. The problem is, the program decides that it's adding references
to the same variable, "terrain," rather than doing what I want: adding a
string. The result is that every entry in the "land" ends up being not
only identical, but the same entry. Even though I "del terrain" to make
it plain that I want to create a new variable.

g.world.land[0] is g.world.land[1]

True

I can fix the problem here just by saying "if b:
self.land.append("water")", but I'd like to know the underlying problem
here. The "del terrain" line was an afterthought because I assumed that
"terrain" went out of scope every pass through the loop, or that by
assigning it a new string value Python would understand that I want to
add the _string_ to the list and not a reference to the variable; and I
would think that "del terrain" should unambiguously say STOP KEEPING
TRACK OF THIS VARIABLE. So, what am I doing wrong here?

In contrast, my random-terrain code used in a test works fine:
terrain = ["grass","sand","water"][random.randint(0,2)]
self.land.append(terrain)




[pygame] "Colony" Demo

2008-03-10 Thread Kris Schnee
Oh, I had forgotten to post it here: There's a demo released of my 
"Colony" game.


I'm on a dial-up connection so I uploaded one version with a Windows EXE 
and the media the program requires, and a separate version with just the 
source.

http://kschnee.xepher.net/code/080301colony.zip
http://kschnee.xepher.net/code/080301colony_code.zip

Screenshots:
http://kschnee.xepher.net/pics/080223colony.jpg
http://kschnee.xepher.net/pics/080223colony2.jpg

I was asking on GameDev.net about a basic problem with my idea. (104 
views, no replies?) I've got the suspicion that my premise for this game 
system is flawed. I know the included scenarios are junk, and had come 
up with better ones to implement in the next demo, but am not sure about 
the basic idea now.

http://www.gamedev.net/community/forums/topic.asp?topic_id=485995


Re: [pygame] Event Stack Weirdness

2008-03-07 Thread Kris Schnee

Lenard Lindstrom wrote:
pygame.quit() must be explicitly called since atexit functions are not 
executed until IDLE's nteractive interpreter is either closed or restarted.


What are the atexit functions, though, that interfere in this very 
specific case?


[pygame] Event Stack Weirdness

2008-03-07 Thread Kris Schnee
I encountered a strange bug. I'm using my "ringtale" game framework, 
which uses a stack of game states. It looks something like this:


class Framework:
def __init__(self):
self.states = []
def Push(self,state):
self.states.append(state)
def Pop(self):
if self.states:
self.states.pop()
else:
raise "No states to pop!"
def Loop(self):
## Based on current state, run logic and drawing functions.
## If certain stuff happens, pop the current state.


Now, if I load my game in IDLE, it runs. If I then run it _again_ 
without closing IDLE, it crashes, giving the no-states-to-pop message! 
Closing and restarting IDLE lets it work again.


At the bottom of my code I create my Game object based on the Framework 
class: "g = Game()". So it _should_ be making a new instance every time 
I run the program, and the id() function suggests it is. One run should 
have no effect on subsequent runs.


I thought maybe this problem had to do with the logic loop I was using:
for event in pygame.event.get(): ## If stuff, then end loop

So I tried making a minimal Pygame program that creates a screen and 
runs a loop till a key is pressed -- no Game object, no stack. I ran 
that, then loaded my game and ran that -- and the game crashed the 
_first_ time, with the no-states error again!


I narrowed down the error a bit. If I load and run the following program 
in IDLE:

import pygame
screen = pygame.display.set_mode((100,100))

...And then run my game, it crashes on the first run. If I comment out 
the screen-creating line above, it does not.


It seems that running a program with a Pygame screen, at all, somehow 
interferes with my program, causing it to decide that an object's 
internal event stack is empty despite it being told to put something 
there. What's going on?


[pygame] Pixel Ships: Rotation

2008-03-06 Thread Kris Schnee

Here's a bit of code that turns one animation frame into a strip
containing rotated versions of that frame. It uses the "pixel ships"
code I posted recently and demonstrates a ship rotating. (Hit Escape to 
quit.) Rotations of 10 or 22.5 degrees seem to give smooth-looking rotation.


A friend is interested in getting a single-player PC version of the game 
"Binary Homeworlds," made for the Icehouse system. (Anyone interested?) 
I could also imagine these rotating ships being used for something 
inspired by "Sinistar," "Starfox," "The Ur-Quan Masters," "Zone 66," or 
"Gate 88."


import random
import pygame
from pygame.locals import *
import pixel_ships
SCREEN_SIZE = (1024,480)
screen = pygame.display.set_mode(SCREEN_SIZE)

def MakeSpriteFromFrame(frame,angle_per_frame=45):
## Make the frames, meanwhile determining which is biggest.
frames = 360 / angle_per_frame
max_size = 0
frameset = []
for n in range(frames):
img = pygame.transform.rotate(frame,n*angle_per_frame)
size = img.get_size()
if size > max_size:
max_size = size[0]
frameset.append(img)

## Now combine those into one image strip.
sprite = pygame.surface.Surface((max_size*frames,max_size))
for n in range(len(frameset)):
size = frameset[n].get_size()[0]
##if size < max_size:
##x = (n*max_size) + (max_size-size)/2
##y = (max_size-size)/2
##else:
##x = n*max_size
##y = 0

x = (n*max_size) + (max_size-size)/2
y = (max_size-size)/2

sprite.blit(frameset[n],(x,y))
return sprite, max_size, frames

s = pixel_ships.MakeShip(pixel_ships.BASE)
s = pygame.transform.scale2x(s)
s = pygame.transform.scale2x(s)

angle = 10 ## Try 45, 22.5 or 2 also. 1 makes Pygame crash for me -- big sprite.
ship_sprite, frame_size, frames = MakeSpriteFromFrame(s,angle)

screen.fill((0,0,150))
screen.blit(ship_sprite,(0,50))

clock = pygame.time.Clock()
frame = 0
done = False
while not done:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
done = True

screen.fill((0,0,0))

screen.blit(ship_sprite,(100,100),(frame*frame_size,0,frame_size,frame_size))
pygame.display.update()

frame += 1
if frame == frames:
frame = 0

clock.tick(20)



[pygame] Pixel Spaceships

2008-03-05 Thread Kris Schnee

Nick Moffitt wrote:

René Dudfield:

I like space ships.


I made some fun Pixel Spaceships:

http://zork.net/~nick/pixel/blackspace.py

They're based on http://www.davebollinger.com/works/pixelspaceships/


Fun little exercise. Here's my version of the ship generator, attached.
Screenshot: 
I didn't get the cockpit designs "right" in the way Bollinger did, but 
tried superimposing a smaller ship design atop a larger one to get a 
two-tone effect (not seen in that shot).


I tried rotating a ship to build a list of rotated images, but the 
rotated versions are often larger than the original, making it hard to 
figure out where to place them. How can that problem be addressed?


[pygame] Corrupted Code

2008-02-22 Thread Kris Schnee
Earlier today I was coding intensively enough that my laptop ran out of 
power. Although I kept saving my work in the process of testing things, 
when I later powered up the laptop, I found that my main program had 
been overwritten by what shows up as a bunch of little squares. I'm not 
sure why this happened, and am not pleased, as my most recent backup 
copy is from 1.29. Is there anything I can do about this?


[pygame] Puzzle Game

2008-02-17 Thread Kris Schnee

http://kschnee.xepher.net/pics/080217puzzle.jpg (slightly outdated)
http://kschnee.xepher.net/code/080218matchgame.zip

This weekend I built a little tile-matching game with totally unoriginal 
gameplay in the style of puzzle games like "Bejeweled." Actually I've 
never played that one; I was inspired by a demo of "Puzzle Quest," which 
impressively dressed up the same game mechanic with graphics, music, a 
plot, and RPG mechanics.


The above ZIP file includes a Windows EXE, plus graphics, music and 
source code. Thanks especially to LostGarden ("PlanetCute" graphics) and 
Jamendo.com (music).


Kris
(Hmm. "Tetris Attack," "Dr. Mario," "Dr. Robotnik's Mean Bean Machine"...)


Re: [pygame] PyGame / PyOpenGL Example

2008-02-13 Thread Kris Schnee

Brian Fisher wrote:

... Also, I have to say that at first I thought it would be a "Royal
Pain" to have to deal with rendering 2d stuff in openGL - but it
actually turned out to be much easier than I thought and kind of a lot
of fun (although I may have more pain later I suppose). The only thing
that isn't trivially simple, in my opinion, is figuring out how you
want to deal with texture size limitations. In particular, on the
majority of systems out there, textures have to be a power-of-2 in
width and height - so you have to deal with that to upload say a 24x12
image for blitting. The 3 basic approaches are:
1. overallocate textures and render just the portion of the texture
that has an image (so that 24x12 image would be on a 32x16 texture and
would render just texcoords (.0,.0)-(.75,.75)), which will waste about
50% of your video memory and possibly cause extra texture thrashing,
but actually some commercial games ship this way cause it just never
ended up being a problem for their game.
2. spread images across multiple textures and draw all of them (so the
24x12 image would be spread across 4 textures, a 16x8, an 8x8, a 16x4
and an 8x4) which lets you draw more polys in order to not waste so
much video memory
3. pack multiple images into a single texture - the attached example
uses that approach. It can be pathologically bad in terms of memory
thrashing in some cases (like say if you wanted to draw one image each
from 100 large multi-image textures) but if images that are used
together are in a texture together, it is actually the optimal
approach in terms of performance (like it tends to be good to make
sure font characters are all packed in textures together)


Thanks for the code.

So, if I wanted to draw a GUI window across the screen, and I'd normally 
want it to be, say, 800x200, I'd have to either split it and draw two 
textures, or make the texture 1024x256, or just draw a polygon with 
shading provided by OpenGL and use that as the window?


[pygame] Pygame Blender Script

2008-02-13 Thread Kris Schnee
Is there any indication of how to use the Pygame Blender script that's 
on the Pygame site -- the one that renders a Blender model to a sprite? 
The included documentation doesn't really explain.


[pygame] Automatic Import Problem

2008-02-13 Thread Kris Schnee
I noticed a problem over lunch. I was trying to re-incorporate that 
little 2D tiled graphics engine into my latest project (is there a 
commented version of that super-fast one someone posted?), and found 
that it seemed to be importing my "art" module, even though that module 
wasn't in the same directory. I think that Python was loading _a_ 
version of "art.py" from _somewhere_, and the fact that I can't tell 
from where bothers me. What are the circumstances in which this happens?


Re: [pygame] PyGame / PyOpenGL Example

2008-02-13 Thread Kris Schnee

Richard Jones wrote:

On Wed, 13 Feb 2008, René Dudfield wrote:

Apart from Richards shameless self promotion of pyglet, here's some
other things to look at...


It was more an attempt to dispel the "even in Python" statement :)


Heh. Thanks, both of you.

It looks like with Pyglet I'd need to learn its equivalents to Pygame's 
event handling, although that doesn't look too complex, and in exchange 
I'd get the ability to load textures and draw images and text easily 
while still being able to use standard OpenGL drawing functions. Maybe 
that's worth trying.


I'm having a hard time figuring out which of these many systems is best 
for my purposes, if I'm to do 3D. Am I making a mistake by looking at 3D 
at all? Since I'm working alone I have no ambitions to do full 3D 
animation; basically it'd be a way to represent a landscape with height. 
The terrain I'd like is a simple island landscape with rocks, trees and 
buildings, like this: 
 
Does it make sense to go to the trouble of a 3D engine to get the 
flexibility of being able to look at the terrain from any angle?


Maybe I'm answering my own question here. I'm basically looking for eye 
candy instead of focusing on the gameplay concepts I want to develop.


[pygame] Tactics Game Demo

2008-01-29 Thread Kris Schnee
Oh! I forgot to mention that I'd finished the new demo of my tactical 
combat game.


 (Windows EXE)
 (Source version)

It's still messy, but closer to being an actual game in that it's got 
data loaded from files, multiple attack types, and a sequence of battles 
interspersed with story scenes.


Re: [pygame] Mode 7 Demo

2008-01-26 Thread Kris Schnee

bhaaluu wrote:

Do you have a link to landscape.bmp and sky.png?

Traceback (most recent call last):
  File "mode7.py", line 9, in ?
ground = pygame.image.load("landscape.bmp") ## 1000x1000 works
pygame.error: Couldn't open landscape.bmp

Traceback (most recent call last):
  File "mode7.py", line 10, in ?
sky = pygame.image.load("sky.png") ## At least 800x300
pygame.error: Couldn't open sky.png

I converted  the landscape.jpg to landscape.bmp to get the second Traceback.

This looks nice!
Arigato!



You can use any suitably-large files in place of the landscape and sky I 
used. But I'll put them up:


Just replace "landscape.bmp" with "landscape.png" in the code then.
Also, if you download the new version of the code, at:

You'll find a version that will generate crude substitutes if the files 
aren't found, so you can see the mode 7 effect without having the images.


Note that the landscape draws every other horizontal line, so if there 
are 300 lines of land drawn, you'll need at least 600 lines of actual 
landscape to avoid getting black areas at the bottom of the screen.


If I try using this with my tile engine (which was my source for the 
landscape image), I'll be generating the 2D base image on the fly rather 
than loading a humongous source image like this.


[pygame] Mode 7 Demo

2008-01-26 Thread Kris Schnee
I put together a quick-and-dirty demo of a "Mode 7" pseudo-3D effect. I 
have no specific plans for it, but it looks neat. The framerate is bad. 
Thoughts?


Screenshot at .
Example of the effect in "Secret of Mana": 



Kris
"""
Quick demo of a "Mode 7" pseudo-3D effect,
as seen in some 16-bit-era video games.
"""

import pygame
screen = pygame.display.set_mode((800,600))

ground = pygame.image.load("landscape.bmp") ## 1000x1000 works
sky = pygame.image.load("sky.png") ## At least 800x300

## Fog @ horizon.
fog = pygame.surface.Surface((800,20)).convert_alpha()
for y in range(20):
a = 200 - (10*y)
pygame.draw.rect(fog,(255,255,255,a),(0,y,800,5))

class Mode7:
def __init__(self,**options):
self.sky = options.get("sky")
self.ground = options.get("ground")
self.fog = options.get("fog")
## "Location" of the top-left part we'll draw.
self.ground_x, self.ground_y = options.get("coords",(0,0))
self.movement = options.get("movement",(3,3))

def Draw(self):
stretch_factor = 200.0 ## Try eg. 75.0 also
for y in range(300,600):
## Take a line from the original & stretch it.
img_y = (y+self.ground_y-300) * 2
line = pygame.surface.Surface((800,1))
line.blit(self.ground,(0,0),(self.ground_x,img_y,800,1))
w = 800 * (1.0 + ((y-300)/stretch_factor) )
x = -(w-800)/2 ## Draw wide line left of screen's edge
line = pygame.transform.scale(line,(w,1))
screen.blit(line,(x,y))
screen.blit(self.sky,(0,0),(200,0,800,300))
screen.blit(self.fog,(0,300))

def Go(self):
for n in range(40):
##screen.fill((0,0,0)) ## Not needed; screen is filled
self.Draw()
pygame.display.update()
self.ground_x += self.movement[0]
self.ground_y += self.movement[1]


m7 = Mode7(sky=sky,ground=ground,fog=fog)
m7.Go()


[pygame] Toolset

2008-01-24 Thread Kris Schnee

http://kschnee.xepher.net/code/schnee_tools_demo.zip>Toolset
After basically getting through a demo of my tactics-combat game and 
thinking about too many ideas as usual, I sat down and focused (by 
accident) on improving the underlying tools I developed for various 
things. These modules include an interface (Driftwood), sound code 
(Conch), graphics-loading (Art), and main game logic (Ringtale), all 
built atop Pygame. With their powers combined, a demo application scans 
available art, plays looping music, displays info in an interactive 
interface, and wraps all that in a good, easily extended logical 
framework. This stuff refines the tactics game's code.


So, if for some reason you want it, it's posted above. Public domain. 
Overall it's still crude, but I'm proud of it, I plan to make good use 
of it, and it may be useful to others.


Re: [pygame] Ideas about storing questions/answers for a boardGame.

2008-01-24 Thread Kris Schnee
This is what I was going to suggest, for a way of storing questions in 
plain text format. You could add additional info like a category by 
specifying that, say, the second line in each block is the category.



f = open("questions.txt","r")
text = f.read()
c.close()
paras = text.split("\n\n")
questions = []
for para in paras:
lines = [line for line in para.split("\n") if line and line[0] != "#"]
question = lines[0]
answers = lines[1:]
questions.append((question,answers))


Then you can just have a text file like so:

# Lines starting with # are ignored
What is your name?
Arthur
Lancelot
Galahad

What is your quest?
I seek the Holy Grail
I seek a shrubbery
## Specify African/European?
I seek an unladen swallow

What is your favorite color?
Red
Blue
Yellow


Just be sure that the first line of every block of lines is the
question, and that every pair of questions is separated by one blank line.


[pygame] "Driftwood" UI (better)

2008-01-22 Thread Kris Schnee

Try this version instead:
http://kschnee.xepher.net/code/driftwood.py

I added a text box that holds multiple lines of text, and a fancier 
"Scroll" class that can be scrolled and hold more text than is visible 
at once. (Slight flaw: if you're adding single characters at a time, you 
may get extra spaces inserted; the system assumes it should break the 
text into space-delimited words.)


This is still pretty rough, but usable. I may upload another version 
later to the same URL.


[pygame] "Driftwood" UI

2008-01-22 Thread Kris Schnee
Over lunch I cleaned up the latest version of my UI code, which is 
attached. This version just contains a generic text-displaying widget 
and a Button that responds to clicking, with a simple solid-color or 
gradient look. I hope to add more widgets to this by cleaning up and 
modifying older code.


Even in this incomplete version, it might serve as a low-end system for 
people looking to make a couple of buttons and text labels as quickly 
and simply as possible. It's public domain if you'd like to use it.


Kris
#!/usr/bin/python
"""
Driftwood v3
by Kris Schnee.

A simple graphical interface (ie. system of buttons, meters &c).
The goal of this system is to provide an interface in a way that is very
simple to use, requires no dependencies but Pygame, and doesn't take over
your program's event-handling loop. It should serve as a basic UI system
for those whose main concern is to get basic interface elements working
quickly, as opposed to a full-featured game engine.

The interface is divided into "widgets" that can respond to events.
To use this module, create a list of widgets, eg "self.widgets = []".
Each widget should be passed an "owner" reference.
Display the widgets by calling eg.:
for widget in self.widgets:
widget.Draw() ## Draws to a Pygame Surface object called "screen".
To make them respond to events, call in your Pygame event loop:
for event in pygame.event.get():
handled = False
for widget in self.widgets:
handled = widget.HandleEvent(event)
if handled:
break
if not handled:
## Put your own event-handling code here

To get information back from the widgets handling events, your game should
have a "Notify" function that puts this info on a stack of some kind for
your game to react to it. The widgets will call Notify and pass along a
dictionary object describing what happened; you can then respond to these
events or not.

See the demo for how all this comes together.
See also my "Ringtale" module for one method of organizing a game's states.

Currently available widget types:
-Widget (generic)
-Button
I'm in the process of rebuilding this module from a past version.

Module Contents (search for chapter symbols):
~Header~
~Imported Modules~
~Constants~
~Classes~
~Functions~
~Autorun~ (the code that runs when this program is run)
"""

##___
##  ~Header~
##___

__author__ = "Kris Schnee"
__version__ = "2008.1.22"
__license__ = "Public Domain"


##___
##  ~Imported Modules~
##___

## Standard modules.
import os

## Third-party modules.
import pygame ## Freeware SDL game toolkit from 
from pygame.locals import * ## Useful constants

##___
##~Constants~
##___

## Look in these subdirectories for graphics.
## I assume a "graphics" subdir containing subdirs for "interface" and "fonts".
GRAPHICS_DIRECTORY = "graphics"
INTERFACE_GRAPHICS_DIRECTORY = os.path.join(GRAPHICS_DIRECTORY,"interface")
FONT_DIRECTORY = os.path.join(GRAPHICS_DIRECTORY,"fonts")
DEFAULT_FONT_NAME = None

##___
##~Classes~
##___

class Pen:
"""A wrapper for pygame's Font class.

It offers a simple text-writing function and is used by widgets."""
def __init__(self,filename=DEFAULT_FONT_NAME,size=30,color=(255,255,255)):
if filename:
filename = os.path.join(FONT_DIRECTORY,filename)
self.font = pygame.font.Font(filename,size)
self.color = color

def Write(self,text,color=None):
"""Return a surface containing rendered text."""
if not color:
color = self.color
return self.font.render(text,1,self.color)

class Widget:
def __init__(self,**options):
self.owner = options.get("owner")
self.name = options.get("name")
self.coords = options.get("coords",(0,0,100,100)) ## Pygame Rect 
object, or tuple.
self.coords = pygame.rect.Rect(self.coords)

## Display surface.
self.surface = pygame.surface.Surface(self.coords.size)
self.dirty = True

## Graphics options.
self.visible = options.get("visible",True)
self.pen = options.get("pen",DEFAULT_PEN)
self.text = options.get("text","") ## Displayed centered.
self.rendered_text = None ## A display surface
self.SetText(self.text)

"""The first color is always used. If a

Re: [pygame] File Loader Window

2008-01-20 Thread Kris Schnee

Bernard Quinn wrote:
I'm using Python 2.5 and can't get Ocemp to cooperate without numeric. 
The example documentation for PGU is a bit too sparse for this newbie to 
fathom... exactly what imports and such do I need to add to get the 
basic 'hello world' example to work?


Maybe it'd help if you'd specify what you want to use it for. A "file 
selector window" is a pretty complex thing, that normally takes a 
complex GUI system to have enough code that you can invoke it easily... 
and to use a complex GUI system takes some effort anyway.


Is there a specific thing you want to do with files?


[pygame] pygame.display.set_icon()

2007-12-24 Thread Kris Schnee
I notice when calling "pygame.display.set_icon()" that this function 
changes the icon displayed in the Windows taskbar, but not on the actual 
game window. Also, when hitting Alt-Tab to switch between programs, my 
game window is represented by a glitchy version of the icon -- shot 
through with white static. How do I fix these problems?


[pygame] UI Blues

2007-12-23 Thread Kris Schnee
In revisiting my interface code, in light of what I've learned from the 
tactics-game project, I've hit a snag.


Earlier, I'd set up my interface so that hitting a button or something 
would cause the button to call a "Notify" function of the main game 
object, sending it a dictionary describing what happened. 
{"headline":"click","sender":self} That meant having a special event 
queue in the game object, to be added to by Notify and read by a game 
loop. That is:


-In Screen X, there's an interface. The user hits a button.
-The button calls Notify.
-The loop for Screen X sees that an "Button B was clicked" message has 
appeared, and reacts to that.


That's the "poorly-formatted random data" situation I was trying to 
avoid, but I don't see how it _can_ be avoided. With the tactics game I 
was getting around it by having ad-hoc variables attached to the 
game-world object, rather than a generic message queue.


Another approach to UI handling I've had suggested is to have a double 
event-handling system. The first part handles raw Pygame events and adds 
to a queue of _gameplay_ events, to which the UI can also add. The 
second part handles the gameplay events, like so:


for event in pygame.event.get():
if event.type == KEYDOWN and event.key == KEYS_JUMP:
self.game_events.append("jump")

for event in self.game_events:
if event == "jump":
self.player.Jump()
elif event == "pause_button_clicked":
self.Pause()

Does this setup make any sense?


[pygame] Tactics Game Updated

2007-12-21 Thread Kris Schnee
Here's a new release of my tactical combat game, provided as a ZIP with 
a Windows EXE and source:

http://kschnee.xepher.net/code/071220tactics.zip
Screenshot:
http://kschnee.xepher.net/pics/071220tactics.jpg

New features include actual enemy AI, random battles, terrain, and life 
meters. And nerfed scouts.


I notice that while the console window (which I want to get rid of) 
displays the custom icon I made due to "pygame.display.set_icon," the 
actual Pygame window shows a generic icon, not even the Pygame icon. How 
do I fix that?


I'm interested in developing this game further. The next thing to do 
would be to have menus for multiple commands, showing off a few variant 
moves with different range and power. Followed by some combination of:
-A real graphics system (dig out old isometric Pygame code? Figure out 
how to make OpenGL practical?) with attack animations

-Sound/music (I've got the code, just haven't implemented it here)
-Story-based sequence of battles (not the silly "story" here at all; I 
have something in mind)

-Cleaned-up code (look at NPCCommandState for a mess)
-Implementation of character facing
-Area-of-effect attacks
-Bigger, scrolling battlefield

It looks like the "GalaxyMage" tactical RPG project is being revived at 
.


[pygame] Tactics Game Demo

2007-12-15 Thread Kris Schnee
At  is a playable 
demo of a quick-and-dirty tactical combat game in the style of "Final 
Fantasy Tactics" and "Disgaea: Hour of Darkness." I did this for 
practice; check out the included source (mainly acorn.py) for the game 
framework I ended up using. The framework code is also available at 
.


Gameplay:
Hit a key to start. Move your characters (the raccoon team) to valid 
spaces, shown in blue, then either attack a target (in red) or click on 
the character themselves to defend for the next round. Your team has a 
fast (overpowered, really) scout, a "heavy," and a healer who does 
negative damage. Defeat both enemies to win.


Known problems:
-Escape quits, but only during the brief pauses between characters' 
actions. I should probably have all unhandled events passed back to the 
main event-handler so that Esc keypresses are always handled.
-NPCs just stand there and attack if you're in range. This is a result 
of the NPC AI not having been fully built.


Screenshot:



"You've gotta be kidding! Level 4000?!" -Laharl, "Disgaea"


  1   2   3   >