473,657 Members | 2,546 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Python share CPU time?

Hi,

I would like to program a small game in Python, kind of like robocode
(http://robocode.sourceforge.net/).
Problem is that I would have to share the CPU between all the robots,
and thus allocate a time period to each robot. However I couldn't find
any way to start a thread (robot), and interrupt it after a given time
period.
Any suggestions on how to proceed?
Is Python just not adapted to this kind of things?

Thanks,
Yannick

Aug 9 '06 #1
13 1661
On 2006-08-09, Yannick <ya************ ***@gmail.comwr ote:
Hi,

I would like to program a small game in Python, kind of like robocode
(http://robocode.sourceforge.net/).
Problem is that I would have to share the CPU between all the robots,
and thus allocate a time period to each robot. However I couldn't find
any way to start a thread (robot), and interrupt it after a given time
period.
The robot code thread needs to block when it runs out of things
to do.
Any suggestions on how to proceed?
Just start a thread for each robot, and put a call to
time.sleep(0.01 0) in the main loop for the robot code. Adjust
the 0.010 value to taste.

As an alternative to sleeping, you could wait for some sort of
event each time through the loop.
Is Python just not adapted to this kind of things?
It's quite well adapted to this sort of thing.

--
Grant Edwards grante Yow! Why don't you
at ever enter and CONTESTS,
visi.com Marvin?? Don't you know
your own ZIPCODE?
Aug 9 '06 #2
There's several ways of doing concurrency in Python. Other than the
threading module, have you tried FibraNet? It's designed with simple
games in mind.
You can download it at http://cheeseshop.python.org/pypi/FibraNet.
Specifically the nanothreads module from FibraNet uses generators to
simulate light-weight cooperative threads.

Generator-based approaches are fast and *deterministic* , unlike true
threads where you have to account for race conditions, etc. You can
pause, resume, kill, or end a "thread". In Python 2.5 (soon to be
released), generators will be consumers rather than just producers, so
you can pass things into generators (without needing global variables
as a workaround) rather than only being able to spit out data
on-the-fly. They'll also have a more graceful way to handle exceptions.

For a good overview of the concept, especially if you want to implement
this yourself instead of using Fibranet (although re-use is often the
better choice), take a look at this link from the Charming Python
column:
http://gnosis.cx/publish/programming...python_b7.html.

If this all seems too exotic, then you can also just go with the
traditional threading approach with the threading module. Normally
you'll want to use the "threading" module rather than the lower-level
"thread" module. But be warned, threads are a big can of worms.

I hope you find this useful.

Yannick wrote:
Hi,

I would like to program a small game in Python, kind of like robocode
(http://robocode.sourceforge.net/).
Problem is that I would have to share the CPU between all the robots,
and thus allocate a time period to each robot. However I couldn't find
any way to start a thread (robot), and interrupt it after a given time
period.
Any suggestions on how to proceed?
Is Python just not adapted to this kind of things?

Thanks,
Yannick
Aug 9 '06 #3
Problem is that I would have to share the CPU between all the robots,
and thus allocate a time period to each robot. However I couldn't find
any way to start a thread (robot), and interrupt it after a given time
period.
Any suggestions on how to proceed?
>>import thread, time
def robot(name):
.... for i in xrange(5):
.... print "%s on pass %i" % (name, i)
.... time.sleep(0.01 )
....
>>ids = [thread.start_ne w(robot, ("Robot%i" % i,)) for i in
xrange(4)]
Robot1 on pass 0
Robot2 on pass 0
Robot0 on pass 0
Robot3 on pass 0
Robot1 on pass 1
Robot0 on pass 1
Robot2 on pass 1
Robot3 on pass 1
Robot1 on pass 2
Robot0 on pass 2
Robot2 on pass 2
Robot3 on pass 2
Robot1 on pass 3
Robot0 on pass 3
Robot2 on pass 3
Robot3 on pass 3
Robot1 on pass 4
Robot0 on pass 4
Robot2 on pass 4
Robot3 on pass 4

Maintaining a Queue of things to do for each robot allows the
robot to process a single thing before sleeping a bit.

The thread scheduler does seem to provide interruptions, as I've
run the above code with no sleep() call and larger iterations,
and you'll find it bouncing from robot to robot.

Or, you can take advantage of python's yield statement:
>>class Robot(object):
.... def __init__(self, name):
.... self.name = name
.... self.thought = 0
.... self.done = False
.... def think(self):
.... while not self.done:
.... yield self.thought
.... self.thought += 1
.... def finish(self):
.... self.done = True
....
>>robots = [Robot(str(i)) for i in xrange(5)]
generators = [robot.think() for robot in robots]
[g.next() for g in generators]
[0, 0, 0, 0, 0]
>>[g.next() for g in generators]
[1, 1, 1, 1, 1]
>>[g.next() for g in generators]
[2, 2, 2, 2, 2]
>>[g.next() for g in generators]
[3, 3, 3, 3, 3]
>>[g.next() for g in generators]
[4, 4, 4, 4, 4]
>>generators[2].next()
5
>>[g.next() for g in generators]
[5, 5, 6, 5, 5]
>>robots[2].thought
6
>>robots[3].thought
5

Just do more complex stuff in the think() method (to most folks,
counting isn't very exciting thinking) and yield your current state.
Is Python just not adapted to this kind of things?
Python is quite adaptable to these sorts of things...it requires
an adaptable programmer to make the best use of it though... ;)

-tkc


Aug 9 '06 #4
On 2006-08-09, Tim Chase <py*********@ti m.thechases.com wrote:
>Problem is that I would have to share the CPU between all the robots,
and thus allocate a time period to each robot. However I couldn't find
any way to start a thread (robot), and interrupt it after a given time
period.
Any suggestions on how to proceed?
>import thread, time
def robot(name):
... for i in xrange(5):
... print "%s on pass %i" % (name, i)
... time.sleep(0.01 )
>[...]
I originally suggested the thread/sleep() scheme, but after
thinking about it more, I really like the generator approach in
the case where you want to explicity end each robot's "turn"
using the CPU (which is what the sleep() call does).

OTOH, if you want the robots to wait for events of some sort
(e.g. from a queue) or data from an I/O device, then threading
is probably the way to go.

I guess it all depends on whether the robots' behavior is to be
time-driven or event-driven.

--
Grant Edwards grante Yow! Used staples are good
at with SOY SAUCE!
visi.com
Aug 9 '06 #5
Yannick wrote:
Hi,

I would like to program a small game in Python, kind of like robocode
(http://robocode.sourceforge.net/).
Problem is that I would have to share the CPU between all the robots,
and thus allocate a time period to each robot. However I couldn't find
any way to start a thread (robot), and interrupt it after a given time
period.
Any suggestions on how to proceed?
Is Python just not adapted to this kind of things?

Thanks,
Yannick
You should take a look at stackless Python. It should do very nicely
for what you want. There is a good tutorial on it here:
http://members.verizon.net/olsongt/s...stackless.html

Aug 9 '06 #6
Yannick wrote:
Hi,

I would like to program a small game in Python, kind of like robocode
(http://robocode.sourceforge.net/).
Problem is that I would have to share the CPU between all the robots,
and thus allocate a time period to each robot. However I couldn't find
any way to start a thread (robot), and interrupt it after a given time
period.
Any suggestions on how to proceed?
Is Python just not adapted to this kind of things?
If your intent is to allow the user to program a robot using python
then no it's NOT suitable. There's no builtin way to restrict what
code can do (but Zope might have a way), nor can you force it to pause
after a predetermined amount of time, nevermind making that amount of
time deterministic enough to be fair in a game.

However, if your intent was to have only trusted code then Python would
work fine. My preference would be for generators (especially once
Python 2.5 is released), but YMMV.

Aug 10 '06 #7
Thank you all for the detailled answers.

What I would like to achieve is something like:

# main loop
while True:
for robot in robots:
robot.start()
robot.join(0.2) # wait 200ms
if robot.is_active ():
robot.stop()
# run all the game physics, pause, frame/rate, etc...

Unfortunately the stop() call doesn't exist in Python.

By using a generator I would make the assumption that every robot is
playing fair, and would yield often. But I cannot control this as
eventually robots would be coded by third parties.

Using Python scheduler would allow me to share time equally between
each robot, but then I would loose the ability to have a main thread
organizing everything.

Aug 10 '06 #8
Yannick wrote:
Thank you all for the detailled answers.

What I would like to achieve is something like:

# main loop
while True:
for robot in robots:
robot.start()
robot.join(0.2) # wait 200ms
if robot.is_active ():
robot.stop()
# run all the game physics, pause, frame/rate, etc...

Unfortunately the stop() call doesn't exist in Python.

By using a generator I would make the assumption that every robot is
playing fair, and would yield often. But I cannot control this as
eventually robots would be coded by third parties.

Using Python scheduler would allow me to share time equally between
each robot, but then I would loose the ability to have a main thread
organizing everything.
This is just a dim memory, but something called lambdaMOO was (is?) a
Multi-User Dungeon that had (has?) a model of processing that allowed
you to create programmed objects that received a "budget" of processor
time. The objects would not work if they "ran out" of processor
time...

Perhaps something like this could help you? (Sorry to be so vague.)

HTH,
~Simon

Aug 11 '06 #9
Simon Forman wrote:
This is just a dim memory, but something called lambdaMOO was (is?) a
Multi-User Dungeon that had (has?) a model of processing that allowed
you to create programmed objects that received a "budget" of processor
time. The objects would not work if they "ran out" of processor
time...
It basically employs its own threading model to do just this.
SecondLife does much the same: any system that allows for the apparent
parallel running of code will.

LambdaMOO still exists, incidentally! You might also be interested in a
python-implemented version of the main MOO core, the unfortunately
named POO: http://www.strout.net/python/poo/

-alex23

Aug 11 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2426
by: Benjamin Sher | last post by:
Dear friends: I would appreciate your help in installing SIP with QT support so that I can then install PyQT. My reason is that I would like to install a number of KDE applications that require as a prerequisite SIP and PyQT. As an ordinary user, I recognize my limitations as far as programming. My dilemma is that this stuff is quite difficult and beyond my competence, but I
1
1721
by: Neil Zanella | last post by:
Hello, What is the best way to install a python application under Unix. Since python modules are platform independent I would guess these should be placed under an application specific directory under either /usr/share or /usr/local/share with a corresponding link to the main module(s) under /usr/bin or /usr/local/bin for user applications and /usr/sbin or /usr/local/sbin for system applications. Assuming this is done, should .pyc and...
114
9818
by: Maurice LING | last post by:
This may be a dumb thing to ask, but besides the penalty for dynamic typing, is there any other real reasons that Python is slower than Java? maurice
2
2257
by: BrianS | last post by:
Hi, I'm trying to learn Python and wanted to play with Tkinter. I couldn't get it to work so I figured it would help if I installed the newest verison of Python. I downloaded the source, compiled it and installed it. No problem. The next time I booted my machine I the following errors when it tried to start CUPS: Traceback (most recent call last): File "/usr/sbin/printconf-backend", line 6, in ?
3
2278
by: Michael Sparks | last post by:
Hi, I'm posting a link to this since I hope it's of interest to people here :) I've written up the talk I gave at ACCU Python UK on the Kamaelia Framework, and it's been published as a BBC R&D White Paper and is available here: * http://www.bbc.co.uk/rd/pubs/whp/whp113.shtml
8
3032
by: Paul Cochrane | last post by:
Hi all, I've got an application that I'm writing that autogenerates python code which I then execute with exec(). I know that this is not the best way to run things, and I'm not 100% sure as to what I really should do. I've had a look through Programming Python and the Python Cookbook, which have given me ideas, but nothing has gelled yet, so I thought I'd put the question to the community. But first, let me be a little more detailed...
112
13804
by: mystilleef | last post by:
Hello, What is the Pythonic way of implementing getters and setters. I've heard people say the use of accessors is not Pythonic. But why? And what is the alternative? I refrain from using them because they smell "Javaish." But now my code base is expanding and I'm beginning to appreciate the wisdom behind them. I welcome example code and illustrations.
2
2033
by: Jean-Paul Calderone | last post by:
On Mon, 16 Jun 2008 08:39:52 +1000, Ben Finney <bignose+hates-spam@benfinney.id.auwrote: Maybe. I'm no expert on Debian packaging. However, exarkun@boson:~$ ls -l /usr/lib/python2.{4,5}/site-packages/sqlite/main.py lrwxrwxrwx 1 root root 63 2007-12-27 15:29 /usr/lib/python2.4/site-packages/sqlite/main.py -/usr/share/pycentral/python-sqlite/site-packages/sqlite/main.py lrwxrwxrwx 1 root root 63 2007-12-27 15:29...
0
8326
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8845
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8743
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8522
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8622
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4333
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1973
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1736
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.