Example #1
0
 def __init__(self, root, party=None, dimension=10, file_path="", unusual_mode=False):
     self.root = root
     if file_path == "":
         self.log = log_parser.GameLogParser('log.ck')
         self.game = game_logic.PlayingField(dimension, None, unusual_mode)
         self.human = party
         self.dimension = dimension
         self.progress = 1
         self.log.create_struct_log(party, self.dimension, self.progress)
     else:
         self.log = log_parser.GameLogParser(file_path)
         self.log.dimension = int(self.log.get_dimension())
         self.dimension = self.log.dimension
         self.progress = self.log.get_progress() + 1
         self.log.count_write = self.progress + 0
         field_save = self.log.get_field()
         self.game = game_logic.PlayingField(self.dimension, field_save)
         if self.log.get_is_human() == 'none':
             self.human = None
             party = None
         else:
             self.human = self.log.get_is_human()
             party = self.human
     self.first_player = self.game.first_player
     self.second_player = self.game.second_player
     self.root = root
     self.list_button = []
     self.list_save_image = []
     for x in range(0, self.game.dimension):
         new_line = []
         for y in range(0, self.game.dimension):
             new_line.append(AdvancedButton(x, y, self.root))
             img = PhotoImage(file='image/white.gif')
             self.list_save_image.append(img)
             new_line[y]['image'] = img
         self.list_button.append(new_line)
     self.is_with_bot = False
     if party is not None:
         self.is_with_bot = True
         if party == 'first':
             self.bot = bot.Bot(self.second_player)
         else:
             self.bot = bot.Bot(self.first_player)
             if self.progress % 2 != 0:
                 self.progress += self.bot_do()
                 self.log.change_fild_text(self.dimension, self.game.field)
     self.draw()
     for x in range(0, self.game.dimension):
         for y in range(0, self.game.dimension):
             self.list_button[x][y].grid(row=x, column=y)
     menu_bar = Menu(self.root)
     menu_bar.add_command(label="Save", command=self.save_game)
     self.root.config(menu=menu_bar)
     self.root.mainloop()
    def test_connect_bots(self):
        o0 = bot.Output()
        o1 = bot.Output()
        o2 = bot.Output()
        b0 = bot.Bot("b0", o0, o2)
        b1 = bot.Bot("b1", b0, o1)
        b2 = bot.Bot("b2", b0, b1)
        b2.giveValue(5)
        b1.giveValue(3)
        b2.giveValue(2)

        self.assertEquals([5, 2], b2.compared)
Example #3
0
    def __init__(self, login=None, password=None, vk=None):
        if vk:
            self.vk = vk
            self.bot = bot.Bot(vk)
            self.vk.auth()
        elif login and password:
            self.vk = vk_api.VkApi(login=login, password=password)
            self.bot = bot.Bot(self.vk)
            self.vk.auth()
        else:
            print('something wrong', login, password, vk)
            raise Exception

        self.accounts = load_accounts('accounts.txt')
Example #4
0
 def __init__(self, config):
      
     
     self._id = 0
     self._bot = bot.Bot(None,config, testing=True)
      
     threading.Thread(target=self._bot.start).start()
Example #5
0
 def test_postMessage(self):
     """Does the bot post messages to the group?"""  #GIVEN the appropriate environment variables are configured
     testBot = bot.Bot(os.environ['bot_id'], os.environ['token'],
                       os.environ['group_ID'])
     status = testBot.postMessage('Zygium')  #WHEN the bot posts a message
     self.assertTrue(
         status == 202)  # a status code of 202 should be returned
Example #6
0
 def connectionMade(self):
     global team
     msg = m.JoinGame(id=self.id, preferred_team=team, type='player')
     self.bot = b.Bot(id=self.id,
                      teamPref=team,
                      callback=self.pass_to_server)
     self.pass_to_server(msg)
Example #7
0
 def setUp(self):
     self.bot = botcode.Bot(nick_source='test_nicks.csv', wait_time=.1)
     botcode.NewComer('Harry', self.bot)
     botcode.NewComer('Hermione', self.bot)
     time.sleep(.15)
     botcode.NewComer('Ron', self.bot)
     self.ircsock = fake_irc_start()
Example #8
0
def main(args):
    # Add SWARMING_HEADLESS into environ so subcommands know that they are running
    # in a headless (non-interactive) mode.
    os.environ['SWARMING_HEADLESS'] = '1'

    # TODO(maruel): Get rid of all flags and support no option at all.
    # https://code.google.com/p/swarming/issues/detail?id=111
    parser = optparse.OptionParser(usage='%prog [options]',
                                   description=sys.modules[__name__].__doc__)
    # TODO(maruel): Always True.
    parser.add_option('-v',
                      '--verbose',
                      action='count',
                      default=0,
                      help='Set logging level to INFO, twice for DEBUG.')

    error = None
    try:
        # Do this late so an error is reported. It could happen when a flag is
        # removed but the auto-update script was not upgraded properly.
        options, args = parser.parse_args(args)
        levels = [logging.WARNING, logging.INFO, logging.DEBUG]
        logging_utils.set_console_level(levels[min(options.verbose,
                                                   len(levels) - 1)])
        if args:
            parser.error('Unsupported args.')
    except Exception as e:
        # Do not reboot here, because it would just cause a reboot loop.
        error = str(e)
    try:
        return run_bot(error)
    finally:
        call_hook(bot.Bot(None, None, None, ROOT_DIR, None), 'on_bot_shutdown')
Example #9
0
 def start(self):
     self.tiros = []
     self.bots = []
     self.ticks = 0
     bot.indice_count = 0
     for f in self.funcoes:
         self.bots.append(bot.Bot(self, f))
Example #10
0
def index():
    message = ''
    try:
        with open("game.pickle", 'rb') as f:
            field = pickle.load(f)
    except FileNotFoundError:
        field = field_.Field()
    bot = bot_.Bot('O')
    if request.method == 'POST':
        x = int(request.form['x'])
        y = int(request.form['y'])
        try:
            field[x, y] = "X"
        except:
            message = 'Cell is occupied'
        if field.is_win('X'):
            os.remove("game.pickle")
            return "You won!"
        if field.is_draw():
            os.remove("game.pickle")
            return "Draw game"
        field[bot.move(field)] = 'O'
        if field.is_win("O"):
            os.remove("game.pickle")
            return "I won!"
        with open('game.pickle', 'wb') as f:
            pickle.dump(field, f)
    return render_template("index.html", field=field, message=message)
Example #11
0
 def test_bot_call_later_cancel(self):
     obj = bot.Bot({}, 'https://localhost:1', '1234-1a2b3c4-tainted-joe',
                   'base_dir', None)
     ev = threading.Event()
     obj.call_later(0.1, ev.set)
     obj.cancel_all_timers()
     self.assertFalse(ev.wait(0.3))
Example #12
0
async def receive_send(websocket, path):
    # Please write your code here

    global clients
    clients.add(websocket)
    try:
        while True:
            msg = await websocket.recv()
            ans = {}
            ans['data'] = msg
            await asyncio.wait([ws.send(json.dumps(ans)) for ws in clients])
            if re.match(' *bot +.+ +.+ *', msg) != None:
                command_list = re.split(" +", msg)[1:]
                command_dic = {
                    'command': command_list[0],
                    'data': command_list[1]
                }
                bt = bot.Bot(command_dic)
                bt.generate_hash()
                ans['data'] = bt.hash
                await asyncio.wait(
                    [ws.send(json.dumps(ans)) for ws in clients])

    except websockets.exceptions.ConnectionClosed:
        pass

    finally:
        clients.remove(websocket)
Example #13
0
def make_bot(remote=None):
    return bot.Bot(remote,
                   {'dimensions': {
                       'id': ['bot1'],
                       'pool': ['private']
                   }}, 'https://localhost:1', '1234-1a2b3c4-tainted-joe',
                   'base_dir', None)
Example #14
0
 def testLoad(self):
     import bot
     import confman
     b = bot.Bot(conf=confman.ConfManager(TestBase.conf),
                 network=TestBase.irc_server,
                 d=False)
     b.load_modules()
     assert len(b.loaded_modules) > 0
Example #15
0
 def testBase(self):
     import bot
     import confman
     assert bot.Bot(
         d=False,
         conf=confman.ConfManager(TestBase.conf),
         network=TestBase.irc_server
     ) is not None, "bot is None! Check tests/test_pybotrc for reachable IRC server."
Example #16
0
def main():
    print('Loading config...')
    config = toml.load('config.toml')

    inst = bot.Bot()
    inst.setup('main', config)
    print('Starting bot...')
    inst.start()
Example #17
0
def main():
    if not os.path.exists(cache_dir):
        os.mkdir(cache_dir)

    token = os.environ.get("TOKEN")
    database_url = os.environ.get("DATABASE_URL")
    fns_bot = bot.Bot(token, database_url)
    fns_bot.run()
Example #18
0
 def test_bot(self):
     obj = bot.Bot(None, {'dimensions': {
         'foo': 'bar'
     }}, '1234-1a2b3c4-tainted-joe', 'base_dir', None)
     self.assertEqual({'foo': 'bar'}, obj.dimensions)
     self.assertEqual(THIS_FILE, obj.swarming_bot_zip)
     self.assertEqual('1234-1a2b3c4-tainted-joe', obj.server_version)
     self.assertEqual('base_dir', obj.base_dir)
Example #19
0
def setup(username, password):
    b = bot.Bot(username, password)
    #b.loginAdmin()
    b.login()
    time.sleep(b.rest)
    b.close_notification_dialog()
    time.sleep(b.rest)
    return b
Example #20
0
 def testBotSocket(self):
     import bot
     import confman
     b = bot.Bot(d=False,
                 conf=confman.ConfManager(TestBase.conf),
                 network=TestBase.irc_server)
     b.worker(mock=True)
     assert b.s is not None
Example #21
0
def main():
    config.load_all()
    my_bot = bot.Bot(config.auth["name"], config.auth["password"], config.auth["pm"])
    for room in config.rooms:
        my_bot.joinRoom(room)
    try:
        my_bot.main()
    finally:
        config.save_all()
Example #22
0
 def test_getImages(self):
     """Does the bot retrieve a list of images?"""  # GIVEN the group chat has at least one image
     testBot = bot.Bot(os.environ['bot_id'], os.environ['token'],
                       os.environ['group_ID'])
     imageList = testBot.run(
     )  #AND THEN post_images calls the private get_images method which returns an array
     self.assertTrue(
         len(imageList) >
         0)  #THEN there should be at least one element in the array
Example #23
0
 def test_postImages(self):
     """Does the bot save images to imgs folder?"""  # GIVEN the group chat has at least one image
     testBot = bot.Bot(os.environ['bot_id'], os.environ['token'],
                       os.environ['group_ID'])
     testBot.run(
     )  #THEN the bot should save images from the group to the imgs folder
     self.assertTrue(
         len(os.listdir('./imgs')) >
         0)  #AND there should be at least one image in the folder
Example #24
0
 def test_add_nick_to_csv(self):
     bot = botcode.Bot(nick_source='test_nicks.csv')
     bot.add_known_nick('Roger__')
     with open('test_nicks.csv', 'rb') as csv_file:
         known_nicks = []
         csv_file_data = csv.reader(csv_file, delimiter=',', quotechar='|')
         for row in csv_file_data:
             known_nicks.append(row)
         self.assertEqual(known_nicks, [['Alice'], ['Bob'], ['Roger']])
Example #25
0
def main():
    player_config = [
        Bot(Race.Random, bot.Bot()),
        Computer(Race.Random, Difficulty.VeryHard)
    ]

    gen = sc2.main._host_game_iter(sc2.maps.get("CatalystLE"),
                                   player_config,
                                   realtime=False)

    while True:
        next(gen)

        if input('Press enter to reload or type "q" to exit: ') == 'q':
            exit()

        reload(bot)
        player_config[0].ai = bot.Bot()
        gen.send(player_config)
Example #26
0
def add_Bot():
    global newBot
    global BOT_COUNT

    newBot = bot.Bot(BOT_COUNT)
    botNet[str(BOT_COUNT)] = newBot

    database.save_bot(newBot)

    BOT_COUNT += 1
Example #27
0
def maxRun(tags, q):
    print('第{}个线程开始'.format(tags))
    Bot = bot.Bot('12315')
    while not q.empty():
        url = q.get()
        print('第{}个线程正在进行: '.format(tags), url)
        Bot.__init__(url)
        Bot.run()
    print('-----------')
    return 0
Example #28
0
def main():
    """
    Main
    """
    parser = crate_arg_parser()
    args = parser.parse_args()
    my_bot = bot.Bot(args.token, args.boss_id, process_input)
    my_bot.start()
    time.sleep(30)
    my_bot.active = False
Example #29
0
 def __init__(self, **kwargs):
     #first load defaults
     self.settings = self.load_default_config()
     self.auth = kwargs['auth']
     self.config = kwargs['config']
     self.sources = kwargs['sources']
     self.init_config()
     self.init_sources()
     self.joe = aj.Joe(self.timezone, self.waketime, self.bedtime,
                       self.interval, self.randomization)
     self.bot = bot.Bot(auth=self.auth, source_list=self.source_list)
Example #30
0
 def test_bot(self):
     obj = bot.Bot({'dimensions': {
         'foo': 'bar'
     }}, 'https://localhost:1', '1234-1a2b3c4-tainted-joe', 'base_dir',
                   None)
     self.assertEqual({'foo': 'bar'}, obj.dimensions)
     self.assertEqual(
         os.path.join(os.path.dirname(THIS_FILE), 'swarming_bot.zip'),
         obj.swarming_bot_zip)
     self.assertEqual('1234-1a2b3c4-tainted-joe', obj.server_version)
     self.assertEqual('base_dir', obj.base_dir)