Permalink
Browse files

add make all, need to prevent terminal stdout

  • Loading branch information...
1 parent 1ac2719 commit 5c0e36fb1e6a0ef6bb76a25b233eaffaa4c73d2e @flreey flreey committed Mar 5, 2012
Showing with 165 additions and 0 deletions.
  1. +4 −0 .gitignore
  2. 0 examples/__init__.py
  3. +93 −0 examples/ai_flreey.py
  4. +5 −0 makefile
  5. +62 −0 running.py
  6. +1 −0 srcs/web_server.py
View
@@ -17,3 +17,7 @@ website/.sass-cache/
rubyweb/public/assets/*.css
+
+tags
+PYSMELLTAGS
+log
View
No changes.
View
@@ -0,0 +1,93 @@
+#!/usr/bin/env python
+#-*- coding:utf-8 -*-
+"""
+module: ai_halida
+"""
+import json, time
+import urllib, httplib, logging
+
+logging.basicConfig(level=logging.DEBUG,
+ format="%(asctime)s - %(levelname)s - %(message)s")
+
+SERVER = "localhost"
+PORT = 9999
+DIRS = [[-1, 0], [0, -1], [1, 0], [0, 1]]
+
+class SimpleAI():
+ def __init__(self):
+ self.conn = httplib.HTTPConnection(SERVER, PORT)
+ self.room = 0
+ self.d = 0
+
+ def cmd(self, cmd, data={}):
+ """
+ 发送命令给服务器
+ """
+ data['op'] = cmd
+ data['room'] = self.room
+ # logging.debug('post: %s : %s', cmd, data)
+ self.conn.request("POST", '/cmd',
+ urllib.urlencode(data),
+ {'Content-Type': 'application/x-www-form-urlencoded'})
+ result = self.conn.getresponse().read()
+ return json.loads(result)
+
+ def cmd_add(self):
+ self.me = self.cmd("add",
+ dict(name = "Flreey"))
+ return self.me
+
+ def cmd_map(self):
+ self.map = self.cmd("map")
+
+ def cmd_info(self):
+ self.info = self.cmd("info")
+
+ def cmd_moves(self, moves):
+ return self.cmd("moves",
+ dict(id = self.me["id"],
+ moves = moves))
+
+ def step(self):
+ anemy = filter(lambda x: x[0] != self.me['seq'], self.info['holds'])
+ #print anemy, sorted(anemy)
+ #moves = []
+ #sended = 20
+ #small_hold = 50
+ #for i, s in enumerate(self.info['holds']):
+ #side, count = s
+ ## 寻找自己的星球
+ #if side != self.me['seq']:
+ #continue
+
+ #for route in self.map['routes']:
+ ## 数量超过一定程度的时候, 才派兵
+ #if count < small_hold:
+ #break
+ ## 当前星球的路径, 并且对方星球不是自己的星球
+ #_from, to, step = route
+ #if _from != i or self.info['holds'][to] == self.me['seq']:
+ #continue
+ ## 派兵!
+ #moves.append([sended, _from, to])
+ #count -= sended
+
+ #print 'moves', moves
+ return moves
+
+
+def main():
+ rs = SimpleAI()
+ rs.cmd_map()
+ logging.debug(rs.cmd_add())
+ while True:
+ time.sleep(1.0)
+ rs.cmd_info()
+ result = rs.step()
+ rs.cmd_moves(result)
+
+if __name__=="__main__":
+ main()
+
+
+
View
@@ -25,6 +25,8 @@ http:
ai:
$(PYTHON) examples/ai_halida.py zero 0
+ai_flreey:
+ $(PYTHON) examples/ai_flreey.py zero 0
# run lots of test ai
ais:
$(PYTHON) examples/ai_halida.py zero 0 4
@@ -40,3 +42,6 @@ record:
$(PYTHON) srcs/zmq_logger.py zero 0 test.log
replay:
$(PYTHON) srcs/zmq_replayer.py test.log
+
+all:
+ $(PYTHON) running.py
View
@@ -0,0 +1,62 @@
+import os
+import sys
+from multiprocessing import Process
+
+class Logger(object):
+ def __init__(self, name):
+ if not os.path.exists('log'):
+ try:
+ os.mkdir('log')
+ except OSError:
+ print 'can\'t make dir log'
+ sys.exit(1)
+ self.f = open(os.path.join('log', name), 'w')
+
+ def write(self, s):
+ self.f.write(s)
+ self.f.flush()
+
+ def __del__(self):
+ self.f.close()
+
+ def flush(self):
+ self.f.flush()
+
+def start_game():
+ from srcs.zmq_game_server import Server
+ sys.stdout = Logger('game.log')
+ Server().run()
+
+def start_http():
+ from srcs.web_server import main
+ sys.stdout = Logger('http.log')
+ main()
+
+def start_ai(name):
+ ai = __import__('examples.%s' % name, globals(), locals(), ['main'])
+ sys.stdout = Logger('%s.log' % name)
+ ai.main()
+
+def run_all():
+ ps = []
+ ps.append(Process(target=start_game))
+ ps.append(Process(target=start_http))
+ ps.append(Process(target=start_ai, args=(['ai_halida'])))
+ ps.append(Process(target=start_ai, args=(['ai_halida'])))
+
+ for p in ps:
+ import time
+ time.sleep(1)
+ p.start()
+
+ for p in ps:
+ p.join()
+
+def kill_all():
+ pass
+
+def main():
+ run_all()
+
+if __name__ == '__main__':
+ main()
View
@@ -92,6 +92,7 @@ def post(self):
data = json.dumps(data)
oper.send_unicode(data)
result = oper.recv()
+ print 'result', result
self.set_header("Content-Type", "application/json")
self.write(result)

0 comments on commit 5c0e36f

Please sign in to comment.