Advertisement
Guest User

Pastebin for Stack Overflow - "Why won't print work"

a guest
Dec 30th, 2014
315
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.02 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. print "test"
  4.  
  5. import websocket,urllib,urllib2,time,threading,json
  6. from movedictfile import movedict    #movedict takes a movename as key and return a list of data about the move (power,typing,etc)
  7. from DBinter import nametomon,eff    #DBinter (external file) includes mainly the entire pokemon stat database + type effectiveness table
  8. from random import randint
  9.  
  10. debug=True
  11.  
  12. name="basically wont give it"
  13. password="neither will i give this one"
  14.  
  15. ws=websocket.create_connection("ws://sim.smogon.com:8000/showdown/websocket")
  16. #ws=websocket.create_connection("ws://85.222.228.199:8000/showdown/websocket")
  17. #ws=websocket.create_connection("ws://pokestrat.com:8000/showdown/websocket")
  18.  
  19. ws.recv(),ws.recv()
  20. txt=ws.recv()
  21. Ptool=[i for i in range(len(txt)) if txt[i]=='|']
  22. data = urllib.urlencode({'act': 'login', 'name': name, 'pass' : password, 'challengekeyid': txt[Ptool[1]+1], 'challenge':txt[Ptool[2]+1:]})
  23. req = urllib2.Request("http://play.pokemonshowdown.com/action.php", data, { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36)' })
  24. response = urllib2.urlopen(req)
  25. result = response.read()
  26. Ptool2=[i for i in range(len(result)) if result[i]=='"']
  27. assertion=result[Ptool2[-2]+1:Ptool2[-1]]
  28. ws.send("|/trn %s,0,%s" % (name, assertion) )
  29. time.sleep(2)
  30. ws.send("|/join franais")
  31.  
  32. def parse(text,character):
  33.     p=[-1]+[i for i in range(len(text)) if text[i]==character]+[len(text)]
  34.     l=[]
  35.     for i in range(len(p)-1):
  36.         l+=[ text[ p[i]+1:p[i+1] ] ]
  37.     return l
  38.  
  39.  
  40. global stridtoid,threadstopcondition,chainladd
  41. threadstopcondition=False
  42. chainladd=False
  43. stridtoid={}
  44.  
  45. class Battle():
  46.     def __init__(self,strid):
  47.         self.strid=strid
  48.         stridtoid[self.strid]=self
  49.         self.idp='0'
  50.         self.allies=[]
  51.         self.ennemies=[]
  52.         self.activeopponent=""
  53.         self.currentreqdata=""
  54.     global chainladd
  55.     def reacttorequest(self,reqdata):
  56.         self.allies=reqdata['side']['pokemon']
  57.         if 'rqid' in reqdata.keys():
  58.             rqid=str(reqdata['rqid'])
  59.             if debug: print type(rqid)
  60.             if rqid=='1':                                                      #choix du lead, choisit actuellement le premier poké
  61.                 ###ALGO CHOIX DU LEAD
  62.                 currentmax,currentmonindex=0,0
  63.                 for i in range(6):
  64.                     studiedmon=reqdata['side']['pokemon'][i]
  65.                     k=0
  66.                     #somme des puissances des attaques
  67.                     for i3 in [i2 for i2 in studiedmon['moves'] if ( i2 in movedict and movedict[i2][6][0] in '0123456789' )]:
  68.                         k+=int(movedict[i3][6])
  69.                     #somme des stats
  70.                     k2=0
  71.                     for i2 in studiedmon['stats']:
  72.                         k2+=studiedmon['stats'][i2]
  73.                     if k*k2>currentmax:
  74.                         currentmax=k*k2
  75.                         currentmonindex=i
  76.                 teammessage=str(i)
  77.                 for i2 in ['1','2','3','4','5','6']:
  78.                     if not i2 in teammessage:
  79.                         teammessage+=i2
  80.                 ws.send(self.strid[1:]+"|/team "+teammessage+"|1")        
  81.                 #ws.send(self.strid[1:]+"|/team 123456|1")
  82.             else:                                                              #analyse du meilleur move
  83.                 activedic=reqdata['side']['pokemon'][0]
  84.                 print reqdata
  85.                 attackmoves=[i for i in activedic['moves'] if ( i in movedict and movedict[i][6][0] in '0123456789' )] # si on connait le move + qu'il a une puissance fixe et définie
  86.                 if debug:
  87.                     print attackmoves,activedic['moves']
  88.                 if len(attackmoves)==0:                                       # si on a pas un seul move offensif, lancer des trucs au hasard ...
  89.                     if debug: print self.strid[1:]+"|/choose move "+activedic['moves'][randint(0,3)]+"|"+rqid
  90.                     ws.send(self.strid[1:]+"|/choose move "+activedic['moves'][randint(0,3)]+"|"+rqid)
  91.                 else:
  92.                     if debug: print attackmoves
  93.                     highestvaluemove=attackmoves[0]
  94.                     highestvalue=0
  95.                     for movename in attackmoves:
  96.                         allymon=nametomon[activedic['ident'][4:]]
  97.                         ennemymon=nametomon[self.activeopponent]
  98.                         move=movedict[movename]                                #attaque / def * puissance * eff1 * eff2 * STAB
  99.                         value=float( {'Physical':activedic['stats']['atk'], 'Special':activedic['stats']['spa']}[move[3]] ) / {'Physical':activedic['stats']['spa'], 'Special':activedic['stats']['spd']}[move[3]] * int(move[6]) * eff[move[2].lower()][ennemymon.typing1] * eff[move[2].lower()][ennemymon.typing2] * {False : 1.,  True : 1.5}[move[2].lower()==allymon.typing1 or move[2].lower()==allymon.typing2]
  100.                         if value > highestvalue:                               #algo pour déterminer le max
  101.                             highestvaluemove=movename
  102.                             highestvalue=value                                 #renvoyer la requête finale
  103.                         if debug: print movename,value,highestvalue,highestvaluemove
  104.                     if debug: print self.strid[1:]+"|/choose move "+highestvaluemove[1]+"|"+rqid
  105.                     if debug: print highestvaluemove
  106.                     ws.send(self.strid[1:]+"|/choose move "+highestvaluemove+"|"+rqid)
  107.  
  108.     def reacttoswitch(self,parsed):
  109.         if debug: print self.idp,parsed[2][:2]
  110.         if parsed[2][:2]!=self.idp:                                            #s'il s'agit du joueur adverse
  111.             self.activeopponent=parsed[2][5:]                                  #mettre à jour le poké adverse actif
  112.     def reacttopoke(self,parsed):
  113.         if parsed[2]=={'p1':'p2' , 'p2':'p1' }[self.idp]:                      #si c'est un poké adverse
  114.             self.ennemies.append(parse( parsed[3],',' )[0] )                   #l'ajouter à la liste
  115.     def reacttowin(self,parsed):
  116.         ws.send(self.strid[1:]+"|/leave")                                      #si l'un des deux joueurs à gagné (issue sans importance)
  117.         if chainladd:
  118.             stridtoid.pop(self.strid)                                          #quitter + enlever le strid de la liste des matchs en cours
  119.             threading.Timer(5,lookforacc1v1).start()
  120.  
  121.  
  122.  
  123. def redirection(message):
  124.     nparsed=parse(message,"\n")
  125.     if len(nparsed)<30:                                                       #vérif nécessaire car le log quand on rejoind une room fait >>30 lignes
  126.         if nparsed[0][:8]==">battle-":                                        #si c'est un message de match alors
  127.             if nparsed[1]=="|init|battle":                                    #si c'est un message d'init
  128.                 Battle(nparsed[0])                                            #ajouter le strid à la liste des matchs en cours  /!/ NE PAS SPECTATE UN AUTRE MATCH !
  129.                 if debug: print stridtoid
  130.             if nparsed[0] in stridtoid:
  131.                 for line in nparsed[1:]:                                        
  132.                     parsed=parse(line,"|")
  133.                     if len(parsed)>1:
  134.                         if parsed[1]=="request":
  135.                             stridtoid[nparsed[0]].currentreqdata=json.loads(parsed[2])                             #transformer le message json en un dictionnaire
  136.                             if stridtoid[nparsed[0]].idp=='0':
  137.                                 stridtoid[nparsed[0]].idp=stridtoid[nparsed[0]].currentreqdata['side']['id']
  138.                                 if debug: print "idp updated"
  139.                             #stridtoid[nparsed[0]].reacttorequest(reqdata)
  140.                         if parsed[1]=="poke":
  141.                             stridtoid[nparsed[0]].reacttopoke(parsed)
  142.                         if parsed[1]=="switch":
  143.                             stridtoid[nparsed[0]].reacttoswitch(parsed)
  144.                         if parsed[1]=="win":
  145.                             stridtoid[nparsed[0]].reacttowin(parsed)
  146.                         if parsed[1]=="turn" or parsed[1]=="teampreview":
  147.                             stridtoid[nparsed[0]].reacttorequest(stridtoid[nparsed[0]].currentreqdata)
  148. #                        if parsed[1]=="leave":
  149. #                            if chainladd:
  150. #                                ws.send("|/search challengecup1vs1 ")
  151.  
  152.                    
  153. class ThreadReception(threading.Thread):
  154.     def ___init___(self):
  155.         threading.Thread.__init__(self)
  156.     def run(self):
  157.         while threadstopcondition==False:
  158.             message=ws.recv()
  159.             print message
  160.             redirection(message)
  161.        
  162. def end():
  163.     global threadstopcondition
  164.     threadstopcondition=True
  165.     ws.close()
  166.  
  167. def lookforacc1v1():
  168.     ws.send("|/utm ")
  169.     ws.send("|/search challengecup1vs1 ")
  170.  
  171. th=ThreadReception()
  172. th.start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement