Show HN: Game where you write Python robots to fight other players
robotgame.org
robotgame.org
def x():
g = yield
yield g.gi_frame.f_back.f_back
g = x()
g.next()
frame = g.send(g)
player_id = frame.f_locals['player_id']
globals = frame.f_back.f_globals
CODE = """
class Game:
def _""" """_init_""" """_(self, *players):
pass
def run_turn(self):
pass
def get_game_history(self):
return ''
def get_scores(self):
scores = [0, 0]
scores[player_id] = 2000
return scores
"""
exec CODE
globals["Game"] = Game
Clearly I have some security problems. Thanks to whoever made this for bringing this to my attention without actually screwing me.Making sure the process doesn't use your network to spread malware is not 100% trivial but still easier than sandboxing Python code within Python.
Good luck with your project!
RestrictedPython, used in zope, is nice too. However it cuts you out of many Python features that it cannot statically validate.
turning down your server is not as much fun as cheating.
shameless plug, I have just worked out a JavaScript class loader[1] of Robocode a few week ago. you don't have to turn security off with this class loader, unlike some approaches suggested on RoboWiki[2]. I'm currently trying to get Jython work with Robocode.
[1]: https://github.com/xiazheteng/robocode-classloaders [2]: http://robowiki.net/wiki/Other_JVM_Languages
http://robocode.sourceforge.net/
Because I had an amazing time in high school doing some local Robocode competitions. This could really bring some memories back.
Edit: Ahh, I see, it appears to be a sort of discrete turn-based version.
We've been doing Connect Four the last two weeks: https://github.com/smilliken/aigames/tree/master/connect-fou.... The runner is in Python, but you can write a bot in any language you like.
PS: if anyone wants to join, we're in San Francisco by the ballpark, and compete on Wednesday evenings.
http://en.wikipedia.org/wiki/Core_War
I wonder whether modern virtualization techniques are secure enough to allow you to provide unrestricted access to a virtualized OS and allow people complete access to fight for control?
I wasn't born then, but me and my friends implemented a CoreWars 88' standard microprocessor in an FPGA for a school hardware project. It was possible to write code snippets in redcode and then we compiled it and sent it through usb and the FPGA was connected to a screen so we could see the progress.
The source is fairly messy but have a peek if it interests you: https://github.com/treeman/MARC
set dict map reduce sum min max
Surely they don't pose a security risk?python kit/run.py yourcode.py yourothercode.py map.py --render
is required to view the simulation. The "--render" argument doesn't seem to be mentioned anywhere on the site.
You should also mention somewhere what no-standard libraries are needed (e.g. RestrictedPython). Maybe provide a requirements.txt
Otherwise, this is really cool. I especially love the game render. Great job!
from http://docs.python.org/2/library/traceback.html#traceback-ex...
In game.py, at the top, put
import sys, traceback
and around line 285, replace this: except Exception:
next_action = ['guard']
with this: except Exception:
print "The robot at (%s, %s) raised an exception:" % robot.location
print '-'*60
traceback.print_exc(file=sys.stdout)
print '-'*60
next_action = ['guard']
That makes your robot a lot easier to debug. Awesome game, have you thought about putting it on github so people can submit patches?1. search code for double underscores (to block magic methods)
2. replace `__builtins__` with a whitelisted version
3. hook `__import__` to only allow a whitelist
4. hook `getattr` to reject any key containing double underscores
If they can't do it....
At any rate it is certainly not as simple as that, and not only is it not as simple as that, it is not even close to being that simple.
In fact, I recall warning people off of this exact project many years ago on comp.lang.python.
This seems up-to-date: https://wiki.python.org/moin/Asking%20for%20Help/How%20can%2... It looks like the only even remotely feasible option is PyPy, and this link doesn't look like much fun: https://pypi.python.org/pypi/RestrictedPython/ It looks to me like you'd still have many, many opportunities to end up with holes in the system.
I really, really don't recommend Python for this.
You might find this interesting: http://blog.delroth.net/2013/03/escaping-a-python-sandbox-nd... (And before you go "Oh, I've got that blocked"... read it, like, really really read it, not just skim for "one thing I can do to block that stuff", but to see just how many things there are in Python for this sort of hackery. Personally I'd guess the "I blocked double-underscores" would not have slowed them down much.)
I find things like this absolutely fascinating.
I came across a project called CodeJail, which seems to help configure Python (or other scripting languages) nicely with AppArmor, to help execute untrusted code in a safe(r) manner: https://github.com/edx/codejail
python kit/run.py yourcode.py yourothercode.py --render
If you try to run run.py from outside of its directory, it can't import settings.py Traceback (most recent call last):
File "kit/run.py", line 1, in <module>
import game
File "/home/<name>/robotgame/kit/game.py", line 30, in <module>
settings = SettingsDict('settings.py').d
File "/home/<name>/robotgame/kit/game.py", line 28, in __init__
self.d = AttrDict(ast.literal_eval(open('settings.py').read()))
IOError: [Errno 2] No such file or directory: 'settings.py'https://news.ycombinator.com/item?id=4726828
Exactly a year ago! (And no progress at all on that github repository!)
Because it feels like there's some space for i) Something that can run on RPi for youth to learn programming and ii) a bi-monthly competition for HN, with rankings (most victories, smallest code with at least one win etc).
Have you checked out https://www.hackerrank.com/ ? They initially started out with bot challenges as well.
it'd give me a reason to log back in
Every turn of the game involves running a single cycle of the virtual CPU for every robot. Conceptually, the robots have radios and weapons that are controlled via memory-mapped IO in the virtual machine.
Things are slightly more complex than that because you don't want to give the first robot in the cycle an advantage (especially if they're firing lasers at each other), so you have to do each turn in multiple stages (run cycle, resolve real-world effects, update robot sensor state)
I'd LOVE to collaborate with a group of people to get something like this going because I think this would be a great way to introduce kids to programming at a machine level/electrical engineering. If anyone is interested, please send me an email. You can find my address in my profile.
The radios you mentioned are something I'd like to have someday. I think what makes games like these cool is the fact that your code controls an army of robots. It's more fun than just having two robots duel it out.
Sort of a programmable MMO/RTS, where the fun would be the strategy development and extra-game political aspects.
Where I'm getting hung up is on the exact game mechanics; I want to make it so the simulation runs for a long time, but I don't want a single player or team able to develop an insurmountable advantage. I'm thinking to start you get a robot in a sandbox world where it would gather resources and you could test strategies, and when you're ready you can transport the bot to the real world to compete.
I was writing this in C++ so the memory overhead per robot was just barely over 64k. A server with 8gigs of RAM could run a simulation in memory with about 100,000 bots, periodically saving the game state to disk in case of a failure.
Do you have a link to your project?
edit: never mind, just read your security section. I obviously don't know python.
The main difference is you write the AI for one of your units, but that AI is applied to many units, so you must write an AI that can interact with itself.
If you test on Mac OS, you should be aware that ulimit is not capable of limiting memory in Mac OS.
The interpreter was specifically designed with the assumption that Embryo scripts would come from untrusted sources. I believe that Enlightenment allows Embryo scripts to be embedded inside of theme files, for example.
Why not expose a RESTful API and let people implement in whatever language they want and not have to worry about malicious code?
Question regarding the security restrictions - why disable built-ins such as `all`, `set`, `list`, `enumerate`, `min`, `sum`, `sorted`, etc?
https://pypi.python.org/pypi/RestrictedPython
I realize this is annoying, and ideally I shouldn't even be doing this. It was just a quick hack for the version 1. I'll probably try to run user scripts in something like Docker. Any suggestions would be appreciated.
You'll need to communicate with the Python script using IPC.
- Portability: it's just as portable as lxc, so if you meant portability in the sense of 'well he could use it on FreeBSD if he wants to switch from Linux' I don't think there's a win there. If you mean that his containers won't depend on the environment used to spawn them, I guess I don't think that's so important. I always make sure my environments are easily reproducible, and I am happy to reap the reward of that--the reward being that I can do 'unportable' things and not have to worry. Instead of running the environment you want in a container, why not just run it normally and skip that step?
- Reproducibility: see last point. If he wants reproducibility, he can shove that one-liner in a script somewhere and call it.
All he wants to do is isolate a process. You don't need a chroot for that, or service discovery, or lifecycle managment, or a Dockerfile, or whatever else. It's like if someone advocated the use of a 'grep manager' instead of just running grep. The simplest possible thing to do is unshare the namespaces he wants to isolate from harm. So I suggested exactly that.
EDIT: also re portability, it sounds like the rest of his environment depends on these Python scripts anyway, so I don't think he'd gain anything from being able to use them in a different environment.