def main(argv): if os.path.exists(pid_file): print( 'PID file exists! If the bot is not running, please delete this file before trying to start again!' ) sys.exit(1) fork = False if len(argv) > 0: if argv[0] == '-fork': fork = True if fork: logging.basicConfig(filename=logging_file, level=logging_level, format=logging_format) else: logging.basicConfig(level=logging_level, format=logging_format) logging.info("Welcome to botje") if fork: try: pid = os.fork() if pid > 0: logging.info('Forked into PID {0}'.format(pid)) with open(pid_file, 'w') as f: f.write(str(pid)) print(pid) return 0 except OSError as error: logging.error('Unable to fork. Error: {0} ({1})'.format( error.errno, error.strerror)) return 1 botje = Bot.Bot() while True: try: logging.info('Starting bot...') botje.start() except Bot.BotRestartException: continue except Bot.BotReloadException: logging.info('Force reloading Bot class') botje = None reload(Bot) botje = Bot.Bot() botje.modules.reload_modules() continue except select.error as e: logging.exception("select.error") continue except (KeyboardInterrupt, Bot.BotExitException): botje.die() break logging.warning('Botje died, restarting in 5...') import time time.sleep(5) logging.info('Exiting bot...') if fork: os.remove(pid_file)
def __init__(self, player1, player2): self.grid = [[0 for x in range(self.COLUMNS)] for y in range(self.ROWS)] self.player = [] if player1 == 'p': self.player.append(Player(1)) else: self.player.append(Bot(1)) if player2 == 'p': self.player.append(Player(2)) else: self.player.append(Bot(2))
def __init_game(self): """ Function initializes all backend game fields. :return: """ self.bombs = [] self.timer = QTimer() self.player = Player.Player(1, 1, 0) self.bots = [ Bot.Bot(10 + (i + 1) * 6, 10 + (i + 1) * 6, i + 1) for i in range(num_of_bots) ] self.score = 0 self.create_board() self.move_dict = { Qt.Key_Left: self.move_left, Qt.Key_Right: self.move_right, Qt.Key_Up: self.move_up, Qt.Key_Down: self.move_down, Qt.Key_Space: self.add_bomb } for bot in self.bots: bot.remember_board(self.board) bot.remember_player_pos([self.player]) bot.remember_bombs(self.bombs)
def createLevel(self, x, y): square = 40 rawImage = pygame.image.load(os.path.abspath('./assets/platform.png')).convert() enemyImage = pygame.image.load(os.path.abspath('./assets/enemy.png')).convert_alpha() currentX = 0 currentY = 0 wallCount = 0 for row in self.CurrentLevel: print(row) for char in row: if char == 'w': self.platforms.append(Wall(None, None, GraphicsComponent(self.screen, None),x,y,square,square)) if char == 'e': self.end = EndBlock(x, y, square, square) self.end.graphics = EndGraphics(self.screen) self.addEntity(self.end) if char == 's': self.start = x, y if char == 'b': bot = Bot(DumbBot(self), PhysicsComponent(self), GraphicsComponent(self.screen, enemyImage)) bot.rect.center = x, y self.addEntity(bot) x += square y += square x = square
def hello_user(): """ Page dans laquelle l'utilisateur configure et lance le bot Encore en développement :return: """ if request.method == 'POST': if request.form['submit_button'] == 'go': user = [] passw = [] order = request.form.getlist('accounts') for account in order: cred = (db.collection(account).document('credentials')).get() user.append(cred.get('email')) passw.append(cred.get('password')) tasks = db.collection('Tasks').stream() # recuperation des tâches print(order) print(user) print(passw) bot_test = Bot(user, passw, order, int(request.form['retrieve']), tasks) # bot_test.vivre() notifications = bot_test.getNotificationTwitter() elif request.form['submit_button'] == 'stop': raise Exception('Arreté prématurement') return render_template('hello_user.html', notifications=notifications) return render_template('hello_user.html')
def __init__(self, row, col, defVal, botname): self.board = Structure.Board(row, col, defVal) playerName = input('Enter your Name to continue\n') self.player = Player.Player(playerName) self.bot = Bot.Bot(botname) print('----------------------------\n') self.decideTurn()
def alternativo(self): inicio = time.time() print("iniciar") hilo = [] for i in range(0, self.cores): self.botsS.acquire() for i in range(0, self.cores): self.lockM.acquire() print("Bot" + str(i) + ": Saliendo") self.lockM.release() ini = int((i * self.lenght) / self.cores) fini = int((self.lenght / self.cores) * (i + 1)) #print(ini, fini, fini - ini, self.lenght) b = Bot.Bot("bot" + str(i), self.diccL, itertools.islice(self.permutaciones, ini, fini), self) b.start() self.lockM.acquire() print("todos los bots despachados") self.lockM.release() for i in range(0, self.cores): self.botsS.acquire() self.lockM.acquire() print("termino") print(time.time() - inicio) self.lockM.release() self.botsS.release()
def newBot(botPosition, botParent=None): import Bot global nextBotIndex newbornBot = Bot.Bot(botPosition, nextBotIndex, botParent) nextBotIndex += 1 gameWorld.createBot(newbornBot) botsToAdd.append(newbornBot) return newbornBot
def __init__(self, symbol, starting_posn, code_file): """ Initializes the bike. """ self.curr_posn = starting_posn self.prev_posn = Position(starting_posn.x, starting_posn.y, starting_posn.max_x, starting_posn.max_y) self.symbol = symbol self.bot = Bot(symbol, code_file) self.is_dead = False
def testGiveDirections(self): self.game = Game.Game() self.player = self.game.player1 self.bot = Bot.Bot(self.game, self.player) self.bot.botPos = (500, 500) self.bot.ballPos = (800, 200) directionList1 = self.bot.giveDirections() for element in directionList1: self.assertIn(element, [Bot.JUMP, Bot.RIGHT])
def start(): login = login_input.get() pw = pw_input.get() hashtag = hashtag_input.get() count = int(count_input.get()) window.destroy() new_bot = Bot() new_bot.login(login, pw) new_bot.like(hashtag, count)
def main(): bot = Bot() autoit.win_wait(bot.title, 5) counter = 0 poitonUse = 0 cycle = True fullCounter = 0 while cycle: hpstatus = bot.checkOwnHp() mpstatus = bot.checkOwnMp() print 'hp ' + str(hpstatus) if hpstatus == 0: print 'Dead' cv2.imwrite('Dead' + str(int(time.time())) + '.png', bot.getScreen(leftCornerx, leftCornery, x2, fullY2)) cycle = False if hpstatus == 1: autoit.control_send(bot.title, '', '{F5}', 0) print 'mp ' + str(mpstatus) if mpstatus < 2: autoit.control_send(bot.title, '', '{F11}', 0) res = bot.findHP() print 'tgs ' + str(res) if res == 3: fullCounter += 1 print 'fc ' + str(fullCounter) else: fullCounter = 0 if fullCounter > 9: autoit.control_send(bot.title, '', '{ESC}', 0) bot.sleep(0.3, 0.6) # autoit.control_send(bot.title, '', '{F3}', 0) # bot.mouseRotate() fullCounter = 0 if res > 0: autoit.control_send(bot.title, '', '{F1}', 0) counter = 0 bot.sleep(0.1, 0.2) autoit.control_send(bot.title, '', '{F2}', 0) else: fullCounter = 0 autoit.control_send(bot.title, '', '{F9}', 0) if counter < 2: autoit.control_send(bot.title, '', '{F3}', 0) bot.sleep(0.1, 0.2) autoit.control_send(bot.title, '', '{F1}', 0) if counter > 1: # bot.findTarget() autoit.control_send(bot.title, '', '{F7}', 0) counter = 0 counter += 1 print 'cnt ' + str(counter) pass
def init_get_players_local(number_of_players): if number_of_players == 1: return [Player("Arnaud")] + [Bot()] elif number_of_players == 2: return [Player("Arnaud")] + [Player("Barry")] else: players_list = [] for i in range(number_of_players): players_list.append( (str(input("Nom du joueur {}: ".format(i + 1))))) return players_list
def load_bot(botModule, port, botName): nameMaxLength = 10 if len(botName) > nameMaxLength: # Cut the name if too long. Bot.safe_print('Warning : Bot name too long ({}) truncated to {}'.format(botName, botName[:nameMaxLength])) botName = botName[:nameMaxLength] bot = Bot.Bot(port, botName) # Create the bot. try: botModule.main(bot) # Run the bot ! except socket.error, exception: # The exception is raised when the socket is closed on server's side. Bot.safe_print('Bot {} shut down'.format(botName)) del bot
def _addBot(self): b = Bot(self._canvas, self._bx.get(), self._by.get(), sF=self._bs.get()) k11 = self._k11.get() k12 = self._k12.get() k21 = self._k21.get() k22 = self._k22.get() b.setMatrix(k11, k12, k21, k22) self._world.addBot(b)
def main(): bot = Bot() autoit.win_wait(bot.title, 5) cycle = True # print 'Argument:', str(sys.argv[1]) while cycle: if not bot.matchBuff(str(sys.argv[1]) + '.png'): # bot.clickBuff(str(sys.argv[1]) + '_click.png') autoit.control_send(bot.title, '', '{F4}', 0) bot.sleep(20, 40) pass
def main(): bot = Bot() autoit.win_wait(bot.title, 5) cycle = True while cycle: mp = bot.checkOwnMp() print mp if mp < 2: autoit.control_send(bot.title, '', '{F11}', 0) bot.sleep(10, 30) pass
def main(): name = input("Hi there. Please Enter you name ") flag = False while not flag: choice = input("Would you like to play v/s player or v/s computer. Enter 'P' for player and 'C' for computer ") if choice in ["P", "p"]: name_second = input("Hi there. Please Enter the name for the second player ") arena = Arena(name, [Player.Player(name), Player.Player(name_second)]) flag = True elif choice in ["C", "c"]: arena = Arena(name, [Player.Player(name), Bot.Bot("Computer Bot!")]) flag = True else: print("Please enter the choice from 'P' or 'C'") arena.play()
def main(): bot = Bot() wincount = sys.argv[1] autoit.win_wait(bot.title, 5) counter = 0 cycle = True while cycle: print 'send' for count in range(1, int(wincount) + 1): title = "[TITLE:Lineage II; INSTANCE:" + str(count) + "]" autoit.control_send(title, '', '{F1}', 0) bot.sleep(0.1, 0.3) autoit.control_send(title, '', '{F1}', 0) bot.sleep(0.7, 1.3) print 'title ', title bot.sleep(0.3, 0.8)
def __init__(self, numberBots, startSize): self.numberBots = numberBots self.startSize = startSize self.botList = [] self.swarmStartX = 200 self.swarmStartY = 200 self.sizeBot = 3 self.swarmCenterX = 0 self.swarmCenterY = 0 for i in range(0, numberBots): overlap = True counter = 0 while overlap: counter += 1 if counter > 1000: print('You F****d up! Not enought space') self.botList = [] return # create random position of bot within defined radius radiusSwarm = random.uniform(0, self.startSize) thetaSwarm = random.uniform(0, 2 * math.pi) # define Bot initial variables xPosBot = self.swarmStartX + radiusSwarm * math.cos(thetaSwarm) yPosBot = self.swarmStartY + radiusSwarm * math.sin(thetaSwarm) if i > 0: for element in self.botList: dist = element.distance(xPosBot, yPosBot, element.xPos, element.yPos) if dist > 2 * self.sizeBot: overlap = False else: overlap = True break else: overlap = False thetaBot = 0 velocityBot = 0 # create Bot and add to list newBot = Bot.Bot(xPosBot, yPosBot, velocityBot, thetaBot, self.sizeBot) self.botList.append(newBot)
def main(): bot = Bot() autoit.win_wait(bot.title, 5) enchx = 1010 ecnhy = 684 cycle = True bot.sleep(3, 5) print 'Count:', str(sys.argv[1]) print 'X:', str(sys.argv[2]) print 'Y:', str(sys.argv[3]) count = sys.argv[1] x = sys.argv[2] y = sys.argv[3] while i <= count: bot.randClick(x, y, 'right') pass
def reinf_main(self): bot = bt.Bot() rospy.on_shutdown(self.shutdown) episodes = 400 gamma = 0.95 alpha = 0.8 try: rate = rospy.Rate(50) while not rospy.is_shutdown(): if(self.flag): #segmentation seg_img = self.imgHelper.segmentation(self.my_img) #do reinforcement learning if(self.episodes_counter < episodes): #decide whether to explore or to exploit explore = self.explore_vs_exploit(self.episodes_counter, episodes) #fill q -matrix for j in range(20): self.curve = bot.q_learning(gamma, alpha, seg_img, explore) #if(self.curve == "stop"): #break else: #use q-matrix self.curve = bot.use_q_matrix(seg_img) print(self.curve) #turn the curve-string into a valid message type self.vel_msg = self.translateToVel(self.curve) #publish self.velocity_publisher.publish(self.vel_msg) #set flag back to false to wait for a new image self.flag = False rate.sleep() except rospy.ROSInterruptException: pass
def main(): print("IA LAUNCHED with [", sys.argv , "]") if len(sys.argv) >= 3: host = sys.argv[1] port = sys.argv[2] step = False serialized_ia = None; if len(sys.argv) == 4 and sys.argv[3] == "step": step = True elif len(sys.argv) == 5 and sys.argv[4] == "step": step = True serialized_ia = sys.argv[3]; elif len(sys.argv) == 4: serialized_ia = sys.argv[3]; print("[INFO]: try to connect to " + host + " on " + port) bot = Bot.Bot(host, int(port), step, serialized_ia) bot.update() else: print("[Error] missing arguments.") usage()
def main(): bot = Bot() autoit.win_wait(bot.title, 5) counter = 0 poitonUse = 0 cycle = True bot.sleep(3, 5) bigsleep = round(random.uniform(10, 50)) print 'Argument:', str(sys.argv[1]) while cycle: bot.randClick(1444, 724, 'right') bot.sleep(1, 1.5) counter += 1 if counter >= int(sys.argv[1]): cycle = False print str(counter) + " bgs(" + str(bigsleep) + ")" if counter % bigsleep == 0: bot.sleep(1, 2) bigsleep = round(random.uniform(10, 50)) pass
def __init__(self, sizeX, sizeY): pygame.init() self.screen = pygame.display.set_mode((sizeX, sizeY)) self.fontStd = pygame.font.Font( pygame.font.match_font("verdana,dejavusans"), 14) self.fontBig = pygame.font.Font( pygame.font.match_font("verdana,dejavusans"), 20) self.screenW = pygame.display.Info().current_w self.screenH = pygame.display.Info().current_h self.ticks = 0 self.boundaries = (0, 0, sizeX, sizeY) self.bots = [] self.resets = [] self.lastInfoUpdate = 0 for i in range(2): bot = Bot.Bot(layers=4, units=2, size=10) bot.RandomizePosition((0, 0, self.screenW, self.screenH)) bot.RandomizeRotation() bot.RandomizeColor() self.bots.append(bot)
def main(): """ Highway 153 """ # Read through the highway json file reader153 = JsonReader("urls/hwy153.json") urls153 = reader153.getAllUrls() saved153Images = [] # Get all iamges count = 1 for item in urls153: url = item["base_url"] filename = "downloads/hwy153--" + str(count) + ".png" displayName = item["display_name"] result = WebScraper.save_image(url, filename) if result[0]: print("[Main]: Saved image #" + str(count)) saved153Images.append((displayName, filename)) else: print("[Main]: Error on image #" + str(count)) saved153Images.append(("displayName", "error")) count += 1 # Post all images in a thread bot = Bot() tweetId = bot.post_text("Highway 153") for item in saved153Images: if item[1] == "error": tweetId = bot.post_text_as_response(item[0] + " - Camera down", tweetId) else: tweetId = bot.post_image_as_response(item[0], item[1], tweetId) """ Interstate 24 """ """ Interstate 75 """ """ US 27 """
def main(): bot = Bot() autoit.win_wait(bot.title, 5) cycle = True colorMin = [160, 160, 5] colorMax = [237, 237, 30] cnt = 0 found = 0 temp = 0 while cycle: if found == 0 and temp == 1: autoit.control_send(bot.title, '', '{F4}', 0) bot.sleep(1, 4) found = temp # systemChatCoord = (27, 751, 350, 870) # grab = ImageGrab.grab(systemChatCoord) # img = array(grab.getdata(),dtype=uint8).reshape((grab.size[1],grab.size[0],3)) # mask = cv2.inRange(img, array(colorMin, dtype='uint8'), array(colorMax, dtype='uint8')) # mask = cv2.filter2D(mask,-1, ones((2,30), float32)) # (cnts, hierarchy) = cv2.findContours(mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) # cv2.drawContours(img, cnts, -1, (255,0,0), 3) # cv2.imshow("images", img) # cv2.waitKey(0) # bla() if temp == 0: found = temp if cnt > 10 or found == 1: print found cnt = 0 cnt += 1 bot.sleep(0.1, 0.2) temp = bot.checkSystemChatColor(colorMin, colorMax) pass
def __init__(self, table_info, table_gui): self.__table_info = table_info self.__table_gui = table_gui # self.__players = [Player(player_info, self.__table_info) for player_info in self.__table_info.players()] self.__players = [(PeoplePlayer(self.__table_info.players()[0], self.__table_info, self.__table_gui.decision_block()))] self.__players += [ Bot(player_info, self.__table_info) for player_info in self.__table_info.players()[1:] ] self.__player_queue = self.__players turn_start_player_num = random.randint( 0, self.__table_info.player_count() - 1) self.__turn_start_player_name = self.__players[ turn_start_player_num].player_info().name() # Prepare player queue tsp_num = self.__player_num_by_name(self.__turn_start_player_name) self.__player_queue = self.__player_queue[ tsp_num:] + self.__player_queue[:tsp_num]
if mode == "training": dataSource = OldDataForModelBuilding.OldDataForModelBuild() #[print(dataSource.getRow()) for i in range(1, 4)] broker = BuySellEmulator(datasource=None, mode=mode) #BrokerMetaTraderEmulator() features = FeatureProvider() agent = QAgent.QAgent(model=file, epsilon=t_epsilon, alpha=t_alpha, gamma=t_gamma, features=features) delay=0 elif mode == "trainingLive": dataSource = CleanBrokerData('C:/Users/garre/AppData/Roaming/MetaQuotes/Terminal/B83207E76A7859F5556693074AFE91E8/MQL4/Files/Data/Math748PriceSending.csv') #NOTE AS OF NOVEMBER I CHANGE DATASOURCE OBJECT to be passed into emulator and broker #I have not thought that through much and might be a design choice later on time.sleep(1)#experiment? broker = BuySellEmulator(dataSource) #BrokerMetaTraderEmulator() features = FeatureProvider() #agent = QAgent.QAgent(model=file, epsilon=t_epsilon, alpha=t_alpha, gamma=t_gamma, features=features) delay=0 elif mode == "testing": dataSource = None#TODO this later broker = None#TODO add this later agent = QAgent(model=file, epsilon=epsilon, alpha=alpha, gamma=gamma) b = Bot(dataSource=dataSource, broker =broker, featureProviders=features, delay=delay) #b = Bot(mode) try: b.run() except KeyboardInterrupt: print("Closing program, saving model") agent.saveModel()
def main(): bot = Bot() bot.authenticate()