Пример #1
0
def pickup_from_ladder(s,l):
    page1 = s.get('http://zooescape.com/ladder.pl?l=%d' % (l.l)).text

    prev_page_link = find_all_between(page1,
        '<table class="page_menu"><tr><td><a href="',
        '" title="previous page">')

    games = ladder(page1).above(args.only_above)

    if len(prev_page_link)!=0:
        page2 = s.get('http://zooescape.com' + prev_page_link[0]).text
        games = ladder(page2).challenges + games

    for g in games:
        form = find_all_between(
            s.get('http://zooescape.com/game-start-special'+g[1]).text,
            '<FORM', '</FORM>' )

        if len(form)>0:
            action = 'http://zooescape.com' + find_all_between(
                form[0][:form[0].find('>')],'action=\"','\"' )[0]

            values = dict( val for sublist in \
                [ re.findall(r'name=\"([^\"]+)\" +(?:value=\"?([^\"]+)\"?)',x) \
                  for x in find_all_between(form[0],'<INPUT','>') ] \
                  for val in sublist )

            msg = 'challenged %s in %s ladder' % (values['opp'],l.s)
            print msg
            if log_file is not None: log_file.write(msg)
            s.post(action, values)

        else: break
Пример #2
0
def play_all(s):
    while True:
        try:
            room = s.get('http://zooescape.com/backgammon-room.pl').text
        except requests.exceptions.ConnectionError as e:
            print e
            time.sleep(10) # wait before reconnecting
            continue
        else: break

    table = find_all_between(
        find_all_between(room,'RoomObjInit','RoomSetup')[0], '[',']' )
    if len(table)==0: return 2 # got kicked out
    head = find_all_between( table[0], 'title:StringDecodeJS(\'', '\')' )

    si = head.index('Game%3cBR%3eStatus') # status index
    ti = head.index('Game%3cBR%3eType')   # type index

    games = [ find_all_between(x,'{','}') for x in table[2:] ]

    global max_n_games
    if len(games)>max_n_games:
        max_n_games = len(games)
        print 'Playing %d games' % (max_n_games)
    elif args.ladder is not None:
        # pick up games from the ladder if has room
        if len(games)<max_n_games:
            for l in args.ladder:
                pickup_from_ladder(s,l)

    played = False

    for row in games:
        if row[si].find('My Turn')!=-1:
            i = row[si].find('gid=')+4
            if not play(s,row[si][i:i+7]): return 2 # got kicked out
            played = True
        elif args.accept and row[si].find('New Challenge')!=-1:
            href = find_all_between(row[si],'href=\"','\"')[0]
            game_type = int(re.findall(r'v=20(\d)',href)[0])
            accepted = False
            for t in args.type:
                if game_type==t.g:
                    s.post('http://zooescape.com'+href,
                        {'bg_challenge_radio':'1', 'bg_challenge_message':''} )
                    accepted = True
                    continue
            if not accepted:
                s.post('http://zooescape.com'+href,
                    {'bg_challenge_radio':'0', 'bg_challenge_message':''} )

    return 1 if played else 0
Пример #3
0
 def __init__(self,html):
     lines = find_all_between(html,
             '<TH>Finished</TH><TH>&nbsp;</TH></TR>\n',
             '</TABLE>')[0].rstrip('\n').split('\n')
     self.challenges = []
     self.own_rank = 0
     for l in lines:
         if l[-23:][:-14]=='Challenge':
             self.challenges.append( (
                 int( find_all_between(l,'>','<')[1] ),
                 find_all_between(l,'game-start-special','\">')[0] ) )
         elif l[-23:][:-14]=='lected_li': # own line
             self.own_rank = int( find_all_between(l,'>','<')[1] )
Пример #4
0
def check_msgs(filename,page,gid,opp):
    msglist = find_all_between(page,'MessageList([{','}])')
    if len(msglist)!=1: return

    db = sqlite3.connect(filename)
    cur = db.cursor()

    new_msgs = False
    for msg in [ zemsg(x) for x in msglist[0].split('},{') ]:
        cur.execute('SELECT mid FROM zemsgs WHERE mid = ?', (msg.mid,))
        if cur.fetchone() is None: # Message is new
            cur.execute('INSERT INTO zemsgs VALUES (?,?,?,?,?)',
                (msg.mid,gid,opp,msg.time,msg.msg,) )
            new_msgs = True
            print msg

    if new_msgs: db.commit()
Пример #5
0
def read_board(game_page):
    # Get game state variables ######################################
    GameSetupMP = find_all_between(game_page,'Backgammon.GameSetupMP(',');')[0]
    SetStateMP  = find_all_between(game_page,'Backgammon.SetStateMP(', ');')[0]

    players = [ [ y.strip('\'') for y in x.strip(' ').split(', ') ]
                for x in find_all_between(GameSetupMP,'new PlayerBG(',')') ]

    setup_tail = GameSetupMP[GameSetupMP.rfind(']')+3:].split(', ')

    state = [ x.strip(' "') for x in SetStateMP.split(', ') ]

    moving = (0 if players[0][0] == state[2] else 1)

    logcube = int(state[6])
    if logcube>0: logcube -= 1

    # Flip board if necessary #######################################
    if players[moving][5] == 'A':
        # Moving player is black => switch white and black
        num = len(state[0])/2
        for i in reversed(range(num)):
            state[0] += (
                alphabet[ len(alphabet) - alphabet.find( state[0][i*2] ) - 1 ]
            )
            state[0] += state[0][i*2+1]
        state[0] = state[0][num*2:]

    # Encode GNU Backgammon board ID ################################
    bit_array = bitarray()
    for a in 'BCDEFGHIJKLMNOPQRSTUVWXYZyxwvutsrqponmlkjihgfedcba':
        i = state[0].find(a)
        if i!=-1:
            while i%2==1:
                i = state[0].find(a,i+1)
                if i==-1: break
            if i!=-1:
                for j in range(int(state[0][i+1],16)):
                    bit_array.append(True)
        bit_array.append(False)
    while len(bit_array)<80: bit_array.append(False)

    board = encode_idbits(bit_array)

    # Encode GNU Backgammon match ID ################################
    cube_owner = str(players[moving][11] + players[1 if moving==0 else 0][11])
    if cube_owner[0]!='1':
        cube_owner = '00' if cube_owner[1]!='1' else '11'

    bit_array = bitarray(72)
    bit_array.setall(False)
    bit_array[0:4] = bitarray(
        bin(logcube)[:1:-1].ljust(4,'0') ) # cube value
    bit_array[4:6] = bitarray(cube_owner) # cube owner
    bit_array[6:7] = bitarray('1') # dice owner
    bit_array[7:8] = bitarray('0') # Crawford
    bit_array[8:11] = bitarray('100') # game sate
    bit_array[11:12] = bitarray([players[1][0]==state[2]]) # turn owner
    bit_array[12:13] = bitarray('0') # double
    bit_array[13:15] = bitarray('00') # resignation
    bit_array[15:18] = bitarray(
        bin(int(state[3][0]))[:1:-1].ljust(3,'0') ) # die 1
    bit_array[18:21] = bitarray(
        bin(int(state[3][1]))[:1:-1].ljust(3,'0') ) # die 2
    bit_array[21:36] = bitarray('000000000000000') # match length
    #bit_array[36:51] = bitarray('010000000000000') # score 1
    #bit_array[51:66] = bitarray('001000000000000') # score 2

    match = encode_idbits(bit_array)

    return game(board,match,state,players,moving)
Пример #6
0
with requests.Session() as s:
    cred = { 'userName': raw_input('Username: '******'password': None }
    login(s, cred, 3)

    url = 'http://zooescape.com/game-list.pl?usr=%s&type=p' % (
        args.player if args.player is not None else cred['userName'])

    all_rows = ''

    while True:
        print url
        page = s.get(url).text

        all_rows += find_all_between(page,'\n],[\n','\n\n],')[0]
        all_rows += '\n,\n'

        b = page.rfind('title=\"next page\"')
        if b==-1: break
        else:
            url = 'http://zooescape.com'+page[page[0:b].rfind('href=\"')+6:b-2]

    file1 = open("gameslist.txt", 'w')
    file1.write(all_rows)
    file1.close()

    for url in [ find_all_between(x,'href=\"','\">')[0] for x in all_rows.split('\n,\n') if len(x)>0 ]:
        print url
        file2 = open(find_all_between(url,'gid=','&')[0]+'.html', 'w')
        file2.write( s.get('http://zooescape.com'+url).text )