Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- print "test"
- import websocket,urllib,urllib2,time,threading,json
- from movedictfile import movedict #movedict takes a movename as key and return a list of data about the move (power,typing,etc)
- from DBinter import nametomon,eff #DBinter (external file) includes mainly the entire pokemon stat database + type effectiveness table
- from random import randint
- debug=True
- name="basically wont give it"
- password="neither will i give this one"
- ws=websocket.create_connection("ws://sim.smogon.com:8000/showdown/websocket")
- #ws=websocket.create_connection("ws://85.222.228.199:8000/showdown/websocket")
- #ws=websocket.create_connection("ws://pokestrat.com:8000/showdown/websocket")
- ws.recv(),ws.recv()
- txt=ws.recv()
- Ptool=[i for i in range(len(txt)) if txt[i]=='|']
- data = urllib.urlencode({'act': 'login', 'name': name, 'pass' : password, 'challengekeyid': txt[Ptool[1]+1], 'challenge':txt[Ptool[2]+1:]})
- 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)' })
- response = urllib2.urlopen(req)
- result = response.read()
- Ptool2=[i for i in range(len(result)) if result[i]=='"']
- assertion=result[Ptool2[-2]+1:Ptool2[-1]]
- ws.send("|/trn %s,0,%s" % (name, assertion) )
- time.sleep(2)
- ws.send("|/join franais")
- def parse(text,character):
- p=[-1]+[i for i in range(len(text)) if text[i]==character]+[len(text)]
- l=[]
- for i in range(len(p)-1):
- l+=[ text[ p[i]+1:p[i+1] ] ]
- return l
- global stridtoid,threadstopcondition,chainladd
- threadstopcondition=False
- chainladd=False
- stridtoid={}
- class Battle():
- def __init__(self,strid):
- self.strid=strid
- stridtoid[self.strid]=self
- self.idp='0'
- self.allies=[]
- self.ennemies=[]
- self.activeopponent=""
- self.currentreqdata=""
- global chainladd
- def reacttorequest(self,reqdata):
- self.allies=reqdata['side']['pokemon']
- if 'rqid' in reqdata.keys():
- rqid=str(reqdata['rqid'])
- if debug: print type(rqid)
- if rqid=='1': #choix du lead, choisit actuellement le premier poké
- ###ALGO CHOIX DU LEAD
- currentmax,currentmonindex=0,0
- for i in range(6):
- studiedmon=reqdata['side']['pokemon'][i]
- k=0
- #somme des puissances des attaques
- for i3 in [i2 for i2 in studiedmon['moves'] if ( i2 in movedict and movedict[i2][6][0] in '0123456789' )]:
- k+=int(movedict[i3][6])
- #somme des stats
- k2=0
- for i2 in studiedmon['stats']:
- k2+=studiedmon['stats'][i2]
- if k*k2>currentmax:
- currentmax=k*k2
- currentmonindex=i
- teammessage=str(i)
- for i2 in ['1','2','3','4','5','6']:
- if not i2 in teammessage:
- teammessage+=i2
- ws.send(self.strid[1:]+"|/team "+teammessage+"|1")
- #ws.send(self.strid[1:]+"|/team 123456|1")
- else: #analyse du meilleur move
- activedic=reqdata['side']['pokemon'][0]
- print reqdata
- 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
- if debug:
- print attackmoves,activedic['moves']
- if len(attackmoves)==0: # si on a pas un seul move offensif, lancer des trucs au hasard ...
- if debug: print self.strid[1:]+"|/choose move "+activedic['moves'][randint(0,3)]+"|"+rqid
- ws.send(self.strid[1:]+"|/choose move "+activedic['moves'][randint(0,3)]+"|"+rqid)
- else:
- if debug: print attackmoves
- highestvaluemove=attackmoves[0]
- highestvalue=0
- for movename in attackmoves:
- allymon=nametomon[activedic['ident'][4:]]
- ennemymon=nametomon[self.activeopponent]
- move=movedict[movename] #attaque / def * puissance * eff1 * eff2 * STAB
- 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]
- if value > highestvalue: #algo pour déterminer le max
- highestvaluemove=movename
- highestvalue=value #renvoyer la requête finale
- if debug: print movename,value,highestvalue,highestvaluemove
- if debug: print self.strid[1:]+"|/choose move "+highestvaluemove[1]+"|"+rqid
- if debug: print highestvaluemove
- ws.send(self.strid[1:]+"|/choose move "+highestvaluemove+"|"+rqid)
- def reacttoswitch(self,parsed):
- if debug: print self.idp,parsed[2][:2]
- if parsed[2][:2]!=self.idp: #s'il s'agit du joueur adverse
- self.activeopponent=parsed[2][5:] #mettre à jour le poké adverse actif
- def reacttopoke(self,parsed):
- if parsed[2]=={'p1':'p2' , 'p2':'p1' }[self.idp]: #si c'est un poké adverse
- self.ennemies.append(parse( parsed[3],',' )[0] ) #l'ajouter à la liste
- def reacttowin(self,parsed):
- ws.send(self.strid[1:]+"|/leave") #si l'un des deux joueurs à gagné (issue sans importance)
- if chainladd:
- stridtoid.pop(self.strid) #quitter + enlever le strid de la liste des matchs en cours
- threading.Timer(5,lookforacc1v1).start()
- def redirection(message):
- nparsed=parse(message,"\n")
- if len(nparsed)<30: #vérif nécessaire car le log quand on rejoind une room fait >>30 lignes
- if nparsed[0][:8]==">battle-": #si c'est un message de match alors
- if nparsed[1]=="|init|battle": #si c'est un message d'init
- Battle(nparsed[0]) #ajouter le strid à la liste des matchs en cours /!/ NE PAS SPECTATE UN AUTRE MATCH !
- if debug: print stridtoid
- if nparsed[0] in stridtoid:
- for line in nparsed[1:]:
- parsed=parse(line,"|")
- if len(parsed)>1:
- if parsed[1]=="request":
- stridtoid[nparsed[0]].currentreqdata=json.loads(parsed[2]) #transformer le message json en un dictionnaire
- if stridtoid[nparsed[0]].idp=='0':
- stridtoid[nparsed[0]].idp=stridtoid[nparsed[0]].currentreqdata['side']['id']
- if debug: print "idp updated"
- #stridtoid[nparsed[0]].reacttorequest(reqdata)
- if parsed[1]=="poke":
- stridtoid[nparsed[0]].reacttopoke(parsed)
- if parsed[1]=="switch":
- stridtoid[nparsed[0]].reacttoswitch(parsed)
- if parsed[1]=="win":
- stridtoid[nparsed[0]].reacttowin(parsed)
- if parsed[1]=="turn" or parsed[1]=="teampreview":
- stridtoid[nparsed[0]].reacttorequest(stridtoid[nparsed[0]].currentreqdata)
- # if parsed[1]=="leave":
- # if chainladd:
- # ws.send("|/search challengecup1vs1 ")
- class ThreadReception(threading.Thread):
- def ___init___(self):
- threading.Thread.__init__(self)
- def run(self):
- while threadstopcondition==False:
- message=ws.recv()
- print message
- redirection(message)
- def end():
- global threadstopcondition
- threadstopcondition=True
- ws.close()
- def lookforacc1v1():
- ws.send("|/utm ")
- ws.send("|/search challengecup1vs1 ")
- th=ThreadReception()
- th.start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement