Fred (pokemon lab bot) source
Would you like to react to this message? Create an account in a few clicks or log in to continue.


Full source of "Fred". To run these files, you must have python 2.7. Copy the source to notepad/python and save as ~(you can't change the name without changing the source).py. But please, we don't need 5 bots.
 
HomeLatest imagesSearchRegisterLog in

 

 -Pyfred.py-

Go down 
AuthorMessage
Admin
Admin



Posts : 22
Join date : 2011-09-21

-Pyfred.py- Empty
PostSubject: -Pyfred.py-   -Pyfred.py- EmptyWed Sep 21, 2011 6:06 pm

-C-h-a-n-g-e-s----------------------------------
--(Code by Cathy [who made pokemon lab]) 9/21/11
Action: source was pulled from http://trac.poke-lab.com/browser/shoddybot
--(Edit by Yuser10 [User on pokemon lab])
Action: line 21: changed teams to set to a variable to allow team shuffling
line 13: This shuffles the list of teams so teamname[0] changes.
-In def start_turn: added and changed messages the bot says in-battle, asks vileman not to crash it, tells umby to smash it (as in baton pass +6+6+6+6 to a basic pokemon and sweep it.)
-In def handle_victory: changed gui msgs and added badge winner announcement(which now that i think of it won't work, will change later)
---------------------------------------------------

-S-o-u-r-c-e-------------------------------------

Code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import random
import time
import os.path


from bot import *
import parsers
from pokemon import Pokemon

teamname = ["bot team.sbt", "3bot team.sbt", "8bot team.sbt"]
random.shuffle(teamname)
#HOST = 'smogon.com'
HOST = 'lab.pokemonexperte.de'
PORT = 8446
USERNAME = '----YuSeRboT----'
PASSWORD = 'mypassword'
TEAM_DIR = "D:\folder\subfolder/"
TEAMS = teamname[0]
nawl = 0
# An awesome, super human robot capable of beating any challenger
class PyFred(MessageHandler):
   
    def __init__(self):
        self.battles = dict()
        self.challenges = dict()
        random.seed()
   
    def handle_welcome_message(self, version, name, message):
        #print name
        #print message
        pass
   
    def handle_metagame_list(self, metagames):
        self.metagames = metagames
       
    def handle_registry_response(self, type, details):
        if type == 7:
            print "Successfully authenticated"
            self.join_channel("main")
        else:
            print "Authentication failed, code ", type
            if details: print details
           
    def handle_incoming_challenge(self, user, generation, n, team_length):
        #too lazy to handle n > 1 or non 6 challenges
        if n > 1 or team_length != 6:
            self.reject_challenge(user)
        else:
            random.shuffle(teamname)
            TEAMS = teamname
            print "Started battle against ", user, "with team", teamname[0]
            file = TEAM_DIR + TEAMS[random.randint(0, len(TEAMS) - 1)]
            file = os.path.normpath(file)
            team = parsers.parse_team_file(file)
            self.challenges[user] = file
            self.accept_challenge(user, team)
   
    def handle_battle_begin(self, fid, user, party):
        b = Battle(fid, self, party, user, self.challenges[user])
        self.battles[fid] = b
        del self.challenges[user]
   
    def handle_battle_use_move(self, fid, party, slot, name, id):
        self.battles[fid].handle_use_move(party, id)
       
    def handle_battle_send_out(self, fid, party, slot, index, name, id, gender, level):
        self.battles[fid].handle_send_out(party, index, id, gender, level)
       
    def handle_battle_health_change(self, fid, party, slot, delta, total, denominator):
        self.battles[fid].handle_health_change(party, delta, total, denominator)
       
    def handle_battle_fainted(self, fid, party, slot, name):
        self.battles[fid].handle_fainted(party)
       
    def handle_battle_print(self, fid, cat, id, args):
        self.battles[fid].print_message(cat, id, args)
       
    def handle_request_action(self, fid, slot, pos, replace, switches, can_switch, forced, moves):
        self.battles[fid].request_action(slot, pos, replace, switches, can_switch, forced, moves)
       
    def handle_battle_begin_turn(self, fid, turn):
        self.battles[fid].start_turn(turn)

       
    def handle_battle_victory(self, fid, party):
        battle = self.battles[fid]
        winner = (battle.party == party)
        battle.handle_victory(winner)
        del self.battles[fid]

    def handle_battle_set_move(self, fid, index, slot, id, pp, max):
        battle = self.battles[fid]
        battle.set_move(index, slot, id, pp, max)
     
##############################################################
class Battle:
    def __init__(self, fid, handler, party, opponent, team):
        self.fid = fid
        self.handler = handler
        self.party = party
        self.opponent = opponent
        self.teams = [[], []]
        self.teams[party] = parsers.parse_team_file(team)
        for i in range(6):
            self.teams[party - 1].append(Pokemon(moves=[]))
        self.active = [0, 0]
       
    # send a message to the users in this battle
    def send_message(self, msg):
        self.handler.send_message(self.fid, msg)
       
    def send_move(self, index, target):
        self.handler.send_move(self.fid, index, target)
       
    def send_switch(self, index):
        self.handler.send_switch(self.fid, index)
   
    def start_turn(self, turn):
        if turn == 1:
            self.send_message ("Good Luck, %s!" % self.opponent)
            self.send_message ("Try to be the 1st one to win the STALLER badges!")
        if turn == 1 and self.opponent == "vileman":
            self.send_message ("Don't crash me, %s!" % self.opponent)
        if turn == 1 and self.opponent == "_ umbreon _" or self.opponent == "-umbreon-" or self.opponent == "_ umbreon _" or self.opponent == "-  umbreon      -" or self.opponent == "_  umbreon  _" or self.opponent == "-  umbreon  -" or self.opponent == "_ umbreon  _" or self.opponent == "-  umbreon-" or self.opponent == "_ umbreon  _" or self.opponent == "- umbreon -":
            self.send_message ("Come smash me bro!")
        if turn == 20:
            self.send_message ("Hmm, what should i do?")
        if turn == 100:
            self.send_message ("*jeopardy song*")
        if turn == 150:
            self.send_message ("Congrats! I present to you... the BASIC STALL badge!")
            print self.opponent + " recieved the BASIC STALL badge."
            nawl = 1
        if turn == 200:
            self.send_message ("Congrats! I present to you... the EPIC STALLER badge!")
            self.send_message ("Now you have no reason to stall this much anymore. You're boring me, and I'm a freaking BOT!")
            print self.opponent + " recieved the EPIC STALL badge!"
            nawl = 1
    def print_message(self, cat, id, args):
        #print cat, id, args
        pass
   
    def handle_use_move(self, party, id):
        if party != self.party:
            p = self.teams[party][self.active[party]]
            move_list = self.handler.client.move_list
            move = None
            for name in move_list:
                if move_list[name]["id"] == id:
                    move = move_list[name]
                    break
            if not move in p.moves:
                p.moves.append(move)
   
    def handle_send_out(self, party, index, id, gender, level):
        self.active[party] = index
        p = self.teams[party][index]
        if p.pokemonspecies is None:
            species_list = self.handler.client.species_list
            if party is self.party:
                p.pokemonspecies = species_list[p.species]
            else:
                species = None
                for key in species_list:
                    if species_list[key]["id"] == id: 
                        species = species_list[key]
                        break
                p.pokemonspecies = species
   
    def handle_health_change(self, party, delta, total, denominator):
        self.teams[party][self.active[party]].health = (total, denominator)
       
    def handle_fainted(self, party):
        self.teams[party][self.active[party]].fainted = True
       
    def handle_victory(self, winner):
        if winner:
            self.send_message("Better Luck Next Time!")
            verb = "Won"
            mooo = "--------WIN--------"
        else:
            self.send_message("Good Game!")
            self.send_message("I present to you... the \"I BEAT A BOT AND I\'M ALMOST PROUD\" badge!")
            self.send_message("*hands over badge*")
            verb = "Lost"
            mooo = "--------LOSE--------"
        self.handler.leave_channel(self.fid)
        print verb, "a battle against", self.opponent
        print mooo
        if nawl == 1:
            print "Badge winner^^^"
   
    def set_move(self, index, slot, id, pp, max):
        move_list = self.handler.client.move_list
        for name, move in move_list.items():
            if move["id"] == id:
                self.teams[party][index].moves[slot] = move
                break               
   
    def get_active(self, us):
        party = self.party if us else self.party - 1
        return self.teams[party][self.active[party]]
           
    def calc_max_threat(self, moves, our_types, their_types):
        max_threat = 0
        for t, power in moves:
            mult = get_effectiveness(t, our_types)
            threat = mult * power
            if t in their_types:
                threat *= 1.5
            max_threat = max(max_threat, threat)
        return max_threat
   
    def get_best_switch(self, available, opponent, comparison=99999):
        min_threat = 9999999
        min_index = -1
        for i in available:
            p = self.teams[self.party][i]
            if p.pokemonspecies is None:
                p.pokemonspecies = self.handler.client.species_list[p.species]
            moves = self.get_move_tuples(opponent)
            threat = self.calc_max_threat(moves, p.pokemonspecies["types"], opponent.pokemonspecies["types"])
            if threat < min_threat:
                min_threat = threat
                min_index = i
        if min_threat < comparison:
            return min_index
        else:
            return -1
   
    def get_move_tuples(self, p):
        moves = []
        for move in p.moves:
            move_type = move["type"]
            if move["class"] != "Other":
                moves.append((move_type, move["power"]))
        for t in p.pokemonspecies["types"]:
            # could be better but guess a 70 power move
            moves.append((t, 70))
        return moves
   
    def get_best_attack(self, attacker, defender, legal_moves):
        max_damage = 0
        max_index = -1
        for i, move in enumerate(attacker.moves):
            if not legal_moves[i]: continue
            move = self.handler.client.move_list[move[0]]
            # stop from using dream eater and focus punch
            if (move["class"] == "Other") or (move["id"] in [144, 105]): continue
            type = move["type"]
            power = move["power"]
            damage = power * get_effectiveness(type, defender.pokemonspecies["types"])
            if type in attacker.pokemonspecies["types"]: damage *= 1.5
            if damage > max_damage:
                max_damage = damage
                max_index = i
        return max_index
           
    def request_action(self, slot, pos, replace, switches, can_switch, forced, legal_moves):
        me = self.get_active(True)
        them = self.get_active(False)
       
        if forced:
            self.send_move(1, 1)
        else:
            available = []
            for i in range(len(switches)):
                if switches[i]:
                    available.append(i)
            if replace:
                #time.sleep(1.5)
                self.send_switch(self.get_best_switch(available, them))
            else:
                moves = []
                for move in them.moves:
                    move_type = move["type"]
                    if move["class"] != "Other":
                        moves.append((move_type, move["power"]))
                for t in them.pokemonspecies["types"]:
                    # could be better but guess a 70 power move
                    moves.append((t, 70))
                max_threat = self.calc_max_threat(moves, me.pokemonspecies["types"], them.pokemonspecies["types"])
                if max_threat > 180: switch = 0.95
                elif max_threat > 150: switch = 0.75
                elif max_threat > 120: switch = 0.4
                elif max_threat > 90: switch = 0.1
                else: switch = 0.05
                rand = random.random()
                best_switch = self.get_best_switch(available, them, max_threat) 
                if can_switch and (rand < switch) and (best_switch >= 0):
                    self.send_switch(best_switch)
                else:
                    best_move = self.get_best_attack(me, them, legal_moves)
                    self.send_move(best_move, 1 - self.party)
   
##############################################################

TYPES = { "Normal" : 0, "Fire" : 1, "Water" : 2, "Electric" : 3, "Grass" : 4, "Ice" : 5, "Fighting" : 6, "Poison" : 7,
    "Ground" : 8, "Flying" : 9, "Psychic" : 10, "Bug" : 11, "Rock" : 12, "Ghost" : 13, "Dragon" : 14, "Dark" : 15,
    "Steel" : 16, "Typeless" : 17 }

EFFECTIVENESS = [  [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.5, 0, 1, 1, 0.5, 1 ],
   [ 1, 0.5, 0.5, 1, 2, 2, 1, 1, 1, 1, 1, 2, 0.5, 1, 0.5, 1, 2, 1 ],
   [ 1, 2, 0.5, 1, 0.5, 1, 1, 1, 2, 1, 1, 1, 2, 1, 0.5, 1, 1, 1 ],
   [ 1, 1, 2, 0.5, 0.5, 1, 1, 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][TYPES[t]]
    return mult

##############################################################
def start_pyfred(host=HOST, port=PORT, username=USERNAME, password=PASSWORD):
    try:
        client = BotClient(HOST, PORT)
    except socket.error:
        print "Failed to connect to host {0} on port {1}".format(host, port)
        exit(1)
    t1 = time.time()
    client.init_species("species.xml")
    t2 = time.time()
    client.init_moves("moves.xml")
    t3 = time.time()
    #print "Loaded species in", (t2-t1)*1000, "milliseconds"
    #print "Loaded moves in", (t3-t2)*1000, "milliseconds"
    client.set_handler(PyFred())
    client.authenticate(username, password)
    client.run()

if __name__ == "__main__":
    start_pyfred()
---------------------------------------------------
Back to top Go down
https://pokelabfred.forumotion.com
 
-Pyfred.py-
Back to top 
Page 1 of 1

Permissions in this forum:You cannot reply to topics in this forum
Fred (pokemon lab bot) source :: Source code-
Jump to: