def fireOnce(): print '--> establishing hatred' key.pressEx(sc.HeightSlot1) time.sleep(1) key.pressEx(sc.HeightSlot1) print '<-- establishing hatred\n' return True
def closeInventory(): print '--> close inventory' key.pressEx(sc.Inventory) time.sleep(1) print '<-- close inventory\n' return True
def enableDefense(): print '--> enable defense' # key.pressEx(sc.LowSlot1) # key.pressEx(sc.LowSlot2) # key.pressEx(sc.LowSlot3) key.pressEx(sc.AllLow) print '<-- enable defense\n' return True
def enterStarMap(): print '--> enter star map' key.pressEx(sc.Map) begin = time.time() while findAtProgressBar('initializing_map') or time.time() - begin < 3: time.sleep(0.5) mouse.moveToP(panel.center(panel.Full)) mouse.wheel(100) print '<-- enter star map\n'
def openInventory(): print '--> open inventory' key.pressEx(sc.Inventory) mouse.moveToP(panel.center(panel.Inventory)) while not findAtInventory('x'): time.sleep(0.2) print '<-- open inventory\n' return True
def check_event(engine, steer): """键盘事件检查""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: keyboard.action_down(event.key, engine, steer) elif event.type == pygame.KEYUP: keyboard.action_up(event.key, engine, steer)
def engage(): print '--> drones engaging\n' key.pressEx(sc.DronesEngage) while not findAtDrones('fighting'): key.pressEx(sc.DronesEngage) time.sleep(0.5) print '<-- drones engaging\n' return True
def handleDangerousAction(): result = findAtFull('dangerous') if result: mouse.moveToP(result) result = None while not result: result = findAtFull('x') mouse.leftClickAtP(result) key.pressEx(sc.Unlock) return True else: return False
def approachFor(second): print '--> approaching target' key.pressEx(sc.Approach) while second > 0: time.sleep(1) second -= 1 if second % 5 == 0: print str(second) + "second's left" print '<-- approaching target\n' return True
def repair(): print '--> repair' result = findAtStationServices('repair_shop') if not result: return mouse.leftClickAtP(result) print 'wait until open repair facilities' result = None while not result: result = findAtFull('repair_facilities') time.sleep(0.5) time.sleep(0.5) mouse.leftClickAt(result[0], result[1] + 70) key.pressEx('ctrl+a') result = None while not result: result = findAtFull('repair_item') time.sleep(0.2) mouse.leftClickAtP(result) print 'wait...' while not findAtFull('pick_new_item'): time.sleep(0.2) result = findAtFull('repair_all') if result: mouse.leftClickAtP(result) print 'repairing...' result = None while not result: time.sleep(0.2) result = findAtFull('ok') if not result: result = findAtFull('yes') mouse.leftClickAtP(result) result = findAtFull('repair_facilities') mouse.moveToP(result) else: print 'nothing to repair' result = None while not result: time.sleep(0.2) result = findAtFull('x') mouse.leftClickAtP(result) print '<-- repair\n' return True
def lockEnemy(wait = 5): print '--> lock enemy' result = findEnemy() if not result: return False mouse.leftClickAtP(result) key.pressEx(sc.Lock) print 'wait for ' + str(wait) + ' seconds' time.sleep(wait) print '<-- lock enemy' return True
def start_command_handler(message): """Start command to start bot""" chat_id = message.chat.id try: bot.send_message(chat_id, text="Hello 👋🏻***" + message.from_user.username + "***", parse_mode="Markdown", reply_markup=Keyboard.main_menu_keyboard()) except Exception as e: bot.send_message(chat_id, text="Hello 👋🏻***" + message.from_user.first_name + "***", parse_mode="Markdown", reply_markup=Keyboard.main_menu_keyboard())
def lockTarget(target, wait = 5): result = findTarget(target) if not result: return False print '--> lock target "' + target + '"' mouse.leftClickAtP(result) key.pressEx(sc.Lock) print 'wait for ' + str(wait) + ' seconds' time.sleep(wait) print '<-- lock target "' + target + '"\n' return True
def activateAccelerationGate(): switchTo('pilot') general.enterStarMap() print '--> activate acceleration gate\n' mouse.leftDownAtP(panel.center(panel.Full)) mouse.move(500, 200) mouse.leftUp() result = findTarget('acceleration_gate') if not result: return False mouse.leftClickAtP(result) key.pressEx(sc.Activate) print 'wait to activate gate' while not findAtDashboard('warp_drive_active'): result = findAtFull('close') if not result: result = findAtFull('ok') if result: mouse.leftClickAtP(result) mouse.moveTo(result[0], result[1] - 200) handleDangerousAction(); key.pressEx(sc.Activate) time.sleep(1) print 'wait until reach location' while findAtDashboard('warp_drive_active'): time.sleep(0.5) result = findAtFull('close') if not result: result = findAtFull('ok') if result: mouse.leftClickAtP(result) mouse.moveTo(result[0], result[1] - 200) time.sleep(1) while findAtDashboard('warp_drive_active'): time.sleep(0.5) print '<-- activate acceleration gate\n' general.exitStarMap() return True
def calculate(message): chat_id = message.chat.id text = message.text currency = text.split(" ") try: if int(text): amount = text try: amount_of_money = int(amount) if isinstance(amount_of_money, int): exchange.amount_money = amount_of_money msg = bot.send_message( message.chat.id, "Select⬇️", reply_markup=Keyboard.currency_select_markup()) bot.register_next_step_handler(msg, reverse_calculation) except Exception as e: msg = bot.send_message(message.chat.id, "You should write how much to convert!", parse_mode='Markdown') bot.register_next_step_handler(msg, reverse_calculation) except Exception as e: exchange.type_of_currency = currency[1] msg = bot.send_message(chat_id, "***How much do you want convert?***🤑", parse_mode='Markdown') bot.register_next_step_handler(msg, return_calculation)
def __init__(self): ##### self.musicEnabled = False ##### self.FRAMERATE = round(1000/60) self.HEIGHT = 800 self.WIDTH = 800 self.TILE_SIZE = 32 self.VERTICAL_TILES = self.HEIGHT//self.TILE_SIZE self.HORIZONTAL_TILES = self.WIDTH//self.TILE_SIZE self.PSTARTX = 400 self.PSTARTY = 400 self.justStarted = True self.titleUp = False self.main_app = self self.root = tkinter.Tk() self.root.title("RPG Land") self.Canvas = tkinter.Canvas(self.root,width= self.WIDTH, height=self.HEIGHT ) self.Level = LevelMgr.LevelMgr(self) self.Audio = Audio.Audio(self) self.Player = Player.Player(320,320,2,self,"./res/hero.gif") self.Collision = CollisionMgr.CollisionMgr(self) self.inputHandler = Keyboard.inputHandlerClass(self) self.Draw = DrawMgr.DrawMgr(self) self.GUI = GUIMgr.GUIMgr(self)
def back(): print '--> drones return' key.pressEx(sc.DronesReturn) mouse.moveToP(panel.center(panel.Drones)) mouse.wheel(-100) mouse.moveToP(panel.center(panel.Full)) print 'wait until drones return' while findAtDrones('returning') or findAtDrones('fighting') or findAtDrones('idle'): key.pressEx(sc.DronesReturn) time.sleep(0.2) print '<-- drones return\n' return True
def currency_calculator_handler(message): """Currency calculator handler, handles request to calculation of differences or conversion""" chat_id = message.chat.id msg = bot.send_message(chat_id, "Select⬇️", reply_markup=Keyboard.currency_select_menu_markup()) bot.register_next_step_handler(msg, select_conversion_type)
def run_game(world, game_state={}, fps=24): pygame.init() screen = pygame.display.set_mode((640, 480)) back_colour = (255, 0, 0) background = pygame.Surface(screen.get_size()) background.fill(back_colour) background = background.convert() owl = (0, 0) screen.blit(background, owl) timer = pygame.time.Clock() #world.reset() game_state["screen"] = screen game_state["clock"] = timer game_state["running"] = True game_state["keyboard"] = Keyboard(pygame) while game_state["running"]: game_state["running"] = game_state["keyboard"].update(pygame) ret = world.update(game_state) if isinstance(ret, WorldInterface): world = ret ret = None world.reset(game_state) continue # draw to buffer draw_world(world, game_state) # show buffer pygame.display.flip() # sync timer.tick(fps)
def Keyboard_fun7(self): if self.a == 0: self.a += 1 # Keyboard self.Keyboard = QtWidgets.QWidget(UI_Mainwindow) self.Keyboard.setMinimumHeight(70) self.Keyboard.setMaximumHeight(70) Keyboard_ui = Keyboard.Ui_Keyboard(self.Keyboard) self.Addition_Layout = QtWidgets.QVBoxLayout(self.Keyboard) self.Addition_Layout.setContentsMargins(0, 0, 0, 0) self.Addition_Layout.setObjectName("Addition_Layout") self.verticalLayout.addLayout(self.Addition_Layout) self.Addition_Layout.addWidget(self.Keyboard) Keyboard_ui.x_pow_n_button.clicked.connect(self.superscript) Keyboard_ui.Pi_button.clicked.connect(self.Pi_fun) Keyboard_ui.Modulus_button.clicked.connect(self.Modulus) Keyboard_ui.Lessthan_button.clicked.connect(self.Lessthan_fun) Keyboard_ui.Greaterthan_button.clicked.connect( self.Greaterthan_fun) Keyboard_ui.Sqrt_button.clicked.connect(self.Sqrt) Keyboard_ui.Exponential_button.clicked.connect( self.Exponential_fun) Keyboard_ui.Constant_button.clicked.connect(self.Constant_fun) self.Current_lineEdit = 6 else: self.Keyboard.deleteLater() if self.form_var_tem != 0: self.Form.deleteLater() self.form_var_tem = 0 self.count = 0 self.a -= 1
def __init__(self): super().__init__(WIDTH, HEIGHT, TITLE, resizable=True) arcade.set_background_color((19, 14, 30)) self.frames = 0 self.time = 0 self.debug_text = "" self.debug = True self.debug_text_list = Graphics.create_text_list(self.debug_text, 12, 12) os.chdir(os.path.dirname(os.path.abspath(__file__))) self.process = psutil.Process(os.getpid()) self.set_icon(pyglet.image.load("resources/icon.png")) self.text_input = TextInput() self.typing = False self.camera = Camera.Camera(WIDTH, HEIGHT) self.camera.zoom(20) self.keyboard = Keyboard.Keyboard() self.set_min_size(WIDTH, HEIGHT) self.prev_size = self.get_size() self.set_location( (self.camera.screen_width - WIDTH) // 2, (self.camera.screen_height - HEIGHT) // 2)
def get_weather(message): """Weather handler, handles request to weather service""" chat_id = message.chat.id msg_text = bot_engine.get_weather_by_default() bot.send_message(chat_id, text=msg_text, reply_markup=Keyboard.main_menu_keyboard(), parse_mode='Markdown')
def __init__(self): self.keypad = key.Keypad() self.led_board = led.LedBoard() self.password_file = "pw.txt" ##Complete pathname to file holding the KPC's password self.password_buffer = "" self.new_password_buffer = "" self.override_signal = "" self.led_id = 0 self.led_dur = 0
def default_keyboard(eng_count, prog_count): # no using more queue_label = Keyboard.Button.link(label="Кнопки занятия очереди:") eng_button = Keyboard.Button.text(label=f"Английский({eng_count})", payload='1') prog_button = Keyboard.Button.text(label=f"Программирование({prog_count})", payload='2') queue_button = Keyboard.Button.text(label="Показать очередь", payload='3', color='positive') donate_label = Keyboard.Button.link(label="На аренду хоста) (55р/мес)") donate_button = Keyboard.Button.vk_pay(_hash='action=transfer-to-group%26group_id=192889258%26aid=10') keyboard = Keyboard.create([queue_label], [eng_button, prog_button], [queue_button], [donate_label], [donate_button]) return keyboard
def send_cancel_button(message, payload, peer): cancel = Keyboard.Button.text(label="Отмена", payload=payload, color='negative') keyboard = Keyboard.create([cancel], inline=True) r = post("messages.send", secret=secret, v="5.103", access_token=token, peer_id=chat_peer, random_id=-random.randint(100000000, 999999999), message=message, keyboard=keyboard)
def initialize(self): ''' It's better to call this method after create all objects''' self.timeNow = now.time() if self.frame : print('Frame already created') else : self.frame = Frame.Frame(self) self.updateScreen() self.mouse = Mouse.Mouse(self) self.keyboard = Keyboard.Keyboard(self) self.running = True
def reverse_calculation(message): chat_id = message.chat.id text = message.text currency = text.split(" ") exchange.type_of_currency = currency[1] returning_value = exchange.return_reverse_conversion() text_msg = "🇺🇿{amount} UZS = {flag}{rtn_value} {code}" \ .format(amount=exchange.amount_money, flag=bot_engine.get_country_flag(exchange.type_of_currency), code=exchange.type_of_currency, rtn_value=returning_value) bot.send_message(chat_id, text_msg, reply_markup=Keyboard.main_menu_keyboard())
def activateShip(ship): print '--> activate ship "' + ship + '"' key.pressEx(sc.ShipHangar) time.sleep(3) result = None while not result: time.sleep(0.5) result = findAtInventory(ship) mouse.rightClickAtP(result) mouse.moveTo(result[0] + 200, result[1]) result = findAtInventory('make_active') if result: mouse.leftClickAtP(result) key.pressEx(sc.ShipHangar) time.sleep(2) print '<-- activate ship "' + ship + '"\n' return True
def tick(): global x,y,running,gameOver,scorePosted,isMultiplayer Keyboard.update(level) if timer == 30: soundFXs = Sounds.Audio(False) soundFXs.Plysound(False,False,False,False,True) if gameOver == True and scorePosted==False: level.player.score.happyDucks(level.player.username) scorePosted = True if Client.isHost == True and isMultiplayer == True: level.tick() endLevel.tick() if isMultiplayer == False and gameOver==False: level.tick() if endLevel!=None:endLevel.tick() if gameOver==False and level.player!=None: level.player.tick() if level.player == None: level.cam.tick() hud.tick(timer,xoff,yoff,level)
def setQuantity(self, quantity): # found = [217,200,217,200] found = [ 199, 181, 199 + GC.offer_button_dimensions[0], 181 + GC.offer_button_dimensions[1] ] found_coord = [ self.self_window_coord[0] + found[0], self.self_window_coord[1] + found[1], self.self_window_coord[0] + found[2], self.self_window_coord[1] + found[3] ] # crop = Screenshot.crop(self.global_rs_image, found_coord) # cv2.imwrite(r'C:\Users\PPC\git\RS_BOT_2.0\aaaaacrop.png', crop) Mouse.clickRadius( self._calculateGlobalCoord(self.global_rs_coord, found_coord)) # Mouse.win32ClickRadius(self._calculateGlobalCoord(self.global_rs_coord, found_coord)) # Mouse.win32MoveToRadius(self._calculateGlobalCoord(self.global_rs_coord, found_coord)) RandTime.randTime(0, 0, 0, 2, 0, 0) Keyboard.type_this(quantity) Keyboard.press("enter")
def main(): input("Press ENTER to start...") start_time = time.clock() products = [ Laptop.Laptop(), Desktop.Desktop(), Monitor.Monitor(), Printer.Printer(), Mouse.Mouse(), Keyboard.Keyboard() ] for product in products: product.run() print("\n{0}s".format(time.clock() - start_time))
def return_calculation(message): amount = message.text try: amount_of_money = int(amount) if isinstance(amount_of_money, int): returning_value = exchange.return_calculation(amount_of_money) text_msg = bot_engine.get_country_flag(exchange.type_of_currency) + "{amount} {code} = 🇺🇿{rtn_value} UZS" \ .format(amount=amount_of_money, code=exchange.type_of_currency, rtn_value=returning_value) bot.send_message(message.chat.id, text_msg, reply_markup=Keyboard.main_menu_keyboard()) except Exception as e: msg = bot.send_message(message.chat.id, "You should write how much to convert!", parse_mode='Markdown') bot.register_next_step_handler(msg, return_calculation)
def __init__(self, parent, gui, **options): """ Initializes TkKeyboardManager object @param parent @param gui @param options """ super(TkKeyboardManager,self).__init__(parent, gui, **options) self.scheduler = gui.scheduler self.specification = gui.specification self.asciimap = Keyboard.AsciiMap() try: self.gui.kbthread except: self.gui.kbthread = Keyboard.KeyboardThread.GetInstance() self.kbthread = self.gui.kbthread self.stopped = not Setting.get('kb_autostart', False) if(Setting.get('kb_autostart', False)): self.OnStartClick()
def main(): """Main function to get information for Bar 4. """ getter_battery = Battery.Battery() getter_clock = Clock.Clock() getter_keyboard = Keyboard.Keyboard() getter_os = Os.Os() getter_battery.show_info() sys.stdout.write(" | ") getter_clock.get_uptime() sys.stdout.write(" | ") getter_clock.get_time() sys.stdout.write(" ") getter_clock.get_date() sys.stdout.write(" | ") getter_keyboard.get_layout() getter_keyboard.show_locks() sys.stdout.write(" | ") getter_os.get_os()
def __init__(self, color, title="StreetCode Academy", show_mouse_pos=False): pygame.init() pygame.font.init() self.screen = pygame.display.set_mode(SCREEN_SIZE) pygame.display.set_caption(title) self.clock = pygame.time.Clock() if pygame.font: self.font = pygame.font.Font(None, 30) else: self.font = None self.screen_color = color self.is_playing_game = True self.sprites = {} self.collision_flag = 0 self._keyboard = Keyboard() self._mouse = Mouse() self._show_mouse_pos = show_mouse_pos if self._show_mouse_pos: self.draw_rectangle(0, 100, 10, 1, WHITE) self.draw_rectangle(0, 200, 10, 1, WHITE) self.draw_rectangle(0, 300, 10, 1, WHITE) self.draw_rectangle(0, 400, 10, 1, WHITE) self.draw_rectangle(100, 0, 1, 10, WHITE) self.draw_rectangle(200, 0, 1, 10, WHITE) self.draw_rectangle(300, 0, 1, 10, WHITE) self.draw_rectangle(400, 0, 1, 10, WHITE) self.draw_rectangle(500, 0, 1, 10, WHITE) self.draw_rectangle(600, 0, 1, 10, WHITE) self.mouse_pos_text = self.draw_text(0, SCREEN_SIZE[1] - 17, '(0,0)', BLACK, size=12)
def send_chat(message): queue_label = Keyboard.Button.link(label="Кнопки занятия очереди:") eng_button = Keyboard.Button.text(label="Английский", payload='1') prog_button = Keyboard.Button.text(label="Программирование", payload='2') queue_button = Keyboard.Button.text(label="Очередь", payload='3', color='positive') queue_button1 = Keyboard.Button.text(label="Очередь", payload='33', color='positive') donate_label = Keyboard.Button.link(label="На аренду хоста) (55р/мес)") donate_button = Keyboard.Button.vk_pay(_hash='action=transfer-to-group%26group_id=192889258%26aid=10') keyboard = Keyboard.create([queue_label], [eng_button, prog_button], [queue_button, queue_button1], [donate_label], [donate_button]) r = post("messages.send", secret=secret, v="5.103", access_token=token, peer_id=chat_peer, random_id=-random.randint(100000000, 999999999), message=message, keyboard=keyboard) print(r)
def send_admin(message): eng_button = Keyboard.Button.text(label="Английский", payload='1', color='negative') prog_button = Keyboard.Button.text(label="Прога", payload='2', color='negative') eng_button1 = Keyboard.Button.text(label="Английский(Without)", payload='11', color='negative') prog_button1 = Keyboard.Button.text(label="Прога(Without)", payload='22', color='negative') status_button = Keyboard.Button.text(label="Статус", payload='3') everyone_button = Keyboard.Button.text(label="@everyone", payload='4', color='positive') everyone2_button = Keyboard.Button.text(label="@everyone(My acc)", payload='44', color='positive') move_button = Keyboard.Button.text(label="/<table> <now> <need>") # test_button = Keyboard.Button.text(label="test payload", payload='\"cancel\"', color='negative') keyboard = Keyboard.create([move_button], [everyone_button, everyone2_button], [eng_button, prog_button], [eng_button1, prog_button1], [status_button]) r = post("messages.send", secret=secret, v="5.103", access_token=token, peer_id=admin_peer, random_id=-random.randint(100000000, 999999999), message=message, keyboard=keyboard) print(r.json())
# move the sphere relative (10,-5,0) to the control point p=Placer.createPlacer("Sphere Mover",s) p.src=V p.x="sx+10" p.y="sy-5" # rotate the cube with rotation arc 20*sx along the default z-axis p2=Placer.createPlacer("Box Rotator",b) p2.src=V p2.x="-50" p2.y="-5" p2.arc="20*sx" # rotate the donat with rotation arc 10*sy along the x-axis p3=Placer.createPlacer("Torus Rotator",t) p3.src=V p3.x="50" p3.y="0" p3.arc="10*sy" p3.RotAxis=FreeCAD.Vector(1,0,0) # SENSOR # kb=Keyboard.createKeyboard("Keybord",V) # start up kb.ViewObject.Proxy.edit() App.activeDocument().recompute() Gui.SendMsgToActiveView("ViewFit")
def tick(): global x,y,running Keyboard.update(level) level.tick() level.player.tick()
def mine(): print '--> mine' key.pressEx(sc.HeightSlot2) key.pressEx(sc.HeightSlot3) print '<-- mine\n' return True
from Bluetooth import * from Gamepad import * from Keyboard import * ch = 0 while ch == 0: print 'press 1 to emulate keyboard' print 'press 2 to emulate gamepad' ch = raw_input("Press any key from menu: ") if ch == '1': bt = Bluetooth("sdp_record_kbd.xml", "000540", "BT\ Keyboard") bt.listen() kb = Keyboard() kb.event_loop(bt) elif ch == '2': bt = Bluetooth("sdp_record_gamepad.xml", "000508", "BT\ Gamepad") bt.listen() gp = Gamepad() gp.event_loop(bt) else: ch = 0 print('Please select from menu')
def stop(): print '--> ship stop' key.pressEx(sc.Stop) print '<-- ship stop\n' return True
def exitStarMap(): print '--> exit star map' key.pressEx(sc.Map) time.sleep(2) print '<-- exit star map\n'
def get_currency_handler(message): """Currency handler, handles request to get currency rate""" chat_id = message.chat.id currency_list = exchange.return_exchange_rate() msg = bot_engine.parse_coming_data(currency_list) bot.send_message(chat_id, msg, reply_markup=Keyboard.currency_markup())
def respond(self, user_id, msg): date = datetime.datetime.today() + datetime.timedelta(hours=3) print( date.strftime("%d.%m.%Y.%H:%M:%S") + f' New message from: {user_id}\nText: {msg}') if msg == "начать" or msg == "start" or msg == "#": self.send_msg_k(user_id, Keyboard.start(), "Здравствуй, " + self.getUserName(user_id)) elif msg == "info": self.send_msg( user_id, "autor @shaidulllin\n" + "# Проект был создан с целью напоминаия о предстоящих парах, подпишись на рассылку, чтобы быть в курсе\n" + "# Так же присутствует возможность узнавать расписание вручную, нажми на расписание\n" + "# Есть возможность узнавать информацию о преподователях\n" + "# Возможности бота небольшие, но вы можете это исправить") elif msg == "расписание" or msg == "<-": self.send_msg_k(user_id, Keyboard.today(), "Расписание на...") elif msg == "->": self.send_msg_k(user_id, Keyboard.weekday(), "Какой день недели?") elif msg == "подписаться на рассылку расписания": if not str(user_id) in open('id.txt', 'r').read(): open('id.txt', 'a').write(str(user_id) + "\n") self.send_msg(user_id, "Ты подписался на мою рассылку") else: self.send_msg(user_id, "Ты уже подписан на мою рассылку!") elif msg == "отказаться от рассылки": if str(user_id) in open('id.txt', 'r').read(): id = open('id.txt', 'r').readlines() f = open('id.txt', 'w') for line in id: if line != str(user_id) + "\n": f.write(line) f.close() self.send_msg(user_id, "Я убрал тебя из рассылки") else: self.send_msg( user_id, "Чтобы отказаться от рассылки, нужно сначала на нее подписаться, дубина" ) elif msg in Rasp.dayWeek: self.send_msg(user_id, Rasp.weekday(msg)) elif msg in "".join(Rasp.teachers).lower().split(" "): self.send_msg(user_id, Rasp.teacher(msg)) elif msg == "преподаватели": self.send_msg( user_id, "Напиши мне его фамилию или предмет, который он ведет") elif msg == "show": self.send_msg(user_id, open('id.txt', 'r').read()) elif msg == '0': self.send_msg(user_id, date) print("-------------------")
from random import choice from points import add_points import Keyboard import weather if not isdir(join(expanduser('~'), '.klb')): mkdir(join(expanduser('~'), '.klb')) if not os.getenv("SLAVE"): house = choice(["Ravenclaw", "Gryffindor", "Slytherin", "Hufflepuff", "Squib", "Durmstrang"]) add_points(house, 1) if house == "Hufflepuff": print("1 point to "+house+"! GO PUFFS!") else: print("1 point to "+house+"!") log_setup.read_from_file() Keyboard.start_keyboard_thread() Keyboard.subscribe(ceefax.name_page_handler) weather_thread = weather.weatherThread() weather_thread.start() while True: ceefax.loop_manager.set_weather_thread(weather_thread) ceefax.loop_manager.current()
from Difficulty import * from restartGame import * #-----------------------Main D = Difficulty() scene = canvas(title="my game", width=800, height=600, center=vector(0, 12, 20), userzoom=False, userspin=False, autoscale=False) P = Player() K = Keyboard() L = FloorList() restartGame(D, P, L, scene) dt = 0.01 t = 0 dv = 0.2 while (True): rate(60) K.checkKeyboard(P, D, L, scene) P.update(L, D, scene) L.checkIfdelete(D) for F in L: F.update(D)
def back_button_handler(message): """Back button, returns to main menu""" chat_id = message.chat.id bot.send_message(chat_id, "Main menu⬇", reply_markup=Keyboard.main_menu_keyboard())
from Bluetooth import * from Gamepad import * from Keyboard import * ch = 0 while ch==0: print 'press 1 to emulate keyboard' print 'press 2 to emulate gamepad' ch = raw_input("Press any key from menu: ") if ch == '1': bt = Bluetooth("sdp_record_kbd.xml","000540","BT\ Keyboard") bt.listen() kb = Keyboard() kb.event_loop(bt) elif ch=='2': bt = Bluetooth("sdp_record_gamepad.xml","000508", "BT\ Gamepad") bt.listen() gp = Gamepad() gp.event_loop(bt) else: ch = 0 print('Please select from menu')
def run(): print '--> mission Intercept The Sabateurs' if not ship.enableDefense(): return False if not drones.launchSmall(): return False overview.seekAndDestory() if not drones.back(): return False ship.enableAfterburn() if not overview.activateAccelerationGate(): return False # pocket 1 # main enemies are 90km away # approach for 85 secs # mean while clean up nearby enemy drones.launchSmall() if not overview.switchTo('battle'): return False if not overview.lockEnemy(20): return False ship.fireOnce() if not overview.lockTarget('transport', 1): return False ship.enableAfterburn() ship.approachFor(85) # wait for stop begin = time.time() while time.time() - begin < 20: ship.stop() key.pressEx(sc.Unlock) mouse.moveToP(panel.center(panel.Drones)) mouse.wheel(-100) while findAtDrones('fighting'): time.sleep(10) drones.back() # use sentry to destory all the smalls for i in range(6): overview.lockTarget('s', 1) drones.launchSentry() begin = time.time() while overview.lockTarget('s', 1) and time.time() - begin < 130: ship.fireOnce() drones.engage() drones.back() # do the rest ship.fireOnce() drones.launchSmall() overview.seekAndDestory() while not overview.pickCargo(): pass drones.back() print '<-- mission Intercept The Sabateurs\n' return True
#!/usr/bin/env python #coding=utf-8 import rospy import Keyboard if __name__ == "__main__": rospy.init_node("keyboard_node", anonymous=True) rate = rospy.Rate(100) #Start keyboard publisher keyboard_publisher = Keyboard.Keyboard() rospy.loginfo("Keyboard_publisher_node started") while (not rospy.is_shutdown()): rate.sleep() keyboard_publisher.stop() rospy.loginfo("Keyboard_publisher_node stopped")
def __init__(self, path_to_pattern, path_to_screenshots='', no_screenshots=False, DEBUG=False): if DEBUG: self.keyboard = Keyboard.KeyboardTest() else: self.keyboard = Keyboard.MouseAndKeyboard() self.use_login = False self.last_login = '' self.new_login_delay = 0 self.check_password = False self.use_screenshot = False self.bruteforce = False self.actions_array = [] self.delay = 100 self.wait = None if path_to_screenshots != '' and os.path.isdir( path_to_screenshots) is False: os.system("mkdir -p " + path_to_screenshots) self.screenshots = path_to_screenshots for line in open(path_to_pattern): if line[0] != '#': #Add the line to the array if line.rstrip().lower() == "screenshot": if no_screenshots is False: self.actions_array.append(line.rstrip()) else: self.actions_array.append(line.rstrip()) #import WOL if needed if line.rstrip().lower().split(' ')[0] == 'wol': import WOL #Var in order to check if pattern is good with command line self.use_login = self.use_login or line.rstrip().lower( ) == "login" or line.rstrip().lower().split(' ')[0] == "login" self.check_password = self.check_password or line.rstrip( ).lower() == "password" self.use_screenshot = self.check_password or line.rstrip( ).lower() == "screenshot" #Check for login delay if line.rstrip().lower().split(' ')[0] == "login" and len( line.rstrip().lower().split(' ')) == 2: self.new_login_delay = line.rstrip().lower().split(' ')[1] #Check for delaypassword if line.rstrip().lower().split(' ')[0] == "delaypassword": self.delay = int(line.rstrip().lower().split(' ')[1]) #Check for wait if line.rstrip().lower().split(' ')[0] == "wait": if len(line.rstrip().split(' ')) != 3: print "Wait instruction is not correct: wait file attempt" sys.exit(1) if path_to_pattern.rpartition('/')[0] != '': wait_file = path_to_pattern.rpartition( '/')[0] + '/' + line.rstrip().split(' ')[1] else: wait_file = line.rstrip().split(' ')[1] if os.path.isfile(wait_file) is False: print "Wait function in " + path_to_pattern + " is not correct" sys.exit(1) self.wait = Action(wait_file, path_to_screenshots, no_screenshots, DEBUG) self.attempt = int(line.rstrip().lower().split(' ')[2]) #Check for bruteforce if line.rstrip().lower().split(' ')[0] == "bruteforce": self.bruteforce = True #add error if no size #key: bruteforce charset (numeric, alphaLower, alphaUpper, alpha, alphaNumericLower, alphaNumericUpper, alphaNumeric) sizemin-sizemax #one size possible line_split = line.rstrip().lower().split(' ') self.bruteforce_charset = line_split[1].lower() if len(line_split[2].split('-')) == 2: self.bruteforce_size_start = int( line_split[2].split('-')[0]) self.bruteforce_size_stop = int( line_split[2].split('-')[1]) else: self.bruteforce_size_start = int(line_split[2]) self.bruteforce_size_stop = int(line_split[2]) if self.bruteforce_size_stop > 6: print "Error, bruteforce size is too high" sys.exit(1) if no_screenshots is True: self.use_screenshot = False #Check if pattern is good with command line if self.check_password and self.bruteforce: print "Error, cannot use a password and bruteforce" sys.exit(1)
# move the sphere relative (10,-5,0) to the control point p = Placer.createPlacer("Sphere Mover", s) p.src = V p.x = "sx+10" p.y = "sy-5" # rotate the cube with rotation arc 20*sx along the default z-axis p2 = Placer.createPlacer("Box Rotator", b) p2.src = V p2.x = "-50" p2.y = "-5" p2.arc = "20*sx" # rotate the donat with rotation arc 10*sy along the x-axis p3 = Placer.createPlacer("Torus Rotator", t) p3.src = V p3.x = "50" p3.y = "0" p3.arc = "10*sy" p3.RotAxis = FreeCAD.Vector(1, 0, 0) # SENSOR # kb = Keyboard.createKeyboard("Keybord", V) # start up kb.ViewObject.Proxy.edit() App.activeDocument().recompute() Gui.SendMsgToActiveView("ViewFit")
def __init__(self): # Create array of keys self.keys = [ Keyboard.Key(20, Song.Note(Song.Position.D, Song.Octave.THREE)), Keyboard.Key(21, Song.Note(Song.Position.D_SHARP, Song.Octave.THREE)), Keyboard.Key(22, Song.Note(Song.Position.E, Song.Octave.THREE)), Keyboard.Key(23, Song.Note(Song.Position.F, Song.Octave.THREE)), Keyboard.Key(24, Song.Note(Song.Position.F_SHARP, Song.Octave.THREE)), Keyboard.Key(25, Song.Note(Song.Position.G, Song.Octave.THREE)), Keyboard.Key(26, Song.Note(Song.Position.G_SHARP, Song.Octave.THREE)), Keyboard.Key(27, Song.Note(Song.Position.A, Song.Octave.THREE)), Keyboard.Key(17, Song.Note(Song.Position.A_SHARP, Song.Octave.THREE)), Keyboard.Key(16, Song.Note(Song.Position.B, Song.Octave.THREE)), Keyboard.Key(13, Song.Note(Song.Position.C, Song.Octave.THREE)), Keyboard.Key(6, Song.Note(Song.Position.C_SHARP, Song.Octave.THREE)), Keyboard.Key(5, Song.Note(Song.Position.D2, Song.Octave.THREE)) ] # Create array of speakers self.speakers = [ Keyboard.Speaker(12), Keyboard.Speaker(18), Keyboard.Speaker(19) ] # Initialize components self.recorder = KeyRecord.KeyRecord(pin=4) self.playback = KeyPlayback.KeyPlayback(self.speakers) # Initialize keyboard and add its listeners self.keyboard = Keyboard.Keyboard(self.keys, self.speakers) self.keyboard.addListener(OctaveSetter.OctaveSetter()) self.keyboard.addListener(self.recorder, Keyboard.Listener.Order.LAST)
def approach(): print '--> approaching target' key.pressEx(sc.Approach) print '<-- approaching target\n' return True
def enableAfterburn(): print '--> enable afterburn' key.pressEx(sc.MiddleSlot1) print '<-- enable afterburn\n' return True
def autopilot(): print '--> autopilot' overview.switchTo('pilot') while True: print 'try to find target stargate or station' finded = '' result = None for retry in range(3): print 'try: ' + str(retry + 1) result = findAtOverview('target_station', 0.2) if result: print 'station finded' finded = 'station' break result = findAtOverview('target_star_gate', 0.2) if result: print 'stargate finded' finded = 'gate' break x, y = panel.center(panel.Overview) y += random.random() * 200 - 100 mouse.leftClickAt(x, y) mouse.wheel(-12) mouse.moveToP(panel.center(panel.Full)) if finded == '': print "can't find any waypoint" print '<-- autopilot\n' return False if finded == 'station': print 'docking...' mouse.leftClickAtP(result) key.pressEx(sc.Activate) print 'wait until entering station' begin = time.time() result = findAtProgressBar('entering_station', 0.1) while not result and time.time() - begin < 80: result = findAtProgressBar('entering_station', 0.1) time.sleep(0.1) if result: print 'entering station' time.sleep(4) print '<-- autopilot\n' return True if finded == 'gate': print 'jump...' mouse.leftClickAtP(result) key.pressEx(sc.Activate) print 'wait until entering space' begin = time.time() result = findAtProgressBar('entering_space', 0.1) while not result and time.time() - begin < 80: result = findAtProgressBar('entering_space', 0.1) time.sleep(0.1) if result: print 'entering space' time.sleep(3)