snake-challenge / examples / makestory / kojiro.py

#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
module: random snake
用来作为示例代码
"""
import json, time, random, sys
import urllib, httplib 
"""
import logging
logging.basicConfig(level=logging.DEBUG,
                    format="%(asctime)s - %(levelname)s - %(message)s")
"""
SERVER = 'pythonvsruby.org'
ROOM_ID =  sys.argv[1] if len(sys.argv) > 1 else 0 
USER_NAME = sys.argv[2] if len(sys.argv) > 2 else 'Kojiro' 
DIRECTION_HASH = {0 : 'Straight',1 : 'Turn right',2 : 'Error',3 : 'Turn left'}

class Snake():
    def __init__(self):
        # 建立web连接
        self.conn = httplib.HTTPConnection(SERVER)
        self.path = '/room/%s/' % ROOM_ID

    def post(self, cmd, data):
        self.conn.request("POST", self.path + cmd,
                          urllib.urlencode(data))
        result = self.conn.getresponse().read()
        return json.loads(result)

    def get(self, cmd):
        self.conn.request("GET", self.path + cmd)
        result = self.conn.getresponse().read()
        return json.loads(result)
    
    def move(self,direction,position=None):
        position = self.head if position == None else position
        result = {0 : ((position[0] - 1)%self.map['size'][0],position[1]),
                  1 : (position[0],(position[1] - 1)%self.map['size'][1]),
                  2 : ((position[0] + 1)%self.map['size'][0],position[1]),
                  3 : (position[0],(position[1] + 1)%self.map['size'][1])}[direction]
        return result

    def distance(self,start,end):
        sub_x = abs(start[0] - end[0])
        sub_y = abs(start[1] - end[1])
        return (sub_x if sub_x < self.map['size'][0]/2 else self.map['size'][0] - sub_x) + (sub_y if sub_y < self.map['size'][1]/2 else self.map['size'][1] - sub_y ) 

    def cmd_add(self):
        result = self.post("add",
                           dict(name = USER_NAME,
                                type = "python"))
        self.me, self.info = result[0], result[1]
        return self.me, self.info
    
    def around(self,position):
      return [self.move(0,position),self.move(1,position),self.move(2,position),self.move(3,position)]

    def cmd_turn(self):
        result = self.post("turn",
                           dict(id = self.me["id"],
                                round = self.info["round"],
                                direction = self.next))
        self.turn, self.info = result[0], result[1]

    def cmd_map(self):
        self.map = self.get("map")

    def cmd_info(self):
        self.info = self.get("info")

    def cmd_think(self):
        self.prev = self.info["snakes"][self.me["seq"]]["direction"]
        self.head = self.info["snakes"][self.me["seq"]]['body'][0]
        self.straight = self.prev
        self.turn_left = (self.prev - 1)%4
        self.turn_right = (self.prev + 1)%4
        self.choices = {self.straight : 0,self.turn_left : 0,self.turn_right : 0}  
        obstacles = self.map['walls'] +  sum([s['body'] for s in self.info['snakes']],[]) 
        goal = sorted(self.info['eggs'],key=lambda egg : self.distance(self.head,egg))[0]
        for direction,rank in self.choices.items():
            wanna = self.move(direction)
            rank = rank + 40 if wanna in self.info['gems'] else rank
            rank = rank - 20 if wanna in self.info['eggs'] else rank
            rank = rank - 10 if self.distance(wanna,goal) < self.distance(self.head,goal) else rank
            rank = rank + 3**len(set(self.around(wanna)) & set([tuple(o) for o in obstacles]))
            rank = rank + 500 if list(wanna) in obstacles else rank
            self.choices[direction] = rank
            print "%s=%s" % (DIRECTION_HASH[(direction - self.prev)%4],self.choices[direction])

        choices = sorted(self.choices.items(),key=lambda item : item[1])
        print choices
        self.next = choices[0][0]

def main():
    snake = Snake()
    snake.cmd_map()
    snake.cmd_add()
    print 'Game Started' 
    while snake.info['status'] == 'waitplayer':
        print 'Waiting Player...' 
        snake.cmd_info()
        time.sleep(1)

    print  "Join room %s as %s" % (ROOM_ID,USER_NAME)
    while snake.info['status'] == 'running':
        snake.cmd_think()
        snake.cmd_turn()
        print DIRECTION_HASH[(snake.next - snake.prev)%4]
    
if __name__=="__main__":
    main()


    while snake.info['status'] == 'running':
        snake.think()
        snake.turn()
    
if __name__=="__main__":
    main()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.