Esempio n. 1
0
 def __init__(self, gui):
     Keys.__init__(self)
     Mouse.__init__(self)
     # tkinter
     self.root = gui
     # self.root.withdraw()
     # parser
     self.parser = ArgumentParser()
     self.configure_parser()
     self.args = self.parser.parse_args()
     # general stuff
     self.firefox = True
     self.msg = 'Nothing'
     self.__link_tabs = 0
     self.link_list = None
     self.wait_time = 1.5
     self.raid_wait = 0.45
     self.a = 0.1
     self.is_sitter = False
     # village
     self.villages = None
     self.read_all_str()
     self.n_villages = len(self.villages)
     self.add_stat_info()
     self.Production = self.init_production()
     # self.print_village_overview()
     # raids
     self.units = {0: 'Clubswinger', 1: 'Scout', 2: 'Ram', 3: 'Chief', 4: 'Spearman', 5: 'Paladin', 6: 'Catapult', 7: 'Settler', 8: 'Axeman', 9: 'Teutonic Knight', 10: 'Hero'}
     self.raid_info = self.get_raid_info()
     # go back to the terminal
     self.press_alt_tab()
Esempio n. 2
0
 def __init__(self, screen_length, screen_width):
     self.things = {}
     self.thing_index = 0
     self.screen_length = screen_length
     self.screen_width = screen_width
     self.background_color = (0, 0, 0)
     self.mouse = Mouse()
Esempio n. 3
0
class Shwabe(object):
    def __init__(self):
        self.camera = Camera()
        self.processor = ImageProcessor()
        # self.mouse = Mouse(self.camera.shape[:2])
        self.mouse = Mouse((480, 640))
        self.brain = MainBrain()
        # self.mouse = Mouse(self.camera.get_camera_view()[:2])

    def main_loop(self):
        while True:
            input_frame = self.camera.get_frame()
            # print("===========", input_frame.shape)
            self.mouse.update_view_size(input_frame.shape)
            # self.processor.extract_morph_from_img(input_frame)
            # center = self.processor.draw_circle()
            # if center:
            #     self.mouse.move(center)
            # self.processor.draw_line()
            # self.processor.draw_windows()

            masked_image = self.processor.extract_mask(input_frame)

            self.brain.find_contours(masked_image)
            self.brain.find_defects_point()

            self.brain.draw_circle()
            # self.brain.draw_line()

            # self.brain.move_stats
            self.mouse.search_trigger(self.brain.move_stats,
                                      self.brain.move_cap,
                                      self.brain.movement_delta)
            self.brain.show_windows()
Esempio n. 4
0
 def setUp(self, data):
     self.mice = []
     self.totalTime = 0
     for mouse in data.keys():
         newMouse = Mouse(mouse)
         newMouse.setUp(data[mouse])
         self.mice.append(newMouse)
Esempio n. 5
0
    def __init__(self):
        self.ir = ImageRecognition()
        self.tr = TextRecognition()
        self.db = Database()
        self.mouse = Mouse()

        self.clear_minigame()
        self.button_map_init()
Esempio n. 6
0
 def _create_mouse(self, mouse_number, row_number):
     """Create a mouse and put it in the row"""
     mouse = Mouse(self)
     mouse_width, mouse_height = mouse.rect.size
     mouse.x = mouse_width + 2 * mouse_width * mouse_number
     mouse.rect.x = mouse.x
     mouse.rect.y = mouse.rect.height + 2 * mouse.rect.height * row_number
     self.mice.add(mouse)
Esempio n. 7
0
 def __init__(self, file_dir):
     self.FileDir = file_dir
     self.Band = self.get_band()
     self.Album = self.get_album()
     self.ExcludeTypes = ['ini', 'jpg', 'txt']
     self.Exclude = [self.Band, self.Album, '(mp3co.biz)']
     self.Songs = self.load_songs()
     Keys.__init__(self)
     Mouse.__init__(self)
Esempio n. 8
0
 def __init__(self, ratio=1):
     self.RUN = True
     self.TOGGLE = False
     self.vision = Vision(ratio=ratio)
     self.keyboard = Keyboard(sleep=1)
     self.KEYCODES = {1: 18, 2: 19, 3: 20, 4: 21, 5: 23}
     self.potions_box = {"top": 850, "left": 1920, "width": 500, "height": 200}
     self.menu_box = {"top": 300, "left": 1920 + 680, "width": 320, "height": 260}
     self.mouse = Mouse()
Esempio n. 9
0
 def __init__(self, window_class, window_title):
     # hwnd = win32gui.FindWindow('WeChatMainWndForPC', '微信')
     hwnd = win32gui.FindWindow(window_class, window_title)
     left, top, right, bottom = win32gui.GetWindowRect(hwnd)
     self.hwnd = hwnd
     self.screen_rect = [left, top, right, bottom]
     self.region = (left, top, right - left, bottom - top)
     logger.launch_logger('绑定窗口成功' + str(self.screen_rect))
     self.relative_move_to(100, 100)
     Mouse.right_click()
Esempio n. 10
0
 def __init__(self):
     self.autos = []
     self.events = []
     self.generation = 0
     self.dt = 0
     self.top_auto = None
     self.slow_car_removed = False
     self.learning_rate = LEARNING_RATE
     self.viewer = TargetViewer(self)
     self.mouse = Mouse(self)
     self.track = RaceTrack(self)
     self.text = Text("Generation : 0")
     self.start_time = pygame.time.get_ticks()
     self.addNewAutos(num_car)
Esempio n. 11
0
class Window:
    def __init__(self, hwnd):
        self.hwnd = hwnd
        self.mouse = Mouse(hwnd)
        self.imp = ImageProcess(hwnd)

    def click(self, pos):
        self.mouse.click(pos)

    def find_img(self, img_name, accuracy=0.9):
        return self.imp.find_img(img_name, accuracy)

    def find_all_imgs(self, img_name, accuracy=0.9):
        return self.imp.find_all_imgs(img_name, accuracy)
Esempio n. 12
0
 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))
Esempio n. 13
0
 def __init__(self,screen_length,screen_width):
     self.things = {}
     self.thing_index = 0
     self.screen_length = screen_length
     self.screen_width = screen_width
     self.background_color = (0,0,0)
     self.mouse = Mouse()
Esempio n. 14
0
 def __init__(self, data, cellID):
     self.id = cellID
     self.mouseData = Mouse()  # To be filled later manually by user
     self.pipette = Pipette()  # To be filled later manually by user
     self.stims = data['Stims'].keys()  # TODO: document
     self.recordings = self._parseRec(data)
     self.__attributize()
Esempio n. 15
0
    def __init__(self):
        self.viewer = None

        self.low = np.array([self.XMIN, self.YMIN, self.ANGLE_MIN, 0])
        self.high = np.array([self.XMAX, self.YMAX, self.ANGLE_MAX, 100])

        self.action_space = spaces.Box(np.array([-self.TURN_ANGLE]),
                                       np.array([self.TURN_ANGLE]))
        self.observation_space = spaces.Box(self.low, self.high)

        self._reference_trajectory = [
            (np.cos(deg) * 150 + 300, np.sin(deg) * 150 + 300)
            for deg in [np.pi * i / 30.0 for i in range(61)]
        ]
        shape_fn = lambda x, y: abs((x - 300)**2 +
                                    (y - 300)**2 - 150**2) < 2000
        self._mouse = Mouse(down=True)
        self._cloth = ShapeCloth(shape_fn,
                                 self._mouse,
                                 width=30,
                                 height=30,
                                 dx=16,
                                 dy=16)
        self.cloth_experiment = Simulation(self._cloth, render=0, init=50)

        self._seed()
        self.reset()
Esempio n. 16
0
def single_gbfs(filename):
    maze, start, goals = file_read(filename)
    graph = state_representation(maze)
    mouse = Mouse(start)

    visited = set()
    path_dict = {}
    pqueue = queue.PriorityQueue(maxsize=1000000)
    pqueue.put((0, start))
    count = 0
    goal = goals[0]
    while pqueue:
        element = pqueue.get()
        vertex = element[1]
        visited.add(vertex)
        if vertex == goal:
            position = vertex
            path = [vertex]
            while position != start:
                position = path_dict[position]
                path.append(position)
            break
        for neighbor in set(graph.neighbors(vertex)) - visited:
            count += 1
            visited.add(neighbor)
            path_dict[neighbor] = vertex
            pqueue.put((m_heuristic(neighbor, goal), neighbor))

    mouse = transition_function(mouse, path[::-1], goals)
    solution(maze, path[::-1], count)
    return mouse
Esempio n. 17
0
def single_bfs(filename):
    maze, start, goals = file_read(filename)
    graph = state_representation(maze)
    mouse = Mouse(start)

    visited, queue = [], [start]
    path_dict = {}
    count = 0
    while queue:
        vertex = queue.pop(0)
        visited.append(vertex)
        neighborhood = graph.neighbors(vertex)
        for neighbor in neighborhood:
            count += 1
            if neighbor not in visited and neighbor not in queue:
                path_dict[neighbor] = vertex
                queue.append(neighbor)
            if neighbor in goals:
                position = neighbor
                path = [neighbor]
                while position != start:
                    position = path_dict[position]
                    path.append(position)

    mouse = transition_function(mouse, path[::-1], goals)
    solution(maze, path[::-1], count)
    return mouse
Esempio n. 18
0
def single_dfs(filename):
    maze, start, goals = file_read(filename)
    graph = state_representation(maze)
    mouse = Mouse(start)

    visited, stack = set(), [start]
    path = []
    path_dict = {}
    count = 0
    while stack:
        vertex = stack.pop()
        if vertex in goals:
            position = vertex
            path.append(vertex)
            while position != start:
                position = path_dict[position]
                path.append(position)
        count += 1
        if vertex in visited:
            continue
        visited.add(vertex)
        neighborhood = graph.neighbors(vertex)
        for neighbor in neighborhood:
            if neighbor not in visited:
                path_dict[neighbor] = vertex
                stack.append(neighbor)

    mouse = transition_function(mouse, path[::-1], goals)
    solution(maze, path[::-1], count)
    return mouse
Esempio n. 19
0
 def randomSpawn(self):
     #Spawner musene
     for i in range(170):
         if self.MouseNumber < 150:
             x = random.randrange(1, 19)
             y = random.randrange(1, 19)
             currentMouseSlot = self.grid[x][y]
             if currentMouseSlot.num_mice < 2:
                 currentMouseSlot.addAnimal("mouse")
                 self.MouseNumber += 1
                 self.allMices.append(Mouse(x, y, 'x'))
     #Spawner uglerne
     for i in range(50):
         if self.numOwels < 2:
             x = random.randrange(1,19)
             y = random.randrange(1,19)
             currentOwlSlot = self.grid[x][y]
             if currentOwlSlot.num_owels == 0:
                 currentOwlSlot.addAnimal("owl")
                 self.numOwels += 1
     #Placere stenene
     for i in range(50):
         if self.rocks < 10:
             x = random.randrange(1,19)
             y = random.randrange(1,19)
             currentRockSpot = self.grid[x][y]
             if currentRockSpot.has_rock == False:
                 currentRockSpot.has_rock = True
                 self.rocks += 1
                 self.currentStoneSlots.append(currentRockSpot)
Esempio n. 20
0
def main():
    ca = Cat('猫咪')
    # ca.eat()
    mou = Mouse('老鼠')
    # mou.eat()
    per = Person()
    per.feedcat(ca)
    per.feedmouse(mou)
Esempio n. 21
0
class World:
    def __init__(self,screen_width,screen_height):
        self.screen_width = screen_width
        self.screen_height = screen_height
        self.background_color = (0,0,0)
        self.mouse = Mouse()
        self.follower = Follower()

    def update(self,time_passed):
        mouse_position = self.mouse.get_position()
        self.mouse.update(time_passed)
        self.follower.update(time_passed,mouse_position)

    def render(self,screen):
        screen.fill(self.background_color)
        self.mouse.render(screen)
        self.follower.render(screen)
Esempio n. 22
0
 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()
Esempio n. 23
0
class World:
    def __init__(self, screen_length, screen_width):
        self.things = {}
        self.thing_index = 0
        self.screen_length = screen_length
        self.screen_width = screen_width
        self.background_color = (0, 0, 0)
        self.mouse = Mouse()

    def set_ball_list(self, n):
        ball_count = n
        balls = []
        for i in range(ball_count):
            radius = randint(15, 30)
            x_pos = randint(0 + radius, self.screen_width - radius)
            y_pos = randint(0 + radius, self.screen_length - radius)
            x_vel = 0
            y_vel = 0
            self.things[self.thing_index] = Ball(
                Vector2(x_pos, y_pos), Vector2(x_vel, y_vel), radius,
                (randint(0, 255), randint(0, 255), randint(0, 255)))
            self.thing_index += 1

    def check_for_collision(self):
        for i in range(self.thing_index):
            b1 = self.things[i]
            for j in range(i):
                b2 = self.things[j]
                if collision.peer_contact(b1, b2):
                    collision.peer_collision(b1, b2)
            collision.manage_wall_contact(b1, self.screen_width,
                                          self.screen_length)
            if collision.mouse_contact(self.mouse, b1):
                collision.mouse_collision(self.mouse, b1)

    def update(self, time_passed):
        for key in self.things.keys():
            self.things[key].update(time_passed)
        self.mouse.update(time_passed)
        self.check_for_collision()

    def render(self, screen):
        screen.fill(self.background_color)
        for key in self.things.keys():
            self.things[key].render(screen)
        self.mouse.render(screen)
Esempio n. 24
0
 def track_motion(self):
     """starts tracking the motion of a mouse. (moution?)"""
     with Mouse() as mouse:
         while True:
             try:
                 self.update(mouse)
             except KeyboardInterrupt:
                 break
Esempio n. 25
0
    def register_and_populate(self):
        """
        this method can be run on a Group given that group.name and group.experiment have been assigned
        """
        experiment = self.experiment
        experiment.group_named[
            self.
            name] = self  # register it with its parent experiment indexed by name
        experiment.group_numbered[
            self.number] = self  # register it as indexed by group.number
        experiment.groups.append(self)  # register it in the list of groups

        # self.color = experiment.groupname_to_color_dictionary[self.name]
        # self.marker = experiment.groupname_to_marker_dictionary[self.name]
        self.individual_numbered = {
        }  # the individuals of the group indexed by their number
        self.mouse_numbered = {
        }  # the individuals of the group indexed by mouseNumber
        self.individuals = []  # the list of all the individuals in the group

        for individualNumber, mouseNumber in enumerate(
                experiment.group_name_to_mouse_number_list_dictionary[
                    self.name]):
            M = Mouse()
            M.mouseNumber = mouseNumber  # the true name of a mouse
            M.group = self  # point to its parent
            M.individualNumber = individualNumber  # legacy stuff
            M.add_days_and_register_with_group()  # add mousedays
Esempio n. 26
0
 def create(cls, name):
     if name == 'Mouse':
         return Mouse()
     elif name == 'Dragon':
         return Dragon()
     elif name == 'Snake':
         return Snake()
     else:
         return None
Esempio n. 27
0
 def __init__(self, screen_width, mode, depth, ai_modes, omni):
     # Variable Initiation
     self.screen_size = int(screen_width / 2)
     self.screen = pygame.display.set_mode(
         (self.screen_size, self.screen_size))  # Where the game is shown
     self.gamestate = GameState(mode, self.screen_size / 8, depth, ai_modes,
                                omni)
     self.mouse = Mouse(self.gamestate)
     self.run = True
Esempio n. 28
0
def read_mouse(filename='/dev/input/mice'):
    # http://wiki.osdev.org/Mouse_Input#Mouse_Packet_Info
    with Mouse() as mouse:
        while True:
            try:
                status, dx, dy = mouse.update()
                print('status: {}, dx: {}, dy: {}'.format(status, dx, dy))
            except KeyboardInterrupt:
                break
Esempio n. 29
0
class World:
    def __init__(self,screen_length,screen_width):
        self.things = {}
        self.thing_index = 0
        self.screen_length = screen_length
        self.screen_width = screen_width
        self.background_color = (0,0,0)
        self.mouse = Mouse()
        
    def set_ball_list(self,n):
        ball_count = n
        balls = []
        for i in range(ball_count):
            radius = randint(15,30)
            x_pos = randint(0+radius,self.screen_width-radius)
            y_pos = randint(0+radius,self.screen_length-radius)
            x_vel = 0
            y_vel = 0
            self.things[self.thing_index] = Ball(Vector2(x_pos,y_pos),Vector2(x_vel,y_vel),radius,(randint(0,255),randint(0,255),randint(0,255)))
            self.thing_index += 1
        
    def check_for_collision(self):
        for i in range(self.thing_index):
            b1 = self.things[i]
            for j in range(i):
                b2 = self.things[j]
                if collision.peer_contact(b1,b2):
                    collision.peer_collision(b1,b2)
            collision.manage_wall_contact(b1,self.screen_width,self.screen_length)
            if collision.mouse_contact(self.mouse,b1):
                collision.mouse_collision(self.mouse,b1)

    def update(self,time_passed):
        for key in self.things.keys():
            self.things[key].update(time_passed)
        self.mouse.update(time_passed)
        self.check_for_collision()

    def render(self,screen):
        screen.fill(self.background_color)
        for key in self.things.keys():
            self.things[key].render(screen)
        self.mouse.render(screen)
Esempio n. 30
0
    def display_welcome(self):
        self.loading = True
        start_text = pygame.font.Font(None, 18).render(
                "Begin!", False, (0, 0, 0))
        maze_demo = Maze((9, 9))
        mouse_demo = Mouse(maze_demo)
        mouse_image = pygame.transform.scale(
            pygame.image.load("mouse.png"), (20, 20))
        board_demo = pygame.Surface((180, 180))
        pygame.draw.rect(board_demo, (150, 150, 150),
                pygame.Rect(20, 20, 140, 140))
        for x in range(1, 8):
                for y in range(1, 8):
                    maze_demo.change_cell((x, y))

        while self.loading:
            #demo maze blitting, updating
            self.window.blit(pygame.transform.scale(board_demo,
                    self.window.get_size()), (0, 0))
            board_demo.fill((0, 0, 0))
            pygame.draw.rect(board_demo, (150, 150, 150),
                    pygame.Rect(20, 20, 140, 140))
            board_demo.blit(
                    pygame.transform.rotate(mouse_image,
                        90 * mouse_demo.facing),
                        (20 * mouse_demo.pos[0], 20 * mouse_demo.pos[1]))
            mouse_demo.demo_move()
            #start button
            pygame.draw.rect(board_demo, (0, 200, 0),
                    pygame.Rect(70, 80, 40, 20))
            self.start_mask = pygame.mask.from_threshold(
                    board_demo, (0, 200, 0), (10, 10, 10, 255)).scale((
                            self.window.get_width(),
                            self.window.get_height()))
            pygame.draw.rect(board_demo, (0, 0, 0),
                    pygame.Rect(70, 80, 40, 20), 1)
            board_demo.blit(start_text, (
                    90 - start_text.get_width() / 2,
                    90 - start_text.get_height() / 2))
            #events and flip
            self.check_events()
            pygame.display.flip()
Esempio n. 31
0
	def rodar(self):
		self.mouse = Mouse(self.amb, self.screen, self.local_img, "minion_mouse.png")
		self.menu = Menu(self.amb, self.screen, (400, 25), 50)

		while self.rodando:
			self.screen.fill((0, 0, 0))

			for event in self.amb.event.get():
				if event.type == self.amb.QUIT:
					self.rodando = False

				eventos_mouse = pygame.mouse.get_pressed()

				self.menu.tratar_eventos(self, eventos_mouse)

			self.menu.desenhar()
			self.mouse.desenhar()

			self.amb.display.flip()

		self.amb.quit()
Esempio n. 32
0
File: vis.py Progetto: ebak/xbuild
    def __init__(self, model, pathFormer):
        super(self.__class__, self).__init__()
        self.pathFormer = pathFormer
        self.model = model
        self.setWindowTitle(
            'Boncz Geza dependency graph visualization tool (early alpha).')
        # self.resize(QtGui.QApplication.desktop().size());
        # self.setRenderHints(QtGui.QPainter.Antialiasing | QtGui.QPainter.SmoothPixmapTransform)
        self.mouse = Mouse()

        self.selectedVNode = None
        self.selectedVisEntList = []
        self.scene = QtGui.QGraphicsScene()
        self.nodeLayer, self.slotLabelLayer, self.nodeLabelLayer, self.lineLayer = [
            Layer() for _ in range(4)
        ]
        for layer in self.nodeLayer, self.slotLabelLayer, self.nodeLabelLayer, self.lineLayer:
            self.scene.addItem(layer)
        np = self.nodePopup = NodePopup(self)
        np.deselectAction.setEnabled(False)
        self.buildScene()
Esempio n. 33
0
def voice():
    #mouse = Controller()
    mouse = Mouse()
    r = sr.Recognizer()

    while True:
        debug_print("1")
        with sr.Microphone() as source:                # use the default microphone as the audio source
            debug_print("2")
            r.adjust_for_ambient_noise(source)         # to reduce noise 
            debug_print("3")
            audio = r.listen(source)                   # listen for the first phrase and extract it into audio data
            debug_print("4")

        try:
            print("You said " + r.recognize(audio))    # recognize speech using Google Speech Recognition
            if (r.recognize(audio) == 'hey iclicker left click' or r.recognize(audio) == 'left click'):
                mouse.left_click()
    
            elif (r.recognize(audio) == 'hey iclicker right click' or r.recognize(audio) == 'right click'):
                mouse.right_click()

        except LookupError:                            # speech is unintelligible
            print("Could not understand audio")
            print("left clicking...")
            debug_print("5")
            debug_print("6")
Esempio n. 34
0
 def __init__(self, canvas, osc_player):
     
     self.canvas = canvas    
     self.mouse = Mouse()
     self.osc_player = osc_player
     self.em = EventManager()
     self.em[ButtonPressed] += self.handle_event
    
     # Mouse action 
     self.drag_start_x = 0
     self.drag_start_y = 0
     self.drag_end_x = 0
     self.drag_end_y = 0
Esempio n. 35
0
    def __init__(self,  size=None):
        pygame.init()
        if not size:
            size = SCREEN_SIZE
            
        self.screen = pygame.display.set_mode(size, HWSURFACE|DOUBLEBUF)
        pygame.display.set_caption("DoTT")
   
        self.font = pygame.font.Font('gui/font.ttf', 14) 
        
        self.room = None
        self.actors = {}
        self.player = None
        self.rooms = {}
        self.verb = WALK
        self.mouse = Mouse('gui/cursor.png')
        self.fullscreen = False
        self.message = ''
        self.gui = pygame.image.load('gui/gui.png').convert_alpha()

        # para la gui
        self.j = 0
Esempio n. 36
0
class Game(object):
    def __init__(self,  size=None):
        pygame.init()
        if not size:
            size = SCREEN_SIZE
            
        self.screen = pygame.display.set_mode(size, HWSURFACE|DOUBLEBUF)
        pygame.display.set_caption("DoTT")
   
        self.font = pygame.font.Font('gui/font.ttf', 14) 
        
        self.room = None
        self.actors = {}
        self.player = None
        self.rooms = {}
        self.verb = WALK
        self.mouse = Mouse('gui/cursor.png')
        self.fullscreen = False
        self.message = ''
        self.gui = pygame.image.load('gui/gui.png').convert_alpha()

        # para la gui
        self.j = 0
    
    def add_room(self, room):
        """ Add a room to the list of rooms of the game. All rooms must belong to this dictionary! """
        self.rooms[room.name] = room
        
    def change_room(self, name):
        self.room = self.rooms[name]

    def run(self, screen=None):
        self.quit = 0
        if screen != None: self.screen = screen
        while not self.quit:
            self.loop()

    def loop(self):
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == MOUSEMOTION:
                self.on_mouse_motion()
            elif event.type == MOUSEBUTTONDOWN:
                self.on_mouse_button_down()
            elif event.type == MOUSEBUTTONUP:
                pass
            elif event.type == KEYUP:
                pass
            elif event.type == KEYDOWN:
                if event.key == K_i:
                    print "Inventory:"
                    print self.player.inventory
                if event.key == K_f:
                    pass
                #self.toggle_fullscreen()
                if event.key == K_c:
                    self.verb = CLOSE
                if event.key == K_o:
                    self.verb = OPEN
                if event.key == K_w:
                    self.verb = WALK
                if event.key == K_l:
                    self.verb = LOOK
                if event.key == K_p:
                    self.verb = PICK_UP
                if event.key == K_s:
                    self.verb = PUSH
                if event.key == K_j:
                    if self.j<len(self.player.inventory)-6:
                        self.j = self.j+3
                if event.key == K_k:
                    if self.j>0:
                        self.j = self.j-3
                if event.key == K_d:
                    x, y = self.mouse.get_pos()
                    print "mouse:",  x,  y
                    print "Active room information:"
                    print self.room.rectangles
                    self.room.info()
                    print "Main actor information:"
                    self.player.info()
                else:
                    self.room.on_event(event)

        # FIXME: hay que usar update de la lista de rects que se modificaron: mouse, texto, sprites.
        self.draw()
        x, y = self.mouse.get_pos()
        self.screen.blit(self.mouse.image,
                (x-self.mouse.image.get_width()/2,
                    y-self.mouse.image.get_height()/2))
        pygame.display.update()

    def on_mouse_motion(self):
        x, y = self.mouse.get_pos()
        x -= self.room.camera.x
        y -= self.room.camera.y
        print x, y
        for i in self.room.areas:
            if i.poly.collidepoint(x,y):
                self.message = self.verb + ' ' + i.description
                break
            else:
                self.message = self.verb
               
    def on_mouse_button_down(self):
        x, y = self.mouse.get_pos()
       
        # select the verb
        verbs = {GIVE: Rect(0, 302, 77, 28), PICK_UP: Rect(81, 302, 124, 28), 
                USE: Rect(209, 302, 76, 28), OPEN: Rect(0, 334, 77, 28), 
                LOOK_AT: Rect(81, 334, 124, 28), PUSH: Rect(209, 334, 76, 28),
                CLOSE: Rect(0, 366, 77, 28), TALK_TO: Rect(81, 366, 124, 28), 
                PULL: Rect(209, 366, 76, 28)} 

        for v, r in verbs.items():
            if r.collidepoint(x, y):
                self.verb = v
                return 

        # select an item of the inventory
        rects = [Rect(320, 299, 80, 48), Rect(400, 299, 80, 48), Rect(480, 299, 80, 48), 
                Rect(320, 348, 80, 48), Rect(400, 348, 80, 48), Rect(480, 348, 80, 48)] 

        for r in rects:
            if r.collidepoint(x, y):
                if self.j + rects.index(r) < len(self.player.inventory):
                    print rects.index(r) 
                    print self.player.inventory[self.j + rects.index(r)]

        x -= self.room.camera.x
        y -= self.room.camera.y
     
        for i in self.room.areas:
            if i.poly.collidepoint(x, y):
                if self.verb == WALK:
                    i.on_walk(self)
                    break
                elif self.verb == OPEN:
                    i.on_open(self)
                    break
                elif self.verb == CLOSE:
                    i.on_close(self)
                    break
                elif self.verb == PICK_UP:
                    i.on_pickup(self)
                    break
                elif self.verb == PUSH:
                    i.on_push(self)
                    
        self.verb = WALK
                
    def draw(self):
        """ Draw the entire scene. """
        self.screen.blit(self.room.image, (self.room.camera.x, self.room.camera.y))
        self.screen.fill((0, 0, 0), Rect(0, 283, 640, 112))
        self.screen.blit(self.gui, (0, 300))
        self.screen.blit(self.font.render(self.message,  True, (255, 255, 255)), ((640-len(self.message))/2, 280))
        
        self.draw_gui()
        self.room.draw(self)
   
    def draw_gui(self):
        j = 0
        p = [(320, 299), (400, 299), (480, 299), (320, 348), (400, 348), (480, 348)] 
        for name in self.player.inventory[self.j:]:
            self.screen.blit(self.items[name].image, p[j])
            if j == 5:
                break
            else:
                j = j+1

    def load_items(self):
        self.items = {
                'textbook': Textbook(),
                'help-wanted': HelpWanted(),
                'dime': Dime(),
                'flier': Flier(),
                'funnel': Funnel(),
                'keys': Keys(),
                'booboo-b-gone': BoobooBGone(),
                'bankbook': Bankbook(),
                'coffee': Coffee(),
                'decaf-coffee': DecafCoffee(),
                'fork': Fork(),
                'ink': Ink() }

    def load_doors(self):
        self.doors = {
                'lobby2study': LobbyToStudy(),
                'lobby2basement': LobbyToBasement(),
                'lobby2outside': LobbyToOutside(),
                'lobby2playroom': LobbyToPlayroom(),
                'lobby2secondfloor': LobbyToSecondfloor(),
                'study2lobby': StudyToLobby(),
                'basement2lobby': BasementToLobby(),
                'outside2lobby': OutsideToLobby(),
                'outside2car': OutsideToCar(),
                'car2outside': CarToOutside(),
                'car2water': CarToWater(),
                'water2car': WaterToCar(),
                'playroom2lobby': PlayroomToLobby(),
                'playroom2kitchen': PlayroomToKitchen(),
                'playroom2roof': PlayroomToRoof(),
                'kitchen2laundry': KitchenToLaundry(),
                'kitchen2playroom': KitchenToPlayroom(),
                'laundry2kitchen': LaundryToKitchen(),
                'secondfloor2suite': SecondfloorToSuite(),
                'secondfloor2sad': SecondfloorToSad(),
                'secondfloor2green': SecondfloorToGreen(),
                'secondfloor2lobby': SecondfloorToLobby(),
                'secondfloor2hallway': SecondfloorToHallway(),
                'suite2secondfloor': SuiteToSecondfloor(),
                'sad2secondfloor': SadToSecondfloor(),
                'green2secondfloor': GreenToSecondfloor(),
                'hallway2secondfloor': HallwayToSecondfloor(),
                'hallway2edd': HallwayToEdd(),
                'hallway2edna': HallwayToEdna(),
                'hallway2warehouse': HallwayToWarehouse(),
                'edd2hallway': EddToHallway(),
                'edna2hallway': EdnaToHallway(),
                'warehouse2hallway': WarehouseToHallway(),
                'warehouse2attic': WarehouseToAttic(),
                'attic2warehouse': AtticToWarehouse(),
                'attic2roof': AtticToRoof(),
                'roof2attic': RoofToAttic(),
                'roof2playroom': RoofToPlayroom() }

    def load_rooms(self):
        self.rooms = {
                'lobby': Lobby(),
                'outside': Outside(),
                'basement': Basement(),
                'study': Study(),
                'playroom': Playroom(),
                'secondfloor': Secondfloor(),
                'roof': Roof(),
                'kitchen': Kitchen(),
                'attic': Attic(),
                'suite': Suite(),
                'sad': Sad(),
                'green': Green(),
                'hallway': Hallway(),
                'warehouse': Warehouse(),
                'laundry': Laundry(),
                'edd': Edd(),
                'edna': Edna(),
                'car': Car(),
                'water': Water() }

    def init(self, room_name):
        """ Create the world """ 
        self.load_items()
        self.load_doors()
        self.load_rooms()

        # Add doors in rooms 
        for d in self.doors.values():
            self.rooms[d.room].add_door(d)

        # Add items in rooms
        for i in self.items.values():
            if not i.room == None:
                self.rooms[i.room].add_item(i)

        # Set the room where to start
        self.room = self.rooms[room_name]

    def toggle_fullscreen(self):
        if self.fullscreen:
            self.screen = pygame.display.set_mode(SCREEN_SIZE, HWSURFACE|DOUBLEBUF)
        else:
            self.screen = pygame.display.set_mode(SCREEN_SIZE, FULLSCREEN|HWSURFACE|DOUBLEBUF)
        self.fullscreen = not self.fullscreen
Esempio n. 37
0
class MouseHandler(object):
    
    def __init__(self, canvas, osc_player):
        
        self.canvas = canvas    
        self.mouse = Mouse()
        self.osc_player = osc_player
        self.em = EventManager()
        self.em[ButtonPressed] += self.handle_event
       
        # Mouse action 
        self.drag_start_x = 0
        self.drag_start_y = 0
        self.drag_end_x = 0
        self.drag_end_y = 0
        
    def handle_event(self, event):
        # Get mouse position
        (self.mouse_x, self.mouse_y) = pygame.mouse.get_pos()
        
        # TODO: find better programmatical solution for addition
        # Now you can also draw lines from outside canvas
        self.mouse_x= self.mouse_x-self.canvas.global_x
        self.mouse_y= self.mouse_y-self.canvas.global_y
        
        
        # Check if the event is mouse-related
        if event.type == MOUSEBUTTONDOWN:
            self.mouse.mouse_pressed()
            self.mouse.set_button_pressed(event.button)
                
        elif event.type == MOUSEBUTTONUP:
            self.mouse.mouse_released()
            self.mouse.set_button_pressed(event.button)
        
        self.measure_line()
        # Write out mouse info
        self.write_mouse_info()
    
    def measure_line(self):
        if not self.mouse.dragging and self.mouse.mouse_down and self.mouse.left_button_pressed:
            self.drag_start_x = self.mouse_x
            self.drag_start_y = self.mouse_y
            self.drag_end_x = self.mouse_x
            self.drag_end_y = self.mouse_y
            self.mouse.set_dragging(True)
            
        elif self.mouse.dragging and self.mouse.mouse_down and self.mouse.left_button_pressed:
            self.drag_end_x = self.mouse_x
            self.drag_end_y = self.mouse_y 
            self.canvas.draw_measuring_line((self.drag_start_x,self.drag_start_y),(self.drag_end_x, self.drag_end_y))
            
            # Send x and y dragging values to PD
            # TODO: restrict to canvas borders
            self.osc_player.send_message(self.drag_end_x, "/mouse/x")
            self.osc_player.send_message(self.drag_end_y, "/mouse/y")
            
        elif self.mouse.dragging and not self.mouse.mouse_down and self.mouse.left_button_pressed:
            self.mouse.set_dragging(False)
            self.canvas.draw_line(self.drag_start_x,self.drag_start_y,self.drag_end_x, self.drag_end_y)

    def write_mouse_info(self):
        
        # Build string
        message = "x = %s "\
                  "y = %s"%(self.mouse_x, self.mouse_y)
        
        # If key pressed add that info
        if self.mouse.mouse_down:
            message = message + " %s"%self.mouse.button_pressed

        # Draw Mouse info on canvas
        self.canvas.draw_mouse_info(message,self.mouse.dragging)        
Esempio n. 38
0
        app.x.set(x.value)
        app.y.set(y.value)

        app.master.after(delay, coords_update)

    delay = int(100/frequency)

    app = DemoApp()
    app.master.bind("<Key>", on_key)
    app.master.protocol("WM_DELETE_WINDOW", on_destroy)

    coords_update()
    app.master.mainloop()


if __name__ == "__main__":
    m1 = Mouse.list_connected()[0]

    x = Value('d', 0.0, lock=False)
    y = Value('d', 0.0, lock=False)
    stop_trigger = Value(ctypes.c_bool, False, lock=False)

    mouse_process = Process(target=stream, args=(m1.usb_device.bus, m1.usb_device.address, 200, x, y, stop_trigger))
    app_process = Process(target=launch_app, args=(50, x, y, stop_trigger))

    mouse_process.start()
    app_process.start()

    mouse_process.join()
    app_process.join()
Esempio n. 39
0
#!/usr/bin/env python
from mouse import Mouse
from board import Board
from time import sleep
from controller import Controller
import sys
import rospy

x = 0
y = 0
direction = 1

# can run using python 1 2 3 where it starts at (x,y), direction is left
# if(len(sys.argv) == 1 ):
    # file = sys.arv[0]

rospy.init_node('maze_solver')
board = Board()
board.read("emptyBoard.txt")
mouse = Mouse(x,y,direction,board,1)

mouse.printBoard()



mouse.floodFillToGoal()
mouse.board.save("exploredBoard.txt")
Esempio n. 40
0
import gui.overlay as overlay
from auxiliary import Pt

import windows as win


if __name__ == "__main__":
    pygame.init()

    display = pygame.display.set_mode((800, 600))

    clock = pygame.time.Clock()

    sl.sprite_dir = 'C:\Users\M\Desktop\graphics'
    cursors = sl.load('cursors.xml')
    mouse = Mouse(display, cursors)

    gui = Gui()
    draw_stack = win.WinStack(gui)

    # gui.add(Button(Rect(710, 50, 70, 40), (255, 200, 0)))
    # gui.add(Button(Rect(710, 110, 70, 40), (255, 200, 0)))
    # gui.add(Button(Rect(600, 560, 150, 35), (255, 200, 0)))

    win_bt = Button(Rect(600, 560, 150, 35), pygame.Color('green'))
    win_bt.click = lambda a, b: draw_stack.open(win.TestWindow((100, 100)))
    gui.add(win_bt)

    # overlays = pygame.sprite.RenderUpdates()
    # pygame.display.flip()
Esempio n. 41
0
from mouse import Mouse
from board import Board
import sys

x = 0
y = 0
direction = 0

# can run using python 1 2 3 where it starts at (x,y), direction is left
# if(len(sys.argv) == 1 ):
    # file = sys.arv[0]



board = Board()
board.read()
mouse = Mouse(x,y,direction,board,0, 1)




raw_input('press n to start')
mouse.floodFillToGoal()
Esempio n. 42
0
from mouse import Mouse
from board import Board

b = Board()
mouse = Mouse(0,0,3,b,0)
altfaceWallFunc = lambda self: False
mouse.facingWall = altfaceWallFunc.__get__(mouse, Mouse) # replace facingWall func so mouse can go through walls
mouse.detectFrontWall = altfaceWallFunc.__get__(mouse, Mouse) 
mouse.detectRightWall = altfaceWallFunc.__get__(mouse, Mouse)
mouse.detectLeftWall = altfaceWallFunc.__get__(mouse, Mouse)
originalBoard= mouse.board
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()
Esempio n. 43
0
 def __init__(self,screen_width,screen_height):
     self.screen_width = screen_width
     self.screen_height = screen_height
     self.background_color = (0,0,0)
     self.mouse = Mouse()
     self.follower = Follower()