Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- print 'test0'
- import websocket,urllib,urllib2,time,threading
- from surge import dicopoke,datacalc,lowerandkill
- from datacalc import eff
- from pokedexjs import moves
- import json
- from copy import deepcopy
- from os import chdir
- print 'test1'
- chdir("C:\\Users\\Julien\\Desktop\\PS BOT")
- log=open('logcubeon.txt','r+')
- req2=urllib2.Request("http://www.smogon.com/stats/2015-04/moveset/ounomega-0.txt")
- response2=urllib2.urlopen(req2)
- result2=response2.read()
- correctifnom={"Keldeo-Resolute":"Keldeo"}
- #usage_list=(result2+).split(' +----------------------------------------+ ')
- usagedata=result2.split('\n')
- class EnemyInstance(dict):
- def __init__(self,unmodifiedname,gender='none'):
- name=lowerandkill(unmodifiedname,[' ','-',"'"])
- for dicopoke_loop_enemy in dicopoke[name]:
- if dicopoke_loop_enemy!='sets':
- self[dicopoke_loop_enemy]=dicopoke[name][dicopoke_loop_enemy]
- self['knownmoves']=[]
- self['knownitem']='Unknown'
- self['status']=''
- self['%hp']=100
- self['boosts']={'atk':0,'def':0,'spa':0,'spd':0,'spe':0}
- self['secondarystatuses']=[] #leech seed, confusion ...
- self['gender']=gender
- self['name']=name
- self['listposition']=0
- self['movelock']=''
- if self['pysets']:
- self['set']=self['pysets'][0]
- else:
- if unmodifiedname in correctifnom:
- unmodifiedname=correctifnom[unmodifiedname]
- try:
- index=usagedata.index(" | "+unmodifiedname+" "*(39-len(unmodifiedname))+"| ")
- except:
- print "#### ERROR : POKEMON UNKNOWN :"+unmodifiedname
- separationlist=[separation for separation in range(index,index+200) if usagedata[separation]==' +----------------------------------------+ ']
- #Ici on crée un set (nul) pour palier au manque
- pyset_custom={}
- pyset_custom['ability']=usagedata[separationlist[1]+2].split('%')[0][3:-7]
- pyset_custom['item']=usagedata[separationlist[2]+2].split('%')[0][3:-7]
- nature_and_evs=usagedata[separationlist[3]+2].split('%')[0][3:-7]
- pyset_custom['nature']=nature_and_evs.split(':')[0]
- pysets_EVs={}
- pysets_EVs['hp'],pysets_EVs['atk'],pysets_EVs['def'],pysets_EVs['spa'],pysets_EVs['spd'],pysets_EVs['spe']=[int(stat) for stat in nature_and_evs.split(':')[1].split('/')]
- pyset_custom['evstats']=pysets_EVs
- pyset_custom['stats']={'hp':datacalc.stathp(dicopoke[name]['baseStats']['hp'],pysets_EVs['hp']),
- 'atk':datacalc.statpashp(dicopoke[name]['baseStats']['atk'],pysets_EVs['atk'],31,datacalc.natureversboost(pyset_custom['nature'],'atk')),
- 'def':datacalc.statpashp(dicopoke[name]['baseStats']['def'],pysets_EVs['def'],31,datacalc.natureversboost(pyset_custom['nature'],'def')),
- 'spa':datacalc.statpashp(dicopoke[name]['baseStats']['spa'],pysets_EVs['spa'],31,datacalc.natureversboost(pyset_custom['nature'],'spa')),
- 'spd':datacalc.statpashp(dicopoke[name]['baseStats']['spd'],pysets_EVs['spd'],31,datacalc.natureversboost(pyset_custom['nature'],'spd')),
- 'spe':datacalc.statpashp(dicopoke[name]['baseStats']['spe'],pysets_EVs['spe'],31,datacalc.natureversboost(pyset_custom['nature'],'spe'))}
- pyset_custom['moves']=[lowerandkill(usagedata[separationlist[4]+i].split('%')[0][3:-7],[' ','-']) for i in range(2,6)]
- pyset_custom['movesalts']=[]
- pyset_custom['level']=100
- self['pysets'].append(pyset_custom)
- self['set']=self['pysets'][0]
- print "##TEST CREATION SET : "+str(self['set'])
- def state(self):
- print self['name']+" : "+str(self['%hp'])+','+self['status']
- class AllyInstance(dict):
- def __init__(self,name,pyset,number,gender='none'):
- for dicopoke_loop_ally in dicopoke[name]:
- if dicopoke_loop_ally!='sets':
- self[dicopoke_loop_ally]=dicopoke[name][dicopoke_loop_ally]
- self['set']=pyset
- self['status']=''
- self['%hp']=100
- self['boosts']={'atk':0,'def':0,'spa':0,'spd':0,'spe':0}
- self['secondarystatuses']=[] #leech seed, confusion ...
- self['gender']=gender
- self['name']=name
- self['listposition']=0
- self['teamposition']=number
- self['movelock']=''
- def state(self):
- print self['name']+" : "+str(self['%hp'])+','+self['status']
- def damagecalc(MonInstance1,MonInstance2,movename,battle,mode='fast'): # mode = 'fast' or 'precise'
- ### Before Damage Calc
- atleast1=True
- # Instance1={i:MonInstance1[i] for i in MonInstance1}
- # Instance2={i:MonInstance2[i] for i in MonInstance2}
- Instance1=deepcopy(MonInstance1)
- Instance2=deepcopy(MonInstance2)
- #sandstorm boosts Rock types mons' spd by 50%
- if battle.weather=='Sandstorm' and 'Rock' in Instance2['types']:
- Instance2['set']['stats']['spd']=Instance2['set']['stats']['spd']*1.5
- #item effects before calcs
- #for Instance1
- elif Instance1['set']['item']=='Choice Band':
- Instance1['set']['stats']['atk']=Instance1['set']['stats']['atk']*1.5
- elif Instance1['set']['item']=='Choice Specs':
- Instance1['set']['stats']['spa']=Instance1['set']['stats']['spa']*1.5
- elif Instance1['name']=='clamperl' and Instance1['set']['item']=='Deepseatooth':
- Instance1['set']['stats']['spa']=Instance1['set']['stats']['spa']*2
- elif (Instance1['name']=='cubone' or Instance1['name']=='marowak') and Instance1['set']['item']=='Thick Club':
- Instance1['set']['stats']['atk']=Instance1['set']['stats']['atk']*2
- elif (Instance1['name']=='latias' or Instance1['name']=='latios') and Instance1['set']['item']=='Soul Dew':
- Instance1['set']['stats']['spa']=Instance1['set']['stats']['spa']*1.5
- elif Instance1['set']['item']=="Muscle Band":
- Instance1['set']['stats']['atk']=Instance1['set']['stats']['atk']*1.1
- elif Instance1['set']['item']=="Wise Glasses":
- Instance1['set']['stats']['spa']=Instance1['set']['stats']['spa']*1.1
- #for Instance2
- if Instance2['set']['item']=='Assault Vest':
- Instance2['set']['stats']['spd']=Instance2['set']['stats']['spd']*1.5
- if Instance2['name']=='clamperl' and Instance2['set']['item']=='Deepseascale':
- Instance2['set']['stats']['spd']=Instance2['set']['stats']['spd']*2
- elif (Instance2['name']=='latias' or Instance2['name']=='latios') and Instance2['set']['item']=='Soul Dew':
- Instance2['set']['stats']['spd']=Instance2['set']['stats']['spd']*1.5
- #Item modifiers on move power
- movepower_modifier=1.
- if Instance1['set']['item']=="Sky Plate" and moves[movename]['type']=='Flying':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Draco Plate" and moves[movename]['type']=='Dragon':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Mind Plate" and moves[movename]['type']=='Psychic':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Spooky Plate" and moves[movename]['type']=='Ghost':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Iron Plate" and moves[movename]['type']=='Steel':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Flame Plate" and moves[movename]['type']=='Fire':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Icicle Plate" and moves[movename]['type']=='Ice':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Meadow Plate" and moves[movename]['type']=='Grass':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Splash Plate" and moves[movename]['type']=='Water':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Insect Plate" and moves[movename]['type']=='Bug':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Dread Plate" and moves[movename]['type']=='Dark':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Pixie Plate" and moves[movename]['type']=='Fairy':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Fist Plate" and moves[movename]['type']=='Fighting':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Stone Plate" and moves[movename]['type']=='Rock':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Earth Plate" and moves[movename]['type']=='Ground':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Toxic Plate" and moves[movename]['type']=='Poison':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Zap Plate" and moves[movename]['type']=='Electric':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Magnet" and moves[movename]['type']=='Electric':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Sharp Beak" and moves[movename]['type']=='Flying':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Black Belt" and moves[movename]['type']=='Flying':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Charcoal" and moves[movename]['type']=='Fire':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Dragon Fang" and moves[movename]['type']=='Dragon':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="TwistedSpoon" and moves[movename]['type']=='Psychic':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Mystic Water" and moves[movename]['type']=='Electric':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Odd Incense" and moves[movename]['type']=='Psychic':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Rose Incense" and moves[movename]['type']=='Grass':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Sea Incense" and moves[movename]['type']=='Water':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Rock Incense" and moves[movename]['type']=='Rock':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Wave Incense" and moves[movename]['type']=='Water':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="NeverMeltIce" and moves[movename]['type']=='Ice':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Miracle Seed" and moves[movename]['type']=='Electric':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="BlackGlasses" and moves[movename]['type']=='Dark':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Silk Scarf" and moves[movename]['type']=='Normal':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="BlackGlasses" and moves[movename]['type']=='Dark':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Adamant Orb" and (moves[movename]['type']=='Dragon' or moves[movename]['type']=='Steel') and Instance1['name']=='dialga':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Lustrous Orb" and (moves[movename]['type']=='Dragon' or moves[movename]['type']=='Water') and Instance1['name']=='palkia':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Griseous Orb" and (moves[movename]['type']=='Dragon' or moves[movename]['type']=='Ghost') and Instance1['name']=='giratina':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Poison Barb" and moves[movename]['type']=='Poison':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Hard Stone" and moves[movename]['type']=='Rock':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="SilverPowder" and moves[movename]['type']=='Bug':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Spell Tag" and moves[movename]['type']=='Ghost':
- movepower_modifier=1.2
- elif Instance1['set']['item']=="Soft Sand" and moves[movename]['type']=='Ground':
- movepower_modifier=1.2
- ###Calculation
- if moves[movename]['category']=='Special' and (not movename in ['Psyshock','Psystrike']):
- IniDamage=((((2.*Instance1['set']['level']/5.+2.)*( moves[movename]['basePower'] * movepower_modifier) * Instance1['set']['stats']['spa'] / Instance2['set']['stats']['spd'])//50)+2)
- elif moves[movename]['category']=='Physical':
- IniDamage=((((2.*Instance1['set']['level']/5.+2.)*( moves[movename]['basePower'] * movepower_modifier) * Instance1['set']['stats']['atk'] / Instance2['set']['stats']['def'])//50)+2)
- elif movename in ['Psyshock','Psystrike']:
- IniDamage=((((2.*Instance1['set']['level']/5.+2.)*( moves[movename]['basePower'] * movepower_modifier) * Instance1['set']['stats']['spa'] / Instance2['set']['stats']['def'])//50)+2)
- #random factor
- temp_damages=[ (IniDamage*i/100.) for i in range(85,101) ]
- #apply weather modifier
- if (battle.weather=='SunnyDay' or battle.weather=='DesolateLand') and moves[movename]['type']=='Fire':
- temp_damages=[i*1.5//1 for i in temp_damages]
- elif (battle.weather=='RainDance' or battle.weather=='PrimordialSea') and moves[movename]['type']=='Water':
- temp_damages=[i*1.5 for i in temp_damages]
- #apply STAB
- if moves[movename] in Instance1['types']:
- temp_damages=[i*1.5//1 for i in temp_damages]
- #apply effectiveness modifier
- for eff_type in Instance2['types']:
- temp_damages=[i*eff[ moves[movename]['type'] ][eff_type]//1 for i in temp_damages]
- if eff[ moves[movename]['type'] ][eff_type]==0:
- atleast1=False
- #apply abilities here
- if Instance2['set']['ability']=='Levitate' and moves[movename]['type']=='Ground':
- temp_damages=[0]*len(temp_damages)
- atleast1=False
- if Instance2['set']['ability']=='Thick Fat' and moves[movename]['type'] in ['Fire','Ice']:
- temp_damages=[max(1,i/2) for i in temp_damages]
- if Instance2['set']['ability']=='Volt Absorb' and moves[movename]['type']=='Electric':
- temp_damages=[0]*len(temp_damages)
- atleast1=False
- if Instance2['set']['ability']=='Water Absorb' and moves[movename]['type']=='Water':
- temp_damages=[0]*len(temp_damages)
- atleast1=False
- if Instance2['set']['ability']=='Storm Drain' and moves[movename]['type']=='Water':
- temp_damages=[0]*len(temp_damages)
- atleast1=False
- if Instance2['set']['ability']=='Dry Skin' and moves[movename]['type']=='Water':
- temp_damages=[0]*len(temp_damages)
- atleast1=False
- if Instance2['set']['ability']=='Sap Sipper' and moves[movename]['type']=='Grass':
- temp_damages=[0]*len(temp_damages)
- atleast1=False
- if Instance2['set']['ability']=='Lightning Grod' and moves[movename]['type']=='Electric':
- temp_damages=[0]*len(temp_damages)
- atleast1=False
- if Instance2['set']['ability']=='Flash Fire' and moves[movename]['type']=='Fire':
- temp_damages=[0]*len(temp_damages)
- atleast1=False
- if Instance2['set']['ability']=='Dry Skin' and moves[movename]['type']=='Fire':
- temp_damages=[i*1.5//1 for i in temp_damages]
- #alter with user's burn
- if Instance1['status']=='brn' and moves[movename]['category']=='Physical':
- temp_damages=[i//2 for i in temp_damages]
- #make sure the damage is at least 1
- if atleast1:
- temp_damages=[max(1,i) for i in temp_damages]
- #ITEMS
- if Instance1['set']['item']=="Expert Belt":
- temp_damages=[round(i*1.2) for i in temp_damages]
- elif Instance1['set']['item']=="Life Orb":
- temp_damages=[round(i*1.3) for i in temp_damages]
- #Multihit power modifier
- if 'multihit' in moves[movename]:
- if moves[movename]['multihit']==[2,5]:
- temp_damages=[3*i for i in temp_damages]
- return temp_damages
- stridtobattle={}
- class Battle():
- def __init__(self,team,strid):
- self.player=0
- self.allies=team #[6 AllyInstance]
- self.enemies=[]
- self.activeAlly=team[0] #sera un AllyInstance (nom foireux car zorua)
- self.activeEnemy='' #sera un EnemyInstance
- self.weather='Normal' ###Les activeXXX doivent être des alias guidant vers la même adresse mémoire que les instances dans les listes.
- self.weatherresettimer=0
- self.fieldeffects=[] #ici, mettre des 2 uplets effect/timer voir 3 si walls
- self.strid=strid
- # self.movedictallyenemy={loop_ally['name']:{} for loop_ally in team}
- # self.movedictenemyally={}
- self.damagedictallyenemy={loop_ally['name']:{} for loop_ally in team}
- self.damagedictenemyally={}
- self.reqdata=''
- self.reactedto=False
- self.pivotmove=False
- self.studiedmove=[]
- stridtobattle[strid]=self
- def confront(self,Instance1,Instance2,fastestInstance,lenght=1): #cette fois, les Instance envoyés en argument seront des copies et le calcul sera fait directement sur les hps
- #Inclure les modifications de vitesse avant de les passer à confront
- #INSTANCE 1 = ALLY ; INSTANCE 2 = ENEMY
- if Instance1['%hp']>0 and Instance2['%hp']>0:
- if fastestInstance is Instance1:
- #si Instance1 est plus rapide
- Instance2['%hp']+=-self.damagedictallyenemy[ Instance1['name'] ][ Instance2['name'] ][1]
- #items appliqués en combat
- if 'contact' in moves[self.damagedictallyenemy[ Instance1['name'] ][ Instance2['name'] ][0]]['flags']:
- if Instance2['set']['item']=='Rocky Helmet':
- Instance1['%hp']+=-16.67
- if Instance2['set']['ability']=='Iron Barbs' or Instance2['set']['ability']=='Rough Skin':
- Instance1['%hp']+=-12.5
- else:
- #si Instance2 est plus rapide
- Instance1['%hp']+=-self.damagedictenemyally[ Instance2['name'] ][ Instance1['name'] ][1]
- #items appliqués en combat
- if 'contact' in moves[self.damagedictenemyally[ Instance2['name'] ][ Instance1['name']][0]]['flags']:
- if Instance1['set']['item']=='Rocky Helmet':
- Instance2['%hp']+=-16.67
- if Instance1['set']['ability']=='Iron Barbs' or Instance1['set']['ability']=='Rough Skin':
- Instance2['%hp']+=-12.5
- if Instance1['%hp']>0 and Instance2['%hp']>0:
- #si y'a pas eu de mort
- if fastestInstance is Instance1:
- #si Instance 1 est plus rapide c'est à son tour de prendre les dégats
- Instance1['%hp']+=-self.damagedictenemyally[ Instance2['name'] ][ Instance1['name'] ][1]
- else:
- #si Instance 2 est plus rapide il prend les dégats
- Instance2['%hp']+=-self.damagedictallyenemy[ Instance1['name'] ][ Instance2['name'] ][1]
- #applications items et/ou statuts/climats
- #items
- for loop_Instance in [Instance1,Instance2]:
- if loop_Instance['%hp']>0:
- if loop_Instance['set']['item']=='Leftovers':
- loop_Instance['%hp']+=6.25
- if loop_Instance['set']['item']=='Black Sludge':
- if 'Poison' in loop_Instance['types']:
- loop_Instance['%hp']+=6.25
- else:
- loop_Instance['%hp']+=-12.5
- #statuts
- if loop_Instance['status']=='tox':
- loop_Instance['%hp']+=-(lenght+1)*6.25
- if loop_Instance['status']=='psn' or loop_Instance['status']=='brn':
- loop_Instance['%hp']+=-12.5
- #climats
- if self.weather=='Sandstorm' and lenght<self.weatherresettimer and (not 'Rock' in loop_Instance['types']) and (not 'Ground' in loop_Instance['types']) and (not 'Steel' in loop_Instance['types']):
- loop_Instance['%hp']+=-6.25
- if self.weather=='Hail' and lenght<self.weatherresettimer and (not 'Ice' in loop_Instance['types']):
- loop_Instance['%hp']+=-6.25
- #Si y'a pas eu de mort, refaire avec lenght+1
- if Instance1['%hp']>0 and Instance2['%hp']>0 and lenght<40:
- return self.confront(Instance1,Instance2,fastestInstance,lenght+1)
- else:
- return [max(0,Instance1['%hp']),max(0,Instance2['%hp'])]
- # if Instance1['%hp']>0:
- # return [Instance1['%hp'],0]
- # else: #Instance1 mort ne veut pas dire Instance2 en vie. On évite de renvoyer des hps négatifs.
- # return [0,max(0,Instance2['%hp'])]
- def SituationRate(self):
- SituationRatingLocal=0
- for ally in self.allies:
- for enemy in self.enemies:
- allyoffensivemoves=[offensive_move for offensive_move in ally['set']['moves'] if moves[offensive_move]['category']!="Status"]
- enemyoffensivemoves=[offensive_move for offensive_move in enemy['set']['moves'] if moves[offensive_move]['category']!="Status"]
- bestoffensivemove1to2='nomove'
- bestdamages1to2=[0]*2
- for offensive_move in allyoffensivemoves:
- temp_damages_confront=damagecalc(ally,enemy,offensive_move,self,'fast')
- if temp_damages_confront[1]>bestdamages1to2[1]:
- bestdamages1to2=temp_damages_confront
- bestoffensivemove1to2=offensive_move
- bestoffensivemove2to1='nomove'
- bestdamages2to1=[0]*2
- for offensive_move in enemyoffensivemoves:
- temp_damages_confront=damagecalc(enemy,ally,offensive_move,self,'fast')
- if temp_damages_confront[1]>bestdamages2to1[1]:
- bestdamages2to1=temp_damages_confront
- bestoffensivemove2to1=offensive_move
- averagedamages1to2=(bestdamages1to2[0]+bestdamages1to2[1])/2.
- averagedamages2to1=(bestdamages2to1[0]+bestdamages2to1[1])/2.
- self.damagedictallyenemy[ally['name']][enemy['name']]=[bestoffensivemove1to2,averagedamages1to2/enemy['set']['stats']['hp']*100.]
- self.damagedictenemyally[enemy['name']][ally['name']]=[bestoffensivemove2to1,averagedamages2to1/ally['set']['stats']['hp']*100.] #bien des float car average float
- allycopy=deepcopy(ally)
- enemycopy=deepcopy(enemy)
- #todo : apply speed changes
- if allycopy['set']['item']=='Choice Scarf':
- allycopy['set']['stats']['spe']=int(allycopy['set']['stats']['spe']*1.5)
- if enemycopy['set']['item']=='Choice Scarf':
- enemycopy['set']['stats']['spe']=int(enemycopy['set']['stats']['spe']*1.5)
- if allycopy['status']=='par':
- allycopy['set']['stats']['spe']=allycopy['set']['stats']['spe']/4
- if enemycopy['status']=='par':
- enemycopy['set']['stats']['spe']=enemycopy['set']['stats']['spe']/4
- #decide fastest one
- if allycopy['set']['stats']['spe']>enemycopy['set']['stats']['spe']:
- fastestInstance=allycopy
- else:
- fastestInstance=enemycopy
- confront_result=self.confront(allycopy,enemycopy,fastestInstance,0)
- SituationRatingLocal+=confront_result[0]-confront_result[1]
- return SituationRatingLocal
- def RequestAnswer(self,faint=False):
- print "RequestAnswerReact"
- if self.reactedto==False:
- print "Reactedto check passed"
- if 'rqid' in self.reqdata:
- print "rqid in reqdata"
- SituationRating=self.SituationRate()
- BestChoice=''
- BestChoiceRating=-9999
- if not 'forceSwitch' in self.reqdata:
- print "MOVELOCK TEST :"+str([ move for move in self.activeAlly['set']['moves'] ])+"MOVELOCK ="+self.activeAlly['movelock']
- #include speed modifications here in a speed integer
- ModifiedSpeedValueAlly=self.activeAlly['set']['stats']['spe']
- #dostuffhere
- ModifiedSpeedValueEnemy=self.activeEnemy['set']['stats']['spe']
- #dostuffhere
- if ModifiedSpeedValueAlly<ModifiedSpeedValueEnemy:
- FirstToPlayWithoutPrio='ally'
- else:
- FirstToPlayWithoutPrio='enemy'
- for move in [movenotlock for movenotlock in self.activeAlly['set']['moves'] if (self.activeAlly['movelock'] in ['',movenotlock])]:
- LittleThief=deepcopy(self)
- if moves[move]['priority']>moves[ self.damagedictenemyally[self.activeEnemy['name']][self.activeAlly['name']][0] ]['priority']:
- FirstToPlay='ally'
- elif moves[move]['priority']<moves[ self.damagedictenemyally[self.activeEnemy['name']][self.activeAlly['name']][0] ]['priority']:
- FirstToPlay='enemy'
- else:
- FirstToPlay=FirstToPlayWithoutPrio
- if FirstToPlay=='ally':
- print
- print 'path : RequestAnswer -> FirstToPlay = ally'
- print
- if moves[move]['basePower'] != 0:
- abstract_damages=damagecalc(self.activeAlly,self.activeEnemy,move,self,mode='fast')
- print move+" : "+str(-(abstract_damages[0]+abstract_damages[1])/2. *100. / LittleThief.activeEnemy['set']['stats']['hp'])
- LittleThief.activeEnemy['%hp']+=- min(abstract_damages[0]+abstract_damages[1]/2. *100. / LittleThief.activeEnemy['set']['stats']['hp'], LittleThief.activeEnemy['%hp'])
- if not self.activeEnemy['status']:
- if move=='toxic' and not 'Poison' in self.activeEnemy['types'] and not 'Steel' in self.activeEnemy['types']:
- LittleThief.activeEnemy['status']='tox'
- elif move=='willowisp' and not 'Fire' in self.activeEnemy['types']:
- LittleThief.activeEnemy['status']='brn'
- elif move=='thunderwave' and not 'Electric' in self.activeEnemy['types'] and not 'Ground' in self.activeEnemy['types']:
- LittleThief.activeEnemy['status']='par'
- elif move=='thunderwave' and not 'Electric' in self.activeEnemy['types']:
- LittleThief.activeEnemy['status']='par'
- elif move=='poisonpowder' and not 'Poison' in self.activeEnemy['types'] and not 'Steel' in self.activeEnemy['types']:
- LittleThief.activeEnemy['status']='psn'
- if LittleThief.activeEnemy['%hp']!=0:
- LittleThief.activeAlly['%hp']+=- min(LittleThief.activeAlly['%hp'],self.damagedictenemyally[self.activeEnemy['name']][self.activeAlly['name']][1])
- #si c'est l'ennemi qui joue en premier
- else:
- print 'path : RequestAnswer -> FirstToPlay = enemy'
- LittleThief.activeAlly['%hp']+=- min(LittleThief.activeAlly['%hp'],self.damagedictenemyally[self.activeEnemy['name']][self.activeAlly['name']][1])
- if LittleThief.activeAlly['%hp']!=0:
- if moves[move]['basePower'] != 0:
- abstract_damages=damagecalc(self.activeAlly,self.activeEnemy,move,self,mode='fast')
- LittleThief.activeEnemy['%hp']+=- min( (abstract_damages[0]+abstract_damages[1])/2. *100. / LittleThief.activeEnemy['set']['stats']['hp'] , LittleThief.activeEnemy['%hp'] )
- if not self.activeEnemy['status']:
- if move=='toxic' and not 'Poison' in self.activeEnemy['types'] and not 'Steel' in self.activeEnemy['types']:
- LittleThief.activeEnemy['status']='tox'
- elif move=='willowisp' and not 'Fire' in self.activeEnemy['types']:
- LittleThief.activeEnemy['status']='brn'
- elif move=='thunderwave' and not 'Electric' in self.activeEnemy['types'] and not 'Ground' in self.activeEnemy['types']:
- LittleThief.activeEnemy['status']='par'
- elif move=='thunderwave' and not 'Electric' in self.activeEnemy['types']:
- LittleThief.activeEnemy['status']='par'
- elif move=='poisonpowder' and not 'Poison' in self.activeEnemy['types'] and not 'Steel' in self.activeEnemy['types']:
- LittleThief.activeEnemy['status']='psn'
- AbstractSituationRating=LittleThief.SituationRate()
- SituationRatingDifference=AbstractSituationRating-SituationRating
- print move," Situation Rating :",SituationRatingDifference
- if SituationRatingDifference>BestChoiceRating:
- BestChoiceRating=SituationRatingDifference
- BestChoice=move
- activeAllyBeforeSwitchName=self.activeAlly['name']
- for allies_index in range(len(self.allies)):
- if self.allies[allies_index]['teamposition']!=1 and self.allies[allies_index]['%hp']!=0:
- print "# WAS TESTED :"+self.allies[allies_index]['name']
- LittleThief=deepcopy(self)
- # LittleThief.allies=[copy(ally) for ally in self.allies]
- # LittleThief.enemies=[copy(enemy) for enemy in self.enemies]
- # LittleThief.activeEnemy=LittleThief.enemies[ self.activeEnemy['listposition'] ]
- LittleThief.activeAlly=LittleThief.allies[allies_index]
- abstract_damages=damagecalc(LittleThief.activeEnemy,LittleThief.activeAlly,LittleThief.damagedictenemyally[ LittleThief.activeEnemy['name'] ][ activeAllyBeforeSwitchName ][0],self,mode='fast')
- LittleThief.activeAlly['%hp']+= - min( (abstract_damages[1]+abstract_damages[0])/2. , LittleThief.activeAlly['%hp'] )
- AbstractSituationRating=LittleThief.SituationRate()
- print
- print LittleThief.allies[allies_index]['name']+' : '+str(AbstractSituationRating)+' , '+str(SituationRating)
- print
- log.write("#####"+LittleThief.allies[allies_index]['name']+' : '+str(AbstractSituationRating)+' , '+str(SituationRating) )
- SituationRatingDifference=AbstractSituationRating-SituationRating+6*(LittleThief.damagedictallyenemy[ LittleThief.activeAlly['name'] ][ LittleThief.activeEnemy['name'] ][1] - LittleThief.damagedictenemyally[ LittleThief.activeEnemy['name'] ][ LittleThief.activeAlly['name'] ][1] )
- print self.allies[allies_index]['name'],SituationRatingDifference
- if SituationRatingDifference>BestChoiceRating:
- BestChoiceRating=SituationRatingDifference
- BestChoice=allies_index
- # for i in self.damagedictallyenemy:
- # print i,self.damagedictallyenemy[i]
- # print
- # for i in self.damagedictenemyally:
- # print i,self.damagedictenemyally[i]
- for i in self.allies + self.enemies:
- i.state()
- if type(BestChoice) == int:
- print "SENT :"+self.strid[1:]+'|/switch '+str(self.allies[BestChoice]['teamposition'])+'|'+str(self.reqdata['rqid'])
- log.write("#-#"+"SENT :"+self.strid[1:]+'|/switch '+str(self.allies[BestChoice]['teamposition'])+'|'+str(self.reqdata['rqid']))
- ws.send( self.strid[1:]+'|/switch '+str(self.allies[BestChoice]['teamposition'])+'|'+str(self.reqdata['rqid']) )
- else:
- print "SENT :"+self.strid[1:]+'|/choose move '+str(BestChoice)+'|'+str(self.reqdata['rqid'])
- log.write("#_#"+"SENT :"+self.strid[1:]+'|/choose move '+str(BestChoice)+'|'+str(self.reqdata['rqid']))
- ws.send( self.strid[1:]+'|/choose move '+str(BestChoice)+'|'+str(self.reqdata['rqid']) )
- self.reactedto=True
- else:
- print "FAIL."
- def react(self,message,last=False):
- bparsed=message.split('|')
- if len(bparsed)>1:
- if bparsed[1]=='win':
- ws.send(self.strid[1:]+'|/leave')
- stridtobattle.pop(self.strid)
- if bparsed[1]=='player' and len(bparsed)>2:
- print 'testplayer'
- if bparsed[3]=='Cube On':
- self.player=bparsed[2]
- else:
- if bparsed[2]=='p1':
- self.player='p2'
- else:
- self.player='p1'
- if bparsed[1]=='poke':
- print 'testpoke'
- if bparsed[2]!=self.player:
- vparsed=bparsed[3].split(',')
- if len(vparsed)==2:
- self.enemies.append(EnemyInstance(lowerandkill(vparsed[0],['-',' ',"'"]), vparsed[1][1]) )
- else:
- self.enemies.append(EnemyInstance(lowerandkill(vparsed[0],['-',' ',"'"])) )
- self.damagedictenemyally[lowerandkill(vparsed[0],['-',' ',"'"])]={}
- self.enemies[-1]['listposition']=len(self.enemies)-1
- if bparsed[1]=='request':
- self.reqdata=json.loads(bparsed[2])
- self.reactedto=False
- if 'rqid' in self.reqdata and self.reqdata['rqid']==1:
- ws.send(self.strid[1:]+'|/team 1|1')
- if bparsed[1]=='switch':
- print 'testswitch'
- if bparsed[2][:2]==self.player:
- self.activeAlly['movelock']=''
- activeAllystr=lowerandkill( bparsed[3].split(',')[0] , [' ','-'] )
- print "~"+activeAllystr
- for ally in self.allies:
- print ally['name']
- if ally['name']==activeAllystr:
- self.activeAlly['teamposition']=ally['teamposition']
- self.activeAlly=ally
- self.activeAlly['teamposition']=1
- else:
- if self.activeEnemy!='': #car au début c'en est un
- self.activeEnemy['movelock']=''
- activeEnemystr=lowerandkill( bparsed[3].split(',')[0] , [' ','-'] )
- print '#'+activeEnemystr
- for enemy in self.enemies:
- print enemy['name']
- if enemy['name']==activeEnemystr:
- self.activeEnemy=enemy
- if bparsed[1]=='turn':
- self.RequestAnswer()
- if bparsed[1]=='faint' and bparsed[2][:2]==self.player:
- self.RequestAnswer(True)
- #ZONE APPRENTISSAGE + c'est normal qu'il y ait 2 if == move
- if bparsed[1]=='move':
- self.studiedmove=bparsed[2:] #studiedmove est alors une liste
- if bparsed[2][:2]==self.player:
- if bparsed[3] in ['U-turn','Volt Switch','Parting Shot']:
- self.pivotmove=True
- elif self.activeAlly['set']['item'] in ['Choice Scarf','Choice Band','Choice Specs']:
- self.activeAlly['movelock']=lowerandkill(bparsed[3],[' ','-',"'"])
- #[ERROR] FAUDRA INCLURE ICI UN TRUC SPECIAL POUR LES HIDDEN POWER
- else:
- if self.activeEnemy['set']['item'] in ['Choice Scarf','Choice Band','Choice Specs']:
- self.activeEnemy['movelock']=lowerandkill(bparsed[3],[' ','-',"'"])
- if bparsed[1] and bparsed[1][0]=='-':
- ##ZONE DE RECEPTION D'INFORMATION
- if bparsed[1][1:]=='damage':
- if bparsed[2][:2]==self.player:
- if bparsed[3][-3:]=='fnt':
- self.activeAlly['%hp']=0
- else:
- self.activeAlly['%hp']=float(bparsed[3].split('/')[0])/float( bparsed[3].split('/')[1].split(' ')[0] )*100
- else:
- self.activeEnemy['%hp']=int( bparsed[3].split('/')[0].split(' ')[0] )
- self.activeEnemy['hp']=int(self.activeEnemy['%hp']/100.*self.activeEnemy['set']['stats']['hp'])
- elif bparsed[1] and bparsed[1][1:]=='status':
- if bparsed[2][:2]==self.player:
- self.activeAlly['status']=bparsed[3]
- else:
- self.activeEnemy['status']=bparsed[3]
- #DOIT ETRE A LA FIN !! Pour assurer que le bot apprenne ce qui se passe à la dernière ligne du U-turn
- if last:
- self.studiedmove=[]
- if self.pivotmove:
- self.RequestAnswer()
- self.pivotmove=False
- team=[AllyInstance('gengar',{'ability': 'Levitate',
- 'evstats': {'atk': 0, 'def': 0, 'hp': 4, 'spa': 252, 'spd': 0, 'spe': 252},
- 'item': 'Black Sludge',
- 'level': 100,
- 'moves': ['hex', 'sludgebomb', 'willowisp', 'substitute'],
- 'movesalts': [],
- 'name': 'gengar',
- 'nature': 'Timid',
- 'stats': {'atk': 121.0,
- 'def': 156.0,
- 'hp': 262.0,
- 'spa': 359.0,
- 'spd': 186.0,
- 'spe': 350.0}},1),
- AllyInstance('garchomp',{'ability': 'Rough Skin',
- 'evstats': {'atk': 0, 'def': 216, 'hp': 232, 'spa': 0, 'spd': 60, 'spe': 0},
- 'item': 'Rocky Helmet',
- 'level': 100,
- 'moves': ['earthquake', 'dragontail', 'toxic', 'stealthrock'],
- 'movesalts': [],
- 'name': 'garchomp',
- 'nature': 'Impish',
- 'stats': {'atk': 296.0,
- 'def': 308.0,
- 'hp': 415.0,
- 'spa': 176.0,
- 'spd': 221.0,
- 'spe': 240.0}},2),
- AllyInstance('gliscor',{'ability': 'Poison Heal',
- 'evstats': {'atk': 0, 'def': 0, 'hp': 252, 'spa': 0, 'spd': 176, 'spe': 80},
- 'item': 'Toxic Orb',
- 'level': 100,
- 'moves': ['earthquake', 'knockoff', 'swordsdance', 'roost'],
- 'movesalts': [],
- 'name': 'gliscor',
- 'nature': 'Jolly',
- 'stats': {'atk': 226.0,
- 'def': 286.0,
- 'hp': 354.0,
- 'spa': 113.0,
- 'spd': 230.0,
- 'spe': 270.0}},3),
- AllyInstance('venusaur',{'ability': 'Chlorophyll',
- 'evstats': {'atk': 0, 'def': 0, 'hp': 200, 'spa': 168, 'spd': 0, 'spe': 140},
- 'item': 'Venusaurite',
- 'level': 100,
- 'moves': ['gigadrain', 'sludgebomb', 'hiddenpowerfire', 'synthesis'],
- 'movesalts': [],
- 'name': 'venusaur',
- 'nature': 'Modest',
- 'stats': {'atk': 152.0,
- 'def': 202.0,
- 'hp': 351.0,
- 'spa': 304.0,
- 'spd': 236.0,
- 'spe': 230.0}},4),
- AllyInstance('keldeo',{'ability': 'Justified',
- 'evstats': {'atk': 0, 'def': 0, 'hp': 0, 'spa': 252, 'spd': 4, 'spe': 252},
- 'item': 'Choice Scarf',
- 'level': 100,
- 'moves': ['hydropump', 'secretsword', 'icywind', 'scald'],
- 'movesalts': [],
- 'name': 'keldeo',
- 'nature': 'Timid',
- 'stats': {'atk': 134.0,
- 'def': 216.0,
- 'hp': 323.0,
- 'spa': 357.0,
- 'spd': 217.0,
- 'spe': 346.0}},5),
- AllyInstance('heatran',{'ability': 'Flash Fire',
- 'evstats': {'atk': 0, 'def': 0, 'hp': 252, 'spa': 0, 'spd': 216, 'spe': 40},
- 'item': 'Leftovers',
- 'level': 100,
- 'moves': ['lavaplume', 'earthpower', 'toxic', 'protect'],
- 'movesalts': [],
- 'name': 'heatran',
- 'nature': 'Calm',
- 'stats': {'atk': 166.0,
- 'def': 248.0,
- 'hp': 386.0,
- 'spa': 296.0,
- 'spd': 332.0,
- 'spe': 200.0}},6)]
- bot = True
- if bot:
- name="Cube On"
- password=
- room="lobby"
- ws=websocket.create_connection("ws://sim.smogon.com:8000/showdown/websocket")
- # ws=websocket.create_connection("ws://pokestrat.com:8000/showdown/websocket")
- ws.recv(),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 "+room)
- ws.send(room+"|/avatar 267")
- def parse(text,character,stopat=0):
- if stopat:
- p=[-1]+[i for i in range(len(text)) if text[i]==character][:(stopat-1)]+[len(text)]
- else:
- 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
- class ThreadReception(threading.Thread):
- def ___init___(self):
- threading.Thread.__init__(self)
- def run(self):
- condition=True
- while condition:
- message=ws.recv()
- print
- print message
- log.write(message+'\n')
- analysis(message)
- ws.close()
- def analysis(message):
- nparsed=parse(message,"\n")
- if len(nparsed)<40: #vérif nécessaire car le log quand on rejoind une room fait >>30 lignes
- if nparsed[0][:8]==">battle-":
- for lineindex in range(1,len(nparsed)): #si c'est un message de match alors
- if nparsed[lineindex]=="|init|battle":
- print 'testinit' #si c'est un message d'init
- Battle(team,nparsed[0]) #ajouter le strid à la liste des matchs en cours /!/ NE PAS SPECTATE UN AUTRE MATCH !
- ws.send(nparsed[0][1:]+"|/timer on")
- else:
- if nparsed[0] in stridtobattle:
- if lineindex==len(nparsed):
- stridtobattle[nparsed[0]].react(nparsed[lineindex],True)
- else:
- stridtobattle[nparsed[0]].react(nparsed[lineindex])
- for i in nparsed:
- parsed=parse(i,"|")
- if len(parsed)>1:
- if parsed[1]=="updatechallenges":
- dicochall=json.loads(parsed[2])
- for i in dicochall["challengesFrom"]:
- ws.send("""|/utm Gengar||blacksludge||hex,sludgebomb,willowisp,substitute|Timid|4,,,252,,252|M|,0,,,,|||]Garchomp||rockyhelmet|H|earthquake,dragontail,toxic,stealthrock|Impish|232,,216,,60,|M||||]Gliscor||toxicorb|H|earthquake,knockoff,swordsdance,roost|Jolly|252,,,,176,80|F||||]Venusaur||venusaurite|H|gigadrain,sludgebomb,hiddenpowerfire,synthesis|Modest|200,,,168,,140|M|,0,,30,,30|||]Keldeo||choicescarf||hydropump,secretsword,icywind,scald|Timid|,,,252,4,252||,0,,,,|||]Heatran||leftovers||lavaplume,earthpower,toxic,protect|Calm|252,,,,216,40|M|,0,,,,|||""")
- ws.send("|/accept "+i)
- if parsed[1]=='pm' and parsed[2]==' Artemis Fowl':
- ws.send(""" |/utm Gengar||blacksludge||hex,sludgebomb,willowisp,substitute|Timid|4,,,252,,252|M|,0,,,,|||]Garchomp||rockyhelmet|H|earthquake,dragontail,toxic,stealthrock|Impish|232,,216,,60,|M||||]Gliscor||toxicorb|H|earthquake,knockoff,swordsdance,roost|Jolly|252,,,,176,80|F||||]Venusaur||venusaurite|H|gigadrain,sludgebomb,hiddenpowerfire,synthesis|Modest|200,,,168,,140|M|,0,,30,,30|||]Keldeo||choicescarf||hydropump,secretsword,icywind,scald|Timid|,,,252,4,252||,0,,,,|||]Heatran||leftovers||lavaplume,earthpower,toxic,protect|Calm|252,,,,216,40|M|,0,,,,|||""")
- ws.send("|/search ounomega")
- if bot:
- print 'Connecté'
- th=ThreadReception()
- time.sleep(4)
- th.start()
- def end():
- ws.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement