def mouse_routine(): mouse = Mouse(sleep=1) mouse.get_position() mouse.move(10, 10) mouse.double_click() mouse.set_position(200, 400) mouse.click()
class MazeDisplay: """Controls the pygame portion of a maze.""" def __init__(self, maze, window): """Set up the game""" pygame.key.set_repeat(50) window.fill((0, 0, 0)) self._solving = False self._solution = [] self.window = window self.maze = maze self.maze.generate_maze() self.mouse = Mouse(maze) self.mouse_image = pygame.transform.scale( pygame.image.load("mouse.png"), (20, 20)) self.cheese_image = pygame.transform.scale( pygame.image.load("cheese.png"), (20, 20)) self.victory = False self.score_box = MazeDisplay.ScoreBox(pygame.font.Font(None, 30)) self.make_board() def run(self): """Start the main loop.""" self.running = True while self.running: self.update() self.check_events() def update(self): """Update objects on the screen.""" self.update_mouse() self.update_board() self.window.blit( pygame.transform.scale(self.score_box.surface, (self.score_box.surface.get_width(), 20)), (0, 0)) self.check_victory() #self.window.blit(self.base_board, (0, 0)) pygame.display.flip() def update_board(self): """Blits the board.""" board = self.base_board.copy() if not self.victory: board.blit(self.cheese_image, (self.maze.goal[0] * 20, self.maze.goal[1] * 20)) board.blit( pygame.transform.rotate(self.mouse_image, 90 * self.mouse.facing), (20 * self.mouse.pos[0], 20 * self.mouse.pos[1])) self.window.blit( pygame.transform.scale( board, (self.window.get_width(), self.window.get_height() - 20)), (0, 20)) def update_mouse(self): """Moves the mouse.""" if not self._solution: if self.mouse.pos == self.maze.start: self._solution = self.mouse.breadth_first_solve()[::-1] else: self._solving = False if self._solving: if pygame.time.get_ticks() - self._solve_time > 50: self.mouse.move(self._solution.pop()) self._solve_time = pygame.time.get_ticks() def check_victory(self): """Checks and handles victory conditions.""" if self.mouse.pos == self.maze.goal: self.victory = True if self.victory: self.score_box.increment() self.maze.generate_maze() self.mouse.pos = self.maze.start self.make_board() self.victory = False def make_board(self): self.base_board = pygame.Surface( (self.maze.size[0] * 20, self.maze.size[1] * 20)) for col in range(self.maze.size[0]): for row in range(self.maze.size[1]): if self.maze.get_cell((col, row)): cell_color = (150, 150, 150) else: cell_color = (0, 0, 0) pygame.draw.rect(self.base_board, cell_color, pygame.Rect(20 * col, 20 * row, 20, 20)) def check_events(self): """Check for user input""" for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.running = False if not self._solving: if event.key == pygame.K_UP: self.mouse.move(Mouse.NORTH) elif event.key == pygame.K_DOWN: self.mouse.move(Mouse.SOUTH) elif event.key == pygame.K_LEFT: self.mouse.move(Mouse.WEST) elif event.key == pygame.K_RIGHT: self.mouse.move(Mouse.EAST) elif event.key == pygame.K_INSERT: self.maze.generate_maze() self.mouse.pos = self.maze.start self.make_board() self.score_box.reset() if event.key == pygame.K_s: self._solution = self.mouse.breadth_first_solve()[::-1] self._solve_time = pygame.time.get_ticks() self._solving = True else: if event.key != pygame.K_s: self._solution = [] class ScoreBox(TextBox): def __init__(self, font, default_text="Score: 0", antialias=True, color=(255, 255, 255), background=(0, 0, 0)): self.score = 0 super(MazeDisplay.ScoreBox, self).__init__(font, default_text, antialias, color, background) def increment(self): self.score += 1 self.set_text(self.score) def reset(self): self.score = 0 def set_text(self, score): super(MazeDisplay.ScoreBox, self).set_text("Score: " + str(self.score))
mouse.action.omniscientBoard = mouse.board def altMove(self): position = self.forwardCoordinates() self.x = position[0] self.y = position[1] print mouse.printBoard() commands = ('w','a','s','d','b', 'r', 'q','p', 'export','xy') while(True): command = raw_input("b for bottom wall, r for right wall, export for export, read for read in:") if command == 'q': break else: if command == 'w': mouse.move() elif command == 'a': mouse.turnLeft() elif command == 's': mouse.moveBack() elif command == 'd': mouse.turnRight() elif command == 'p': print mouse.AStarSearch() elif command == 'b': mouse.board.addBound(mouse.x, mouse.y, 2) elif command == 'r': mouse.board.addBound(mouse.x, mouse.y, 1) elif command == 'export': mouse.board.save() elif command == "read":
port = bluetooth.PORT_ANY serverSocket.bind(("", port)) serverSocket.listen(1) port = serverSocket.getsockname()[1] bluetooth.advertise_service(serverSocket, "Mouse", service_id, service_classes, profiles) global inputSocket inputSocket, address = serverSocket.accept() print "connected" def close(): inputSocket.close() serverSocket.close() setup() # i = input() while True: input = inputSocket.recv(1024) data = bytearray(input) # for b in data : # print b x = int(data[0]) y = int(data[1]) mbot.move(x, y) print x, y close() # mbot.move(10,10)
class Location(object): def __init__(self, x, y, title="New Location"): self.title = title self.mouse = Mouse() self.keyboard = Keyboard() try: self.x = int(x) self.y = int(y) self._is_mouse_down = False logger.debug( 'New Location with name "{name}" created ({x}, {y})'.format( name=self.title, x=self.x, y=self.y)) except: raise FailExit('Incorect Location class constructor call:' '\n\tx = {x}\n\ty = {y}\n\ttitle= %{title}'.format( x=x, y=y, title=title)) def __str__(self): return 'Location ({x}, {y})'.format(x=self.x, y=self.y) @property def coordinates(self): return self.x, self.y def mouse_move(self, delay=0): self.mouse.move(self.x, self.y, delay) logger.debug('Mouse moved to ({x}, {y})'.format(x=self.x, y=self.y)) def offset(self, dx, dy): if isinstance(dx, int) and isinstance(dy, int): return Location(self.x + dx, self.y + dy) else: raise FailExit('Location.offset: incorrect offset values') def above(self, dy): if isinstance(dy, int) and dy >= 0: return Location(self.x, self.y - dy) else: raise FailExit('Location.above: incorrect value') def below(self, dy): if isinstance(dy, int) and dy >= 0: return Location(self.x, self.y + dy) else: raise FailExit('Location.below: incorrect value') def left(self, dx): if isinstance(dx, int) and dx >= 0: return Location(self.x - dx, self.y) else: raise FailExit('Location.left: incorrect value') def right(self, dx): if isinstance(dx, int) and dx >= 0: return Location(self.x + dx, self.y) else: raise FailExit('Location.right: incorrect value') def click(self, after_click_delay=0): self.mouse.click(self.x, self.y, after_click_delay) logger.debug('mouse left click in ({x}, {y})'.format(x=self.x, y=self.y)) def mouse_down(self): self.mouse.key_down(self.x, self.y) logger.debug('mouse down in ({x}, {y})'.format(x=self.x, y=self.y)) def mouse_up(self): self.mouse.key_up(self.x, self.y) logger.debug('mouse up in ({x}, {y})'.format(x=self.x, y=self.y)) def right_click(self, after_click_delay=0): self.mouse.right_click(self.x, self.y, after_click_delay) logger.debug('mouse right click in ({x}, {y})'.format(x=self.x, y=self.y)) def double_click(self, after_click_delay=0): self.mouse.double_click(self.x, self.y, after_click_delay) logger.debug('mouse double click in ({x}, {y})'.format(x=self.x, y=self.y)) def scroll(self, direction=1, count=1, click=True): # direction: # 1 - forward # -1 - backward for _ in range(0, int(count)): self.mouse.scroll(self.x, self.y, direction, click) logger.debug( 'scroll in ({x}, {y}) {count} times, {dir_} direction'.format( x=self.x, y=self.y, count=count, dir_='forward' if direction == 1 else 'backward')) def drag_to(self, *dest_location): delay = DRAGnDROP_MOVE_DELAY if len(dest_location) == 1 and isinstance(dest_location[0], Location): (dest_x, dest_y) = (dest_location[0].x, dest_location[0].y) elif len(dest_location) == 2: try: (dest_x, dest_y) = (int(dest_location[0]), int(dest_location[1])) except ValueError: raise FailExit('Location.drag_to: incorrect parameters') elif len(dest_location) == 3: try: (dest_x, dest_y) = (int(dest_location[0]), int(dest_location[1])) except ValueError: raise FailExit('Location.drag_to: incorrect parameters') delay = float(dest_location[2]) else: raise FailExit('') self.mouse.drag_to(self.x, self.y, dest_x, dest_y, delay) logger.debug('Mouse drag from (%i, %i) to (%i, %i)' % (self.x, self.y, dest_x, dest_y)) return self def drop(self): self.mouse.drop() logger.debug('Mouse drop') def dragndrop(self, *dest_location): self.drag_to(*dest_location) self.drop() return self def type(self, text, modifiers=None, click=True, click_type_delay=DELAY_BETWEEN_CLICK_AND_TYPE): log = 'Typed "{}"'.format(text) log += ' with modifiers "{}"'.format( modifiers) if modifiers is not None else '' if click: self.click(after_click_delay=click_type_delay) self.keyboard.type_text(str(text), modifiers) logger.info(log) def enter_text(self, text, modifiers=None, click=True, click_type_delay=DELAY_BETWEEN_CLICK_AND_TYPE): if click: self.click(after_click_delay=click_type_delay) self.keyboard.type_text('a', 'CTRL') time.sleep(click_type_delay) self.keyboard.type_text(str(text), modifiers)
def modified_pledge(occupancy_grid, start_position, end_position): maze = Labyrinth(occupancy_grid, start_position, end_position) rover = Mouse(maze) while rover.has_reached_exit() == False: rover.move() return rover.path, rover.infinite_loop
class MiningBot: def __init__(self): self.mouse = Mouse() self.keyboard = Keyboard() self.screen = Screen() def start(self): while True: self.warp_to_system(self.get_system()) if not self.belts_exist(): continue self.warp_to_belt() while True: if not self.asteroids_exist('ore'): break if self.mine() == 'full': self.unload() break def warp_to_system(self, name): self.set_destination(name) self.toggle('autopilot') while self.is_in_autopilot(): time.sleep(10) def warp_to_belt(self): self.select_hotspot() self.select_image('warp_button') time.sleep(60) def mine(self): self.approach() self.lock() self.toggle('miners') while True: time.sleep(10) if not self.is_locked(): return 'depleted' if self.is_full(): return 'full' def unload(self): self.warp_to_system('home') time.sleep(10) for ore in ['veldspar', 'dense_veldspar', 'concentrated_veldspar']: rect = self.screen.locate(ore, 0.9) if (rect != None): self.mouse.move_to_rect(rect) x, y, w, h = rect x -= 400 rect = x, y, w, h self.mouse.drag_to_rect(rect, 'left') self.undock() def approach(self): self.select_hotspot() self.select_image('approach_button') time.sleep(60) def undock(self): self.select_image('undock_button') while self.is_in_station(): time.sleep(10) def lock(self): self.select_image('lock_button') time.sleep(10) def set_destination(self, name): rect = self.screen.locate(name + '_system', 0.9) if rect == None: raise ValueError('Invalid destination: ' + name) self.mouse.click_rect(rect, 'right') self.mouse.move(30, 42) self.mouse.click('left') def change_overview(self, tab): rect = self.screen.locate(tab + '_overview') self.mouse.click_rect(rect, 'left') def toggle(self, module): if module == 'autopilot': self.select_image('autopilot_off') elif module == 'miners': for index in [1, 2]: self.keyboard.press('f' + str(index)) else: raise ValueError('Invalid module: ' + module) def select_hotspot(self): self.mouse.click_point(1597, 195, 'left') time.sleep(1) def select_image(self, name): rect = self.screen.locate(name) self.mouse.click_rect(rect, 'left') time.sleep(1) self.mouse.move_to_point(1000, 500) time.sleep(1) def belts_exist(self): self.change_overview('belts') rect = self.screen.locate('asteroid_belt', 0.85) if rect == None: return False return True def asteroids_exist(self, type): self.change_overview('asteroids') if type not in ['ore', 'ice']: raise ValueError('Invalid asteroid type: ' + type) for size in ['large', 'medium', 'small']: rect = self.screen.locate(size + '_' + type + '_asteroid', 0.9) if rect != None: return True return False def get_system(self): return 'mine' def is_in_space(self): if self.screen.locate('autopilot_off', 0.9) == None: return False return True def is_in_station(self): return not self.is_in_space() def is_in_autopilot(self): if self.screen.locate('autopilot_on', 0.98) == None: return False return True def is_locked(self): if self.screen.locate('lock', 0.9) == None: return False return True def is_full(self): if self.screen.locate('cargo_full', 0.98) == None: return False return True
from mouse import Mouse jerry = Mouse("Jerry", 3, 5) print("Call move() method") jerry.move() print("\n") print("Call showInfo() method") jerry.showInfo()