I am trying to write a game that does stuff in the background until you hit a key, so it's waiting for input while doing other stuff at the same time. I have never done something like this before but I hear the solution has to do with event handling. I am trying to use either 开发者_运维问答the "asyncore" library or the "signal" library (Python), but I don't understand the documentation and I think I'm missing basic concepts. Can you explain to me how I might go about using signal handling? (Or maybe there's something else I can do?)
Thanks!
Python's asyncore library is for network communication, and the signal library is used for timers and operating system signals (not related to keyboard input).
To get started, you should find a Python game programming library that suits your purposes.
If you want to do something as seemingly simple as keyboard input without help from a game programming library, you'll quickly be forced to use native APIs like Win32 and X11. By using a game programming library, you'll have get a chance to learn about events and background tasks first.
If you want to write a game in python with an SDL support, you should consider using pygame.
SDL: Simple DirectMedia Layer is a cross-platform multimedia library designed to provide low level access to audio, keyboard, mouse, joystick, 3D hardware via OpenGL, and 2D video framebuffer. [ http://www.libsdl.org/ ]
Pygame is python bindings with SDL: http://www.pygame.org
But if you really want to do it the hard way, I think that you should consider using the multiprocessing package.
The reason is that your game should have a main loop which is used for analysing the inputs (mouse, keyboard) and update the screen of your game. This process should not have too much overhead or the game will show signs of poor performance...
The second process should be the worker process that you want to use to code your other stuff in the background...
the multiprocessing package gives you plenty of choices for the interprocess communications (Pipe, Queue, Event)... http://docs.python.org/library/multiprocessing.html
To conclude, even if you use a framework or not for your game, your background stuff should be on a different process that your game's main loop. (Threading in python is good only for high use of I/O, so it's not the package you want right now).
精彩评论