Advertisement
Guest User

Cube On Smogon Thread 21/5

a guest
May 21st, 2015
586
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 46.05 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. print 'test0'
  4.  
  5. import websocket,urllib,urllib2,time,threading
  6. from surge import dicopoke,datacalc,lowerandkill
  7. from datacalc import eff
  8. from pokedexjs import moves
  9. import json
  10. from copy import deepcopy
  11. from os import chdir
  12. print 'test1'
  13.  
  14. chdir("C:\\Users\\Julien\\Desktop\\PS BOT")
  15. log=open('logcubeon.txt','r+')
  16. req2=urllib2.Request("http://www.smogon.com/stats/2015-04/moveset/ounomega-0.txt")
  17. response2=urllib2.urlopen(req2)
  18. result2=response2.read()
  19.  
  20. correctifnom={"Keldeo-Resolute":"Keldeo"}
  21.  
  22. #usage_list=(result2+).split(' +----------------------------------------+ ')
  23. usagedata=result2.split('\n')
  24.  
  25. class EnemyInstance(dict):
  26.     def __init__(self,unmodifiedname,gender='none'):
  27.         name=lowerandkill(unmodifiedname,[' ','-',"'"])
  28.         for dicopoke_loop_enemy in dicopoke[name]:
  29.             if dicopoke_loop_enemy!='sets':
  30.                 self[dicopoke_loop_enemy]=dicopoke[name][dicopoke_loop_enemy]
  31.         self['knownmoves']=[]
  32.         self['knownitem']='Unknown'
  33.         self['status']=''
  34.         self['%hp']=100
  35.         self['boosts']={'atk':0,'def':0,'spa':0,'spd':0,'spe':0}
  36.         self['secondarystatuses']=[] #leech seed, confusion ...
  37.         self['gender']=gender
  38.         self['name']=name
  39.         self['listposition']=0
  40.         self['movelock']=''
  41.         if self['pysets']:
  42.             self['set']=self['pysets'][0]
  43.         else:
  44.             if unmodifiedname in correctifnom:
  45.                 unmodifiedname=correctifnom[unmodifiedname]
  46.             try:
  47.                 index=usagedata.index(" | "+unmodifiedname+" "*(39-len(unmodifiedname))+"| ")
  48.             except:
  49.                 print "#### ERROR : POKEMON UNKNOWN :"+unmodifiedname
  50.                
  51.             separationlist=[separation for separation in range(index,index+200) if usagedata[separation]==' +----------------------------------------+ ']
  52.             #Ici on crée un set (nul) pour palier au manque
  53.             pyset_custom={}
  54.             pyset_custom['ability']=usagedata[separationlist[1]+2].split('%')[0][3:-7]
  55.             pyset_custom['item']=usagedata[separationlist[2]+2].split('%')[0][3:-7]
  56.             nature_and_evs=usagedata[separationlist[3]+2].split('%')[0][3:-7]
  57.             pyset_custom['nature']=nature_and_evs.split(':')[0]
  58.             pysets_EVs={}
  59.             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('/')]
  60.             pyset_custom['evstats']=pysets_EVs
  61.             pyset_custom['stats']={'hp':datacalc.stathp(dicopoke[name]['baseStats']['hp'],pysets_EVs['hp']),
  62.             'atk':datacalc.statpashp(dicopoke[name]['baseStats']['atk'],pysets_EVs['atk'],31,datacalc.natureversboost(pyset_custom['nature'],'atk')),
  63.             'def':datacalc.statpashp(dicopoke[name]['baseStats']['def'],pysets_EVs['def'],31,datacalc.natureversboost(pyset_custom['nature'],'def')),
  64.             'spa':datacalc.statpashp(dicopoke[name]['baseStats']['spa'],pysets_EVs['spa'],31,datacalc.natureversboost(pyset_custom['nature'],'spa')),
  65.             'spd':datacalc.statpashp(dicopoke[name]['baseStats']['spd'],pysets_EVs['spd'],31,datacalc.natureversboost(pyset_custom['nature'],'spd')),
  66.             'spe':datacalc.statpashp(dicopoke[name]['baseStats']['spe'],pysets_EVs['spe'],31,datacalc.natureversboost(pyset_custom['nature'],'spe'))}
  67.             pyset_custom['moves']=[lowerandkill(usagedata[separationlist[4]+i].split('%')[0][3:-7],[' ','-']) for i in range(2,6)]
  68.             pyset_custom['movesalts']=[]
  69.             pyset_custom['level']=100
  70.             self['pysets'].append(pyset_custom)
  71.             self['set']=self['pysets'][0]
  72.             print "##TEST CREATION SET : "+str(self['set'])
  73.            
  74.     def state(self):
  75.         print self['name']+" : "+str(self['%hp'])+','+self['status']
  76.            
  77.            
  78.            
  79.  
  80. class AllyInstance(dict):    
  81.     def __init__(self,name,pyset,number,gender='none'):
  82.         for dicopoke_loop_ally in dicopoke[name]:
  83.             if dicopoke_loop_ally!='sets':
  84.                 self[dicopoke_loop_ally]=dicopoke[name][dicopoke_loop_ally]
  85.         self['set']=pyset
  86.         self['status']=''
  87.         self['%hp']=100
  88.         self['boosts']={'atk':0,'def':0,'spa':0,'spd':0,'spe':0}
  89.         self['secondarystatuses']=[] #leech seed, confusion ...
  90.         self['gender']=gender
  91.         self['name']=name
  92.         self['listposition']=0
  93.         self['teamposition']=number
  94.         self['movelock']=''
  95.        
  96.     def state(self):
  97.         print self['name']+" : "+str(self['%hp'])+','+self['status']
  98.    
  99. def damagecalc(MonInstance1,MonInstance2,movename,battle,mode='fast'): # mode = 'fast' or 'precise'
  100.     ### Before Damage Calc
  101.     atleast1=True
  102.    
  103. #    Instance1={i:MonInstance1[i] for i in MonInstance1}
  104. #    Instance2={i:MonInstance2[i] for i in MonInstance2}
  105.    
  106.     Instance1=deepcopy(MonInstance1)
  107.     Instance2=deepcopy(MonInstance2)
  108.    
  109.     #sandstorm boosts Rock types mons' spd by 50%
  110.     if battle.weather=='Sandstorm' and 'Rock' in Instance2['types']:
  111.         Instance2['set']['stats']['spd']=Instance2['set']['stats']['spd']*1.5
  112.  
  113.     #item effects before calcs
  114.     #for Instance1
  115.     elif Instance1['set']['item']=='Choice Band':
  116.         Instance1['set']['stats']['atk']=Instance1['set']['stats']['atk']*1.5
  117.     elif Instance1['set']['item']=='Choice Specs':
  118.         Instance1['set']['stats']['spa']=Instance1['set']['stats']['spa']*1.5
  119.     elif Instance1['name']=='clamperl' and Instance1['set']['item']=='Deepseatooth':
  120.         Instance1['set']['stats']['spa']=Instance1['set']['stats']['spa']*2
  121.     elif (Instance1['name']=='cubone' or Instance1['name']=='marowak') and Instance1['set']['item']=='Thick Club':
  122.         Instance1['set']['stats']['atk']=Instance1['set']['stats']['atk']*2
  123.     elif (Instance1['name']=='latias' or Instance1['name']=='latios') and Instance1['set']['item']=='Soul Dew':
  124.         Instance1['set']['stats']['spa']=Instance1['set']['stats']['spa']*1.5
  125.     elif Instance1['set']['item']=="Muscle Band":
  126.         Instance1['set']['stats']['atk']=Instance1['set']['stats']['atk']*1.1
  127.     elif Instance1['set']['item']=="Wise Glasses":
  128.         Instance1['set']['stats']['spa']=Instance1['set']['stats']['spa']*1.1
  129.        
  130.     #for Instance2
  131.     if Instance2['set']['item']=='Assault Vest':
  132.         Instance2['set']['stats']['spd']=Instance2['set']['stats']['spd']*1.5
  133.     if Instance2['name']=='clamperl' and Instance2['set']['item']=='Deepseascale':
  134.         Instance2['set']['stats']['spd']=Instance2['set']['stats']['spd']*2
  135.     elif (Instance2['name']=='latias' or Instance2['name']=='latios') and Instance2['set']['item']=='Soul Dew':
  136.         Instance2['set']['stats']['spd']=Instance2['set']['stats']['spd']*1.5
  137.  
  138.     #Item modifiers on move power
  139.     movepower_modifier=1.
  140.     if Instance1['set']['item']=="Sky Plate" and moves[movename]['type']=='Flying':
  141.         movepower_modifier=1.2
  142.     elif Instance1['set']['item']=="Draco Plate" and moves[movename]['type']=='Dragon':
  143.         movepower_modifier=1.2
  144.     elif Instance1['set']['item']=="Mind Plate" and moves[movename]['type']=='Psychic':
  145.         movepower_modifier=1.2
  146.     elif Instance1['set']['item']=="Spooky Plate" and moves[movename]['type']=='Ghost':
  147.         movepower_modifier=1.2
  148.     elif Instance1['set']['item']=="Iron Plate" and moves[movename]['type']=='Steel':
  149.         movepower_modifier=1.2
  150.     elif Instance1['set']['item']=="Flame Plate" and moves[movename]['type']=='Fire':
  151.         movepower_modifier=1.2
  152.     elif Instance1['set']['item']=="Icicle Plate" and moves[movename]['type']=='Ice':
  153.         movepower_modifier=1.2
  154.     elif Instance1['set']['item']=="Meadow Plate" and moves[movename]['type']=='Grass':
  155.         movepower_modifier=1.2
  156.     elif Instance1['set']['item']=="Splash Plate" and moves[movename]['type']=='Water':
  157.         movepower_modifier=1.2
  158.     elif Instance1['set']['item']=="Insect Plate" and moves[movename]['type']=='Bug':
  159.         movepower_modifier=1.2
  160.     elif Instance1['set']['item']=="Dread Plate" and moves[movename]['type']=='Dark':
  161.         movepower_modifier=1.2
  162.     elif Instance1['set']['item']=="Pixie Plate" and moves[movename]['type']=='Fairy':
  163.         movepower_modifier=1.2
  164.     elif Instance1['set']['item']=="Fist Plate" and moves[movename]['type']=='Fighting':
  165.         movepower_modifier=1.2
  166.     elif Instance1['set']['item']=="Stone Plate" and moves[movename]['type']=='Rock':
  167.         movepower_modifier=1.2
  168.     elif Instance1['set']['item']=="Earth Plate" and moves[movename]['type']=='Ground':
  169.         movepower_modifier=1.2
  170.     elif Instance1['set']['item']=="Toxic Plate" and moves[movename]['type']=='Poison':
  171.         movepower_modifier=1.2
  172.     elif Instance1['set']['item']=="Zap Plate" and moves[movename]['type']=='Electric':
  173.         movepower_modifier=1.2
  174.     elif Instance1['set']['item']=="Magnet" and moves[movename]['type']=='Electric':
  175.         movepower_modifier=1.2
  176.     elif Instance1['set']['item']=="Sharp Beak" and moves[movename]['type']=='Flying':
  177.         movepower_modifier=1.2
  178.     elif Instance1['set']['item']=="Black Belt" and moves[movename]['type']=='Flying':
  179.         movepower_modifier=1.2
  180.     elif Instance1['set']['item']=="Charcoal" and moves[movename]['type']=='Fire':
  181.         movepower_modifier=1.2
  182.     elif Instance1['set']['item']=="Dragon Fang" and moves[movename]['type']=='Dragon':
  183.         movepower_modifier=1.2
  184.     elif Instance1['set']['item']=="TwistedSpoon" and moves[movename]['type']=='Psychic':
  185.         movepower_modifier=1.2
  186.     elif Instance1['set']['item']=="Mystic Water" and moves[movename]['type']=='Electric':
  187.         movepower_modifier=1.2
  188.     elif Instance1['set']['item']=="Odd Incense" and moves[movename]['type']=='Psychic':
  189.         movepower_modifier=1.2
  190.     elif Instance1['set']['item']=="Rose Incense" and moves[movename]['type']=='Grass':
  191.         movepower_modifier=1.2
  192.     elif Instance1['set']['item']=="Sea Incense" and moves[movename]['type']=='Water':
  193.         movepower_modifier=1.2
  194.     elif Instance1['set']['item']=="Rock Incense" and moves[movename]['type']=='Rock':
  195.         movepower_modifier=1.2
  196.     elif Instance1['set']['item']=="Wave Incense" and moves[movename]['type']=='Water':
  197.         movepower_modifier=1.2
  198.     elif Instance1['set']['item']=="NeverMeltIce" and moves[movename]['type']=='Ice':
  199.         movepower_modifier=1.2
  200.     elif Instance1['set']['item']=="Miracle Seed" and moves[movename]['type']=='Electric':
  201.         movepower_modifier=1.2
  202.     elif Instance1['set']['item']=="BlackGlasses" and moves[movename]['type']=='Dark':
  203.         movepower_modifier=1.2
  204.     elif Instance1['set']['item']=="Silk Scarf" and moves[movename]['type']=='Normal':
  205.         movepower_modifier=1.2
  206.     elif Instance1['set']['item']=="BlackGlasses" and moves[movename]['type']=='Dark':
  207.         movepower_modifier=1.2
  208.     elif Instance1['set']['item']=="Adamant Orb" and (moves[movename]['type']=='Dragon' or moves[movename]['type']=='Steel') and Instance1['name']=='dialga':
  209.         movepower_modifier=1.2
  210.     elif Instance1['set']['item']=="Lustrous Orb" and (moves[movename]['type']=='Dragon' or moves[movename]['type']=='Water') and Instance1['name']=='palkia':
  211.         movepower_modifier=1.2
  212.     elif Instance1['set']['item']=="Griseous Orb" and (moves[movename]['type']=='Dragon' or moves[movename]['type']=='Ghost') and Instance1['name']=='giratina':
  213.         movepower_modifier=1.2
  214.     elif Instance1['set']['item']=="Poison Barb" and moves[movename]['type']=='Poison':
  215.         movepower_modifier=1.2
  216.     elif Instance1['set']['item']=="Hard Stone" and moves[movename]['type']=='Rock':
  217.         movepower_modifier=1.2
  218.     elif Instance1['set']['item']=="SilverPowder" and moves[movename]['type']=='Bug':
  219.         movepower_modifier=1.2
  220.     elif Instance1['set']['item']=="Spell Tag" and moves[movename]['type']=='Ghost':
  221.         movepower_modifier=1.2
  222.     elif Instance1['set']['item']=="Soft Sand" and moves[movename]['type']=='Ground':
  223.         movepower_modifier=1.2
  224.  
  225.     ###Calculation
  226.     if moves[movename]['category']=='Special' and (not movename in ['Psyshock','Psystrike']):
  227.         IniDamage=((((2.*Instance1['set']['level']/5.+2.)*( moves[movename]['basePower'] * movepower_modifier) * Instance1['set']['stats']['spa'] / Instance2['set']['stats']['spd'])//50)+2)
  228.     elif moves[movename]['category']=='Physical':
  229.         IniDamage=((((2.*Instance1['set']['level']/5.+2.)*( moves[movename]['basePower'] * movepower_modifier) * Instance1['set']['stats']['atk'] / Instance2['set']['stats']['def'])//50)+2)
  230.     elif movename in ['Psyshock','Psystrike']:
  231.         IniDamage=((((2.*Instance1['set']['level']/5.+2.)*( moves[movename]['basePower'] * movepower_modifier) * Instance1['set']['stats']['spa'] / Instance2['set']['stats']['def'])//50)+2)
  232.  
  233.     #random factor
  234.     temp_damages=[ (IniDamage*i/100.) for i in range(85,101) ]
  235.  
  236.     #apply weather modifier
  237.     if (battle.weather=='SunnyDay' or battle.weather=='DesolateLand') and moves[movename]['type']=='Fire':
  238.         temp_damages=[i*1.5//1 for i in temp_damages]
  239.     elif (battle.weather=='RainDance' or battle.weather=='PrimordialSea') and moves[movename]['type']=='Water':
  240.         temp_damages=[i*1.5 for i in temp_damages]
  241.  
  242.     #apply STAB
  243.     if moves[movename] in Instance1['types']:
  244.         temp_damages=[i*1.5//1 for i in temp_damages]
  245.  
  246.     #apply effectiveness modifier
  247.     for eff_type in Instance2['types']:
  248.         temp_damages=[i*eff[ moves[movename]['type'] ][eff_type]//1 for i in temp_damages]
  249.         if eff[ moves[movename]['type'] ][eff_type]==0:
  250.             atleast1=False
  251.    
  252.     #apply abilities here
  253.     if Instance2['set']['ability']=='Levitate' and moves[movename]['type']=='Ground':
  254.         temp_damages=[0]*len(temp_damages)
  255.         atleast1=False
  256.     if Instance2['set']['ability']=='Thick Fat' and moves[movename]['type'] in ['Fire','Ice']:
  257.         temp_damages=[max(1,i/2) for i in temp_damages]
  258.     if Instance2['set']['ability']=='Volt Absorb' and moves[movename]['type']=='Electric':
  259.         temp_damages=[0]*len(temp_damages)
  260.         atleast1=False
  261.     if Instance2['set']['ability']=='Water Absorb' and moves[movename]['type']=='Water':
  262.         temp_damages=[0]*len(temp_damages)
  263.         atleast1=False
  264.     if Instance2['set']['ability']=='Storm Drain' and moves[movename]['type']=='Water':
  265.         temp_damages=[0]*len(temp_damages)
  266.         atleast1=False
  267.     if Instance2['set']['ability']=='Dry Skin' and moves[movename]['type']=='Water':
  268.         temp_damages=[0]*len(temp_damages)
  269.         atleast1=False
  270.     if Instance2['set']['ability']=='Sap Sipper' and moves[movename]['type']=='Grass':
  271.         temp_damages=[0]*len(temp_damages)
  272.         atleast1=False
  273.     if Instance2['set']['ability']=='Lightning Grod' and moves[movename]['type']=='Electric':
  274.         temp_damages=[0]*len(temp_damages)
  275.         atleast1=False
  276.     if Instance2['set']['ability']=='Flash Fire' and moves[movename]['type']=='Fire':
  277.         temp_damages=[0]*len(temp_damages)
  278.         atleast1=False
  279.     if Instance2['set']['ability']=='Dry Skin' and moves[movename]['type']=='Fire':
  280.         temp_damages=[i*1.5//1 for i in temp_damages]
  281.            
  282.     #alter with user's burn
  283.     if Instance1['status']=='brn' and moves[movename]['category']=='Physical':
  284.         temp_damages=[i//2 for i in temp_damages]
  285.  
  286.     #make sure the damage is at least 1
  287.     if atleast1:
  288.         temp_damages=[max(1,i) for i in temp_damages]
  289.  
  290.     #ITEMS
  291.     if Instance1['set']['item']=="Expert Belt":
  292.         temp_damages=[round(i*1.2) for i in temp_damages]    
  293.     elif Instance1['set']['item']=="Life Orb":
  294.         temp_damages=[round(i*1.3) for i in temp_damages]
  295.  
  296.     #Multihit power modifier
  297.     if 'multihit' in moves[movename]:
  298.         if moves[movename]['multihit']==[2,5]:
  299.             temp_damages=[3*i for i in temp_damages]
  300.    
  301.     return temp_damages
  302.    
  303. stridtobattle={}
  304.  
  305. class Battle():
  306.     def __init__(self,team,strid):
  307.         self.player=0
  308.         self.allies=team #[6 AllyInstance]
  309.         self.enemies=[]
  310.         self.activeAlly=team[0] #sera un AllyInstance (nom foireux car zorua)
  311.         self.activeEnemy='' #sera un EnemyInstance
  312.         self.weather='Normal'  ###Les activeXXX doivent être des alias guidant vers la même adresse mémoire que les instances dans les listes.
  313.         self.weatherresettimer=0
  314.         self.fieldeffects=[] #ici, mettre des 2 uplets effect/timer voir 3 si walls
  315.         self.strid=strid
  316. #        self.movedictallyenemy={loop_ally['name']:{} for loop_ally in team}
  317. #        self.movedictenemyally={}
  318.         self.damagedictallyenemy={loop_ally['name']:{} for loop_ally in team}
  319.         self.damagedictenemyally={}
  320.         self.reqdata=''
  321.         self.reactedto=False
  322.         self.pivotmove=False
  323.         self.studiedmove=[]
  324.         stridtobattle[strid]=self
  325.        
  326.     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
  327.         #Inclure les modifications de vitesse avant de les passer à confront
  328.         #INSTANCE 1 = ALLY ; INSTANCE 2 = ENEMY
  329.         if Instance1['%hp']>0 and Instance2['%hp']>0:
  330.             if fastestInstance is Instance1:
  331.                 #si Instance1 est plus rapide
  332.                 Instance2['%hp']+=-self.damagedictallyenemy[ Instance1['name'] ][ Instance2['name'] ][1]
  333.                 #items appliqués en combat
  334.                 if 'contact' in moves[self.damagedictallyenemy[ Instance1['name'] ][ Instance2['name'] ][0]]['flags']:
  335.                     if Instance2['set']['item']=='Rocky Helmet':
  336.                         Instance1['%hp']+=-16.67
  337.                     if Instance2['set']['ability']=='Iron Barbs' or Instance2['set']['ability']=='Rough Skin':
  338.                         Instance1['%hp']+=-12.5
  339.                    
  340.             else:
  341.                 #si Instance2 est plus rapide
  342.                 Instance1['%hp']+=-self.damagedictenemyally[ Instance2['name'] ][ Instance1['name'] ][1]
  343.                 #items appliqués en combat
  344.                 if 'contact' in moves[self.damagedictenemyally[ Instance2['name'] ][ Instance1['name']][0]]['flags']:
  345.                     if Instance1['set']['item']=='Rocky Helmet':
  346.                         Instance2['%hp']+=-16.67
  347.                     if Instance1['set']['ability']=='Iron Barbs' or Instance1['set']['ability']=='Rough Skin':
  348.                         Instance2['%hp']+=-12.5
  349.                    
  350.         if Instance1['%hp']>0 and Instance2['%hp']>0:
  351.             #si y'a pas eu de mort
  352.             if fastestInstance is Instance1:
  353.                 #si Instance 1 est plus rapide c'est à son tour de prendre les dégats
  354.                 Instance1['%hp']+=-self.damagedictenemyally[ Instance2['name'] ][ Instance1['name'] ][1]
  355.             else:
  356.                 #si Instance 2 est plus rapide il prend les dégats
  357.                 Instance2['%hp']+=-self.damagedictallyenemy[ Instance1['name'] ][ Instance2['name'] ][1]
  358.        
  359.         #applications items et/ou statuts/climats
  360.             #items
  361.         for loop_Instance in [Instance1,Instance2]:
  362.             if loop_Instance['%hp']>0:
  363.                 if loop_Instance['set']['item']=='Leftovers':
  364.                     loop_Instance['%hp']+=6.25
  365.                 if loop_Instance['set']['item']=='Black Sludge':
  366.                     if 'Poison' in loop_Instance['types']:
  367.                         loop_Instance['%hp']+=6.25
  368.                     else:
  369.                         loop_Instance['%hp']+=-12.5
  370.             #statuts
  371.                 if loop_Instance['status']=='tox':
  372.                     loop_Instance['%hp']+=-(lenght+1)*6.25
  373.                 if loop_Instance['status']=='psn' or loop_Instance['status']=='brn':
  374.                     loop_Instance['%hp']+=-12.5
  375.             #climats
  376.                 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']):
  377.                     loop_Instance['%hp']+=-6.25
  378.                 if self.weather=='Hail' and lenght<self.weatherresettimer and (not 'Ice' in loop_Instance['types']):
  379.                     loop_Instance['%hp']+=-6.25
  380.        
  381.         #Si y'a pas eu de mort, refaire avec lenght+1      
  382.         if Instance1['%hp']>0 and Instance2['%hp']>0 and lenght<40:
  383.             return self.confront(Instance1,Instance2,fastestInstance,lenght+1)
  384.         else:
  385.             return [max(0,Instance1['%hp']),max(0,Instance2['%hp'])]
  386. #            if Instance1['%hp']>0:
  387. #                return [Instance1['%hp'],0]
  388. #            else: #Instance1 mort ne veut pas dire Instance2 en vie. On évite de renvoyer des hps négatifs.
  389. #                return [0,max(0,Instance2['%hp'])]
  390.                    
  391.     def SituationRate(self):
  392.         SituationRatingLocal=0
  393.              
  394.         for ally in self.allies:
  395.             for enemy in self.enemies:
  396.                 allyoffensivemoves=[offensive_move for offensive_move in ally['set']['moves'] if moves[offensive_move]['category']!="Status"]
  397.                 enemyoffensivemoves=[offensive_move for offensive_move in enemy['set']['moves'] if moves[offensive_move]['category']!="Status"]
  398.                
  399.                 bestoffensivemove1to2='nomove'
  400.                 bestdamages1to2=[0]*2
  401.                
  402.                 for offensive_move in allyoffensivemoves:
  403.                     temp_damages_confront=damagecalc(ally,enemy,offensive_move,self,'fast')
  404.                     if temp_damages_confront[1]>bestdamages1to2[1]:
  405.                         bestdamages1to2=temp_damages_confront
  406.                         bestoffensivemove1to2=offensive_move
  407.                        
  408.                 bestoffensivemove2to1='nomove'
  409.                 bestdamages2to1=[0]*2
  410.                
  411.                 for offensive_move in enemyoffensivemoves:
  412.                     temp_damages_confront=damagecalc(enemy,ally,offensive_move,self,'fast')
  413.                     if temp_damages_confront[1]>bestdamages2to1[1]:
  414.                         bestdamages2to1=temp_damages_confront
  415.                         bestoffensivemove2to1=offensive_move
  416.                        
  417.                 averagedamages1to2=(bestdamages1to2[0]+bestdamages1to2[1])/2.
  418.                 averagedamages2to1=(bestdamages2to1[0]+bestdamages2to1[1])/2.
  419.                
  420.                 self.damagedictallyenemy[ally['name']][enemy['name']]=[bestoffensivemove1to2,averagedamages1to2/enemy['set']['stats']['hp']*100.]
  421.                 self.damagedictenemyally[enemy['name']][ally['name']]=[bestoffensivemove2to1,averagedamages2to1/ally['set']['stats']['hp']*100.] #bien des float car average float
  422.                
  423.                 allycopy=deepcopy(ally)
  424.                 enemycopy=deepcopy(enemy)
  425.                
  426.                 #todo : apply speed changes
  427.                 if allycopy['set']['item']=='Choice Scarf':
  428.                     allycopy['set']['stats']['spe']=int(allycopy['set']['stats']['spe']*1.5)
  429.                 if enemycopy['set']['item']=='Choice Scarf':
  430.                     enemycopy['set']['stats']['spe']=int(enemycopy['set']['stats']['spe']*1.5)    
  431.                 if allycopy['status']=='par':
  432.                     allycopy['set']['stats']['spe']=allycopy['set']['stats']['spe']/4
  433.                 if enemycopy['status']=='par':
  434.                     enemycopy['set']['stats']['spe']=enemycopy['set']['stats']['spe']/4
  435.                
  436.                 #decide fastest one                
  437.                 if allycopy['set']['stats']['spe']>enemycopy['set']['stats']['spe']:
  438.                     fastestInstance=allycopy
  439.                 else:
  440.                     fastestInstance=enemycopy
  441.                    
  442.                 confront_result=self.confront(allycopy,enemycopy,fastestInstance,0)
  443.                
  444.                 SituationRatingLocal+=confront_result[0]-confront_result[1]
  445.                
  446.         return SituationRatingLocal
  447.  
  448.  
  449.     def RequestAnswer(self,faint=False):
  450.         print "RequestAnswerReact"
  451.         if self.reactedto==False:
  452.             print "Reactedto check passed"
  453.             if 'rqid' in self.reqdata:
  454.                 print "rqid in reqdata"
  455.                 SituationRating=self.SituationRate()
  456.                
  457.                 BestChoice=''
  458.                 BestChoiceRating=-9999
  459.                 if not 'forceSwitch' in self.reqdata:
  460.                     print "MOVELOCK TEST :"+str([ move for move in self.activeAlly['set']['moves'] ])+"MOVELOCK ="+self.activeAlly['movelock']
  461.                    
  462.                     #include speed modifications here in a speed integer
  463.                     ModifiedSpeedValueAlly=self.activeAlly['set']['stats']['spe']
  464.                     #dostuffhere
  465.                     ModifiedSpeedValueEnemy=self.activeEnemy['set']['stats']['spe']
  466.                     #dostuffhere
  467.                     if ModifiedSpeedValueAlly<ModifiedSpeedValueEnemy:
  468.                         FirstToPlayWithoutPrio='ally'
  469.                     else:
  470.                         FirstToPlayWithoutPrio='enemy'
  471.                        
  472.                     for move in [movenotlock for movenotlock in self.activeAlly['set']['moves'] if (self.activeAlly['movelock'] in ['',movenotlock])]:
  473.                        
  474.                         LittleThief=deepcopy(self)
  475.                        
  476.                         if moves[move]['priority']>moves[   self.damagedictenemyally[self.activeEnemy['name']][self.activeAlly['name']][0]    ]['priority']:
  477.                             FirstToPlay='ally'
  478.                         elif moves[move]['priority']<moves[    self.damagedictenemyally[self.activeEnemy['name']][self.activeAlly['name']][0]    ]['priority']:
  479.                             FirstToPlay='enemy'
  480.                         else:
  481.                             FirstToPlay=FirstToPlayWithoutPrio
  482.                        
  483.                         if FirstToPlay=='ally':
  484.                             print
  485.                             print 'path : RequestAnswer -> FirstToPlay = ally'
  486.                             print
  487.                                                                                    
  488.                             if moves[move]['basePower'] != 0:
  489.                                 abstract_damages=damagecalc(self.activeAlly,self.activeEnemy,move,self,mode='fast')
  490.                                 print move+" : "+str(-(abstract_damages[0]+abstract_damages[1])/2. *100. / LittleThief.activeEnemy['set']['stats']['hp'])
  491.                                 LittleThief.activeEnemy['%hp']+=- min(abstract_damages[0]+abstract_damages[1]/2. *100. / LittleThief.activeEnemy['set']['stats']['hp'], LittleThief.activeEnemy['%hp'])                            
  492.                            
  493.                             if not self.activeEnemy['status']:
  494.                                 if move=='toxic' and not 'Poison' in self.activeEnemy['types'] and not 'Steel' in self.activeEnemy['types']:
  495.                                     LittleThief.activeEnemy['status']='tox'
  496.                                 elif move=='willowisp' and not 'Fire' in self.activeEnemy['types']:
  497.                                     LittleThief.activeEnemy['status']='brn'
  498.                                 elif move=='thunderwave' and not 'Electric' in self.activeEnemy['types'] and not 'Ground' in self.activeEnemy['types']:
  499.                                     LittleThief.activeEnemy['status']='par'
  500.                                 elif move=='thunderwave' and not 'Electric' in self.activeEnemy['types']:
  501.                                     LittleThief.activeEnemy['status']='par'
  502.                                 elif move=='poisonpowder' and not 'Poison' in self.activeEnemy['types'] and not 'Steel' in self.activeEnemy['types']:
  503.                                     LittleThief.activeEnemy['status']='psn'
  504.                                                    
  505.                             if LittleThief.activeEnemy['%hp']!=0:
  506.                                 LittleThief.activeAlly['%hp']+=- min(LittleThief.activeAlly['%hp'],self.damagedictenemyally[self.activeEnemy['name']][self.activeAlly['name']][1])
  507.                        
  508.                         #si c'est l'ennemi qui joue en premier
  509.                         else:
  510.                             print 'path : RequestAnswer -> FirstToPlay = enemy'
  511.                            
  512.                             LittleThief.activeAlly['%hp']+=- min(LittleThief.activeAlly['%hp'],self.damagedictenemyally[self.activeEnemy['name']][self.activeAlly['name']][1])
  513.                            
  514.                             if LittleThief.activeAlly['%hp']!=0:
  515.                                 if moves[move]['basePower'] != 0:
  516.                                     abstract_damages=damagecalc(self.activeAlly,self.activeEnemy,move,self,mode='fast')
  517.                                     LittleThief.activeEnemy['%hp']+=- min( (abstract_damages[0]+abstract_damages[1])/2. *100. / LittleThief.activeEnemy['set']['stats']['hp'] , LittleThief.activeEnemy['%hp'] )                        
  518.                            
  519.                                 if not self.activeEnemy['status']:
  520.                                     if move=='toxic' and not 'Poison' in self.activeEnemy['types'] and not 'Steel' in self.activeEnemy['types']:
  521.                                         LittleThief.activeEnemy['status']='tox'
  522.                                     elif move=='willowisp' and not 'Fire' in self.activeEnemy['types']:
  523.                                         LittleThief.activeEnemy['status']='brn'
  524.                                     elif move=='thunderwave' and not 'Electric' in self.activeEnemy['types'] and not 'Ground' in self.activeEnemy['types']:
  525.                                         LittleThief.activeEnemy['status']='par'
  526.                                     elif move=='thunderwave' and not 'Electric' in self.activeEnemy['types']:
  527.                                         LittleThief.activeEnemy['status']='par'
  528.                                     elif move=='poisonpowder' and not 'Poison' in self.activeEnemy['types'] and not 'Steel' in self.activeEnemy['types']:
  529.                                         LittleThief.activeEnemy['status']='psn'
  530.                        
  531.                         AbstractSituationRating=LittleThief.SituationRate()
  532.                         SituationRatingDifference=AbstractSituationRating-SituationRating
  533.                         print move," Situation Rating :",SituationRatingDifference
  534.                         if SituationRatingDifference>BestChoiceRating:
  535.                             BestChoiceRating=SituationRatingDifference
  536.                             BestChoice=move
  537.                        
  538.                 activeAllyBeforeSwitchName=self.activeAlly['name']  
  539.                      
  540.                 for allies_index in range(len(self.allies)):
  541.                     if self.allies[allies_index]['teamposition']!=1 and self.allies[allies_index]['%hp']!=0:
  542.                         print "# WAS TESTED :"+self.allies[allies_index]['name']
  543.                        
  544.                         LittleThief=deepcopy(self)
  545. #                        LittleThief.allies=[copy(ally) for ally in self.allies]
  546. #                        LittleThief.enemies=[copy(enemy) for enemy in self.enemies]
  547.                            
  548. #                        LittleThief.activeEnemy=LittleThief.enemies[ self.activeEnemy['listposition'] ]
  549.                        
  550.                         LittleThief.activeAlly=LittleThief.allies[allies_index]
  551.                         abstract_damages=damagecalc(LittleThief.activeEnemy,LittleThief.activeAlly,LittleThief.damagedictenemyally[ LittleThief.activeEnemy['name'] ][ activeAllyBeforeSwitchName ][0],self,mode='fast')
  552.                        
  553.                         LittleThief.activeAlly['%hp']+= - min( (abstract_damages[1]+abstract_damages[0])/2. , LittleThief.activeAlly['%hp'] )
  554.                        
  555.                         AbstractSituationRating=LittleThief.SituationRate()
  556.                         print
  557.                         print LittleThief.allies[allies_index]['name']+' : '+str(AbstractSituationRating)+' , '+str(SituationRating)  
  558.                         print                      
  559.                         log.write("#####"+LittleThief.allies[allies_index]['name']+' : '+str(AbstractSituationRating)+' , '+str(SituationRating)  )
  560.                         SituationRatingDifference=AbstractSituationRating-SituationRating+6*(LittleThief.damagedictallyenemy[ LittleThief.activeAlly['name'] ][ LittleThief.activeEnemy['name'] ][1] - LittleThief.damagedictenemyally[ LittleThief.activeEnemy['name'] ][ LittleThief.activeAlly['name'] ][1] )
  561.                        
  562.                         print self.allies[allies_index]['name'],SituationRatingDifference
  563.                         if SituationRatingDifference>BestChoiceRating:
  564.                             BestChoiceRating=SituationRatingDifference
  565.                             BestChoice=allies_index
  566.                    
  567. #                for i in self.damagedictallyenemy:
  568. #                    print i,self.damagedictallyenemy[i]
  569. #                print
  570. #                for i in self.damagedictenemyally:
  571. #                    print i,self.damagedictenemyally[i]
  572.  
  573.                 for i in self.allies + self.enemies:
  574.                     i.state()
  575.                                        
  576.                 if type(BestChoice) == int:
  577.                     print "SENT :"+self.strid[1:]+'|/switch '+str(self.allies[BestChoice]['teamposition'])+'|'+str(self.reqdata['rqid'])
  578.                     log.write("#-#"+"SENT :"+self.strid[1:]+'|/switch '+str(self.allies[BestChoice]['teamposition'])+'|'+str(self.reqdata['rqid']))
  579.                     ws.send( self.strid[1:]+'|/switch '+str(self.allies[BestChoice]['teamposition'])+'|'+str(self.reqdata['rqid']) )
  580.                
  581.                 else:
  582.                     print "SENT :"+self.strid[1:]+'|/choose move '+str(BestChoice)+'|'+str(self.reqdata['rqid'])
  583.                     log.write("#_#"+"SENT :"+self.strid[1:]+'|/choose move '+str(BestChoice)+'|'+str(self.reqdata['rqid']))
  584.                     ws.send( self.strid[1:]+'|/choose move '+str(BestChoice)+'|'+str(self.reqdata['rqid']) )
  585.                    
  586.                 self.reactedto=True
  587.                
  588.         else:
  589.             print "FAIL."
  590.                    
  591.     def react(self,message,last=False):
  592.         bparsed=message.split('|')
  593.         if len(bparsed)>1:
  594.             if bparsed[1]=='win':
  595.                 ws.send(self.strid[1:]+'|/leave')
  596.                 stridtobattle.pop(self.strid)
  597.                
  598.             if bparsed[1]=='player' and len(bparsed)>2:
  599.                 print 'testplayer'
  600.                 if bparsed[3]=='Cube On':
  601.                     self.player=bparsed[2]
  602.                 else:
  603.                     if bparsed[2]=='p1':
  604.                         self.player='p2'
  605.                     else:
  606.                         self.player='p1'
  607.                        
  608.             if bparsed[1]=='poke':
  609.                 print 'testpoke'
  610.                 if bparsed[2]!=self.player:
  611.                     vparsed=bparsed[3].split(',')
  612.                     if len(vparsed)==2:
  613.                         self.enemies.append(EnemyInstance(lowerandkill(vparsed[0],['-',' ',"'"]), vparsed[1][1]) )
  614.                     else:
  615.                         self.enemies.append(EnemyInstance(lowerandkill(vparsed[0],['-',' ',"'"])) )
  616.                     self.damagedictenemyally[lowerandkill(vparsed[0],['-',' ',"'"])]={}
  617.                    
  618.                     self.enemies[-1]['listposition']=len(self.enemies)-1
  619.                    
  620.             if bparsed[1]=='request':
  621.                 self.reqdata=json.loads(bparsed[2])
  622.                 self.reactedto=False
  623.                 if 'rqid' in self.reqdata and self.reqdata['rqid']==1:
  624.                     ws.send(self.strid[1:]+'|/team 1|1')
  625.            
  626.             if bparsed[1]=='switch':
  627.                 print 'testswitch'
  628.                 if bparsed[2][:2]==self.player:
  629.                     self.activeAlly['movelock']=''
  630.                     activeAllystr=lowerandkill( bparsed[3].split(',')[0] , [' ','-'] )
  631.                     print "~"+activeAllystr
  632.                     for ally in self.allies:
  633.                         print ally['name']
  634.                         if ally['name']==activeAllystr:
  635.                             self.activeAlly['teamposition']=ally['teamposition']
  636.                             self.activeAlly=ally
  637.                             self.activeAlly['teamposition']=1
  638.                 else:
  639.                     if self.activeEnemy!='':                                #car au début c'en est un
  640.                         self.activeEnemy['movelock']=''
  641.                     activeEnemystr=lowerandkill( bparsed[3].split(',')[0] , [' ','-'] )
  642.                     print '#'+activeEnemystr
  643.                     for enemy in self.enemies:
  644.                         print enemy['name']
  645.                         if enemy['name']==activeEnemystr:
  646.                             self.activeEnemy=enemy
  647.            
  648.             if bparsed[1]=='turn':
  649.                 self.RequestAnswer()
  650.            
  651.             if bparsed[1]=='faint' and bparsed[2][:2]==self.player:
  652.                 self.RequestAnswer(True)
  653.             #ZONE APPRENTISSAGE + c'est normal qu'il y ait 2 if == move
  654.            
  655.             if bparsed[1]=='move':
  656.                 self.studiedmove=bparsed[2:] #studiedmove est alors une liste
  657.                 if bparsed[2][:2]==self.player:
  658.                     if bparsed[3] in ['U-turn','Volt Switch','Parting Shot']:
  659.                         self.pivotmove=True
  660.                     elif self.activeAlly['set']['item'] in ['Choice Scarf','Choice Band','Choice Specs']:
  661.                         self.activeAlly['movelock']=lowerandkill(bparsed[3],[' ','-',"'"])
  662.                         #[ERROR] FAUDRA INCLURE ICI UN TRUC SPECIAL POUR LES HIDDEN POWER
  663.                 else:
  664.                     if self.activeEnemy['set']['item'] in ['Choice Scarf','Choice Band','Choice Specs']:
  665.                         self.activeEnemy['movelock']=lowerandkill(bparsed[3],[' ','-',"'"])
  666.                                  
  667.             if bparsed[1] and bparsed[1][0]=='-':
  668.                 ##ZONE DE RECEPTION D'INFORMATION
  669.                 if bparsed[1][1:]=='damage':
  670.                     if bparsed[2][:2]==self.player:
  671.                         if bparsed[3][-3:]=='fnt':
  672.                             self.activeAlly['%hp']=0
  673.                         else:
  674.                             self.activeAlly['%hp']=float(bparsed[3].split('/')[0])/float(    bparsed[3].split('/')[1].split(' ')[0]      )*100
  675.                     else:    
  676.                         self.activeEnemy['%hp']=int(   bparsed[3].split('/')[0].split(' ')[0]   )
  677.                         self.activeEnemy['hp']=int(self.activeEnemy['%hp']/100.*self.activeEnemy['set']['stats']['hp'])
  678.                
  679.                 elif bparsed[1] and bparsed[1][1:]=='status':
  680.                     if bparsed[2][:2]==self.player:
  681.                         self.activeAlly['status']=bparsed[3]
  682.                     else:
  683.                         self.activeEnemy['status']=bparsed[3]
  684.                        
  685.                        
  686.            
  687.             #DOIT ETRE A LA FIN !! Pour assurer que le bot apprenne ce qui se passe à la dernière ligne du U-turn
  688.             if last:
  689.                 self.studiedmove=[]
  690.                 if self.pivotmove:
  691.                     self.RequestAnswer()
  692.                     self.pivotmove=False
  693.            
  694. team=[AllyInstance('gengar',{'ability': 'Levitate',
  695.  'evstats': {'atk': 0, 'def': 0, 'hp': 4, 'spa': 252, 'spd': 0, 'spe': 252},
  696.  'item': 'Black Sludge',
  697.  'level': 100,
  698.  'moves': ['hex', 'sludgebomb', 'willowisp', 'substitute'],
  699.  'movesalts': [],
  700.  'name': 'gengar',
  701.  'nature': 'Timid',
  702.  'stats': {'atk': 121.0,
  703.   'def': 156.0,
  704.   'hp': 262.0,
  705.   'spa': 359.0,
  706.   'spd': 186.0,
  707.   'spe': 350.0}},1),
  708.  AllyInstance('garchomp',{'ability': 'Rough Skin',
  709.  'evstats': {'atk': 0, 'def': 216, 'hp': 232, 'spa': 0, 'spd': 60, 'spe': 0},
  710.  'item': 'Rocky Helmet',
  711.  'level': 100,
  712.  'moves': ['earthquake', 'dragontail', 'toxic', 'stealthrock'],
  713.  'movesalts': [],
  714.  'name': 'garchomp',
  715.  'nature': 'Impish',
  716.  'stats': {'atk': 296.0,
  717.   'def': 308.0,
  718.   'hp': 415.0,
  719.   'spa': 176.0,
  720.   'spd': 221.0,
  721.   'spe': 240.0}},2),
  722. AllyInstance('gliscor',{'ability': 'Poison Heal',
  723.  'evstats': {'atk': 0, 'def': 0, 'hp': 252, 'spa': 0, 'spd': 176, 'spe': 80},
  724.  'item': 'Toxic Orb',
  725.  'level': 100,
  726.  'moves': ['earthquake', 'knockoff', 'swordsdance', 'roost'],
  727.  'movesalts': [],
  728.  'name': 'gliscor',
  729.  'nature': 'Jolly',
  730.  'stats': {'atk': 226.0,
  731.   'def': 286.0,
  732.   'hp': 354.0,
  733.   'spa': 113.0,
  734.   'spd': 230.0,
  735.   'spe': 270.0}},3),
  736. AllyInstance('venusaur',{'ability': 'Chlorophyll',
  737.  'evstats': {'atk': 0, 'def': 0, 'hp': 200, 'spa': 168, 'spd': 0, 'spe': 140},
  738.  'item': 'Venusaurite',
  739.  'level': 100,
  740.  'moves': ['gigadrain', 'sludgebomb', 'hiddenpowerfire', 'synthesis'],
  741.  'movesalts': [],
  742.  'name': 'venusaur',
  743.  'nature': 'Modest',
  744.  'stats': {'atk': 152.0,
  745.   'def': 202.0,
  746.   'hp': 351.0,
  747.   'spa': 304.0,
  748.   'spd': 236.0,
  749.   'spe': 230.0}},4),
  750. AllyInstance('keldeo',{'ability': 'Justified',
  751.  'evstats': {'atk': 0, 'def': 0, 'hp': 0, 'spa': 252, 'spd': 4, 'spe': 252},
  752.  'item': 'Choice Scarf',
  753.  'level': 100,
  754.  'moves': ['hydropump', 'secretsword', 'icywind', 'scald'],
  755.  'movesalts': [],
  756.  'name': 'keldeo',
  757.  'nature': 'Timid',
  758.  'stats': {'atk': 134.0,
  759.   'def': 216.0,
  760.   'hp': 323.0,
  761.   'spa': 357.0,
  762.   'spd': 217.0,
  763.   'spe': 346.0}},5),
  764. AllyInstance('heatran',{'ability': 'Flash Fire',
  765.  'evstats': {'atk': 0, 'def': 0, 'hp': 252, 'spa': 0, 'spd': 216, 'spe': 40},
  766.  'item': 'Leftovers',
  767.  'level': 100,
  768.  'moves': ['lavaplume', 'earthpower', 'toxic', 'protect'],
  769.  'movesalts': [],
  770.  'name': 'heatran',
  771.  'nature': 'Calm',
  772.  'stats': {'atk': 166.0,
  773.   'def': 248.0,
  774.   'hp': 386.0,
  775.   'spa': 296.0,
  776.   'spd': 332.0,
  777.   'spe': 200.0}},6)]
  778.  
  779.  
  780. bot = True
  781.  
  782. if bot:
  783.     name="Cube On"
  784.     password=
  785.     room="lobby"
  786.     ws=websocket.create_connection("ws://sim.smogon.com:8000/showdown/websocket")
  787. #    ws=websocket.create_connection("ws://pokestrat.com:8000/showdown/websocket")
  788.     ws.recv(),ws.recv()
  789. #    ws.recv()
  790.     txt=ws.recv()
  791.     Ptool=[i for i in range(len(txt)) if txt[i]=='|']
  792.     data = urllib.urlencode({'act': 'login', 'name': name, 'pass' : password, 'challengekeyid': txt[Ptool[1]+1], 'challenge':txt[Ptool[2]+1:]})
  793.     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)' })
  794.     response = urllib2.urlopen(req)
  795.     result = response.read()
  796.     Ptool2=[i for i in range(len(result)) if result[i]=='"']
  797.     assertion=result[Ptool2[-2]+1:Ptool2[-1]]
  798.     ws.send("|/trn %s,0,%s" % (name, assertion) )
  799.     time.sleep(2)
  800. #    ws.send("|/join "+room)
  801.     ws.send(room+"|/avatar 267")
  802.    
  803. def parse(text,character,stopat=0):
  804.     if stopat:
  805.         p=[-1]+[i for i in range(len(text)) if text[i]==character][:(stopat-1)]+[len(text)]
  806.     else:
  807.         p=[-1]+[i for i in range(len(text)) if text[i]==character]+[len(text)]
  808.     l=[]
  809.     for i in range(len(p)-1):
  810.         l+=[ text[ p[i]+1:p[i+1] ] ]
  811.     return l
  812.  
  813.  
  814. class ThreadReception(threading.Thread):
  815.     def ___init___(self):
  816.         threading.Thread.__init__(self)
  817.     def run(self):
  818.         condition=True
  819.         while condition:
  820.             message=ws.recv()
  821.             print
  822.             print message
  823.             log.write(message+'\n')
  824.             analysis(message)
  825.         ws.close()
  826.  
  827. def analysis(message):
  828.     nparsed=parse(message,"\n")
  829.     if len(nparsed)<40:                                                        #vérif nécessaire car le log quand on rejoind une room fait >>30 lignes
  830.         if nparsed[0][:8]==">battle-":
  831.             for lineindex in range(1,len(nparsed)):                                           #si c'est un message de match alors
  832.                 if nparsed[lineindex]=="|init|battle":
  833.                     print 'testinit'                                            #si c'est un message d'init
  834.                     Battle(team,nparsed[0])                                        #ajouter le strid à la liste des matchs en cours  /!/ NE PAS SPECTATE UN AUTRE MATCH !
  835.                     ws.send(nparsed[0][1:]+"|/timer on")
  836.                 else:
  837.                     if nparsed[0] in stridtobattle:
  838.                         if lineindex==len(nparsed):
  839.                             stridtobattle[nparsed[0]].react(nparsed[lineindex],True)
  840.                         else:
  841.                             stridtobattle[nparsed[0]].react(nparsed[lineindex])
  842.                            
  843.     for i in nparsed:
  844.         parsed=parse(i,"|")
  845.         if len(parsed)>1:
  846.             if parsed[1]=="updatechallenges":
  847.                 dicochall=json.loads(parsed[2])
  848.                 for i in dicochall["challengesFrom"]:
  849.                     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,,,,|||""")
  850.                     ws.send("|/accept "+i)
  851.             if parsed[1]=='pm' and parsed[2]==' Artemis Fowl':
  852.                 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,,,,|||""")
  853.                 ws.send("|/search ounomega")
  854.  
  855.  
  856. if bot:
  857.     print 'Connecté'
  858.     th=ThreadReception()
  859.     time.sleep(4)
  860.     th.start()
  861.    
  862. def end():
  863.     ws.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement