Esempio n. 1
0
    def draw(self):
        # What is needed? : Highlight if mouseOver, Change color to white if it's a wall

        # Set the state of the node
        if isMouseOver(self):
            # Left Mouse Button
            if mouse.get_pressed()[0] == 1:
                self.isWall = True
            # Right Mouse Button
            if mouse.get_pressed()[2] == 1:
                self.isWall = False

            self.color = ColorCode.DARK_GRAY.value
        elif self.isStart:
            self.color = ColorCode.YELLOW.value
        elif self.isEnd:
            self.color = ColorCode.ORANGE.value
        elif self.isWall:
            self.color = ColorCode.WHITE.value
        elif self.isPath:
            self.color = ColorCode.BLUE.value
        elif self.checked:
            self.color = ColorCode.RED.value
        elif self.isCurrent:
            self.color = ColorCode.GREEN.value
        else:
            self.color = ColorCode.BLACK.value

        # Render the node on the screen
        rect = Rect(self.x, self.y, self.width, self.width)
        draw.rect(self.surface, self.color, rect)
Esempio n. 2
0
    def HandleMouseClicks(self):
        """
        Handles the Add/Remove Block based on the Mouse Click

        Returns
        -------
        None
        """
        currrentTime = time()

        if self.mouse0LastRegistered + self.mouse0Timeout < currrentTime:
            self.mouse0Debounce = False

        if self.mouse2LastRegistered + self.mouse2Timeout < currrentTime:
            self.mouse2Debounce = False

        if not self.mouse0Debounce and mouse.get_pressed()[0]:
            self.mouse0Debounce = True
            self.mouse0LastRegistered = time()

            if self.highlightedBlock:
                self.removeBlock(self.highlightedBlock)

        if not self.mouse2Debounce and mouse.get_pressed()[2]:
            self.mouse2Debounce = True
            self.mouse2LastRegistered = time()

            if self.highlightedBlock and (self.highlightedSurfaceIndex
                                          is not None):
                self.addBlock(self.highlightedBlock,
                              self.highlightedSurfaceIndex)
            elif self.highlightedBlock:
                pass
    def update(self):

        if mouse.get_pressed()[0]:
            # Si le bouton gauche de la souris est enfoncé...
            if not self.l_mouse_pressed:
                # ... et que l'on n'était pas déjà en train de l'enfoncer,
                self.l_mouse_pressed = True
                # On déclenche le clic
                self.on_l_mouse_click()
        else:
            # Si le bouton est relaché on le retient
            self.l_mouse_pressed = False

        # Idem pour le bouton droit de la souris
        if mouse.get_pressed()[2]:
            if not self.r_mouse_pressed:
                self.r_mouse_pressed = True
                self.on_r_mouse_click()
        else:
            self.r_mouse_pressed = False

        # On incrémente le compteur avant le refresh
        self.time_before_fetch += 1

        # Si le compteur arrive à un certain point, on récupère
        # les infos du serveur et on remet le compteur à 0
        if self.time_before_fetch >= 2000:
            self.fetch_server()
            self.time_before_fetch = 0
Esempio n. 4
0
    def render(self, surf):
        if get_pressed()[0]:
            self.image = self.textures['l']
        elif get_pressed()[2]:
            self.image = self.textures['r']
        else:
            self.image = self.textures['def']
        self.rect = self.image.get_rect(center=get_pos())

        surf.blit(self.image, self.rect)
Esempio n. 5
0
 def update(self):
     position = Vector(*mouse.get_pos())
     self.delta = position - self.position
     self.position = position
     if self.buttons is None:
         self.buttons = tuple(
             Button(position, pressed)
             for position, pressed in enumerate(mouse.get_pressed()))
         return
     pressed = mouse.get_pressed()
     for button in self.buttons:
         button.update(pressed[button.id])
Esempio n. 6
0
    def _update(self):
        if self.font_size is None:
            self.font_size = 25

        if self.font is None and self.font_family is None:
            self.font           = font.SysFont("freesansbold.ttf", self.font_size, self.bold, self.italic)
            self.highlight_font = font.SysFont("freesansbold.ttf", self.font_size - 2, self.bold, self.italic)
        elif self.font is None and self.font_family is not None:
            self.font           = font.SysFont(self.font_family, self.font_size, self.bold, self.italic)
            self.highlight_font = font.SysFont(self.font_family, self.font_size - 2, self.bold, self.italic)

        if self.hover_color is None:
            r, g, b = [val - 30 if val > 30 else val + 30 for val in list(self.color)[:3]]
            self.hover_color = (r, g, b)

        if mouse_over(btn):
            self.active_color = self.hover_color

            if get_pressed()[0]:
                if not self.is_clicked:
                    self.command()
                self.is_clicked = True
            else:
                self.is_clicked = False
        else:
            self.active_color = self.color

        if self.is_clicked:
            self.current_font = self.highlight_font
        else:
            self.current_font = self.font
Esempio n. 7
0
    def getPressed(self, getTime=False):
        """Returns a 3-item list indicating whether or not buttons 0,1,2
        are currently pressed.

        If `getTime=True` (False by default) then `getPressed` will
        return all buttons that have been pressed since the last call
        to `mouse.clickReset` as well as their time stamps::

            buttons = mouse.getPressed()
            buttons, times = mouse.getPressed(getTime=True)

        Typically you want to call :ref:`mouse.clickReset()` at stimulus
        onset, then after the button is pressed in reaction to it, the
        total time elapsed from the last reset to click is in mouseTimes.
        This is the actual RT, regardless of when the call to `getPressed()`
        was made.

        """
        global mouseButtons, mouseTimes
        if usePygame:
            return mouse.get_pressed()
        else:
            # False:  # havePyglet: # like in getKeys - pump the events
            # for each (pyglet) window, dispatch its events before checking
            # event buffer
            defDisplay = pyglet.window.get_platform().get_default_display()
            for win in defDisplay.get_windows():
                win.dispatch_events()  # pump events on pyglet windows

            # else:
            if not getTime:
                return copy.copy(mouseButtons)
            else:
                return copy.copy(mouseButtons), copy.copy(mouseTimes)
Esempio n. 8
0
    def draw(self, screen, coordinates):
        """ Draw button widget on a screen with given coordinates

        Changes color of button when mouse is on a button or when button is clicked.
        Also, if user clicked a button, self.action would be called.

        :param screen: pygame screen
        :param coordinates: tuple (int, int)
            Coordinates (x, y) where button widget should be drawn
        """
        x, y = coordinates
        mouse_pos, mouse_click = mouse.get_pos(), mouse.get_pressed()
        button_rect = Rect(x, y, self.width, self.height)

        text_coordinates = coordinates
        if self.centralized:
            text_rect = self.text.get_rect()
            text_coordinates = (x + self.width // 2 - text_rect.width // 2,
                                y + self.height // 2 - text_rect.height // 2)

        if button_rect.collidepoint(mouse_pos[0], mouse_pos[1]):
            if mouse_click[0]:
                if self.sound:
                    self.sound.play()
                draw.rect(screen, self.pressed_bg, button_rect)
                self.text.draw(screen, text_coordinates)

                self.action()
                time.delay(200)
            else:
                draw.rect(screen, self.active_bg, button_rect)
                self.text.draw(screen, text_coordinates)
        else:
            draw.rect(screen, self.inactive_bg, button_rect)
            self.text.draw(screen, text_coordinates)
Esempio n. 9
0
def getClickedSquare():
    if mouse.get_pressed()[0]:
        mouseCoords = mouse.get_pos()
        square = squares[squares.index(mouseCoords)]
        if mouseCoords not in current_selection_of_squares and not square.isStart and not square.isEnd:
            current_selection_of_squares.append(square)
            square.onSelect()
Esempio n. 10
0
    def getPressed(self, getTime=False):
        """Returns a 3-item list indicating whether or not buttons 0,1,2
        are currently pressed.

        If `getTime=True` (False by default) then `getPressed` will
        return all buttons that have been pressed since the last call
        to `mouse.clickReset` as well as their time stamps::

            buttons = mouse.getPressed()
            buttons, times = mouse.getPressed(getTime=True)

        Typically you want to call :ref:`mouse.clickReset()` at stimulus
        onset, then after the button is pressed in reaction to it, the
        total time elapsed from the last reset to click is in mouseTimes.
        This is the actual RT, regardless of when the call to `getPressed()`
        was made.

        """
        global mouseButtons, mouseTimes
        if usePygame:
            return mouse.get_pressed()
        else:
            # False:  # havePyglet: # like in getKeys - pump the events
            # for each (pyglet) window, dispatch its events before checking
            # event buffer
            defDisplay = pyglet.window.get_platform().get_default_display()
            for win in defDisplay.get_windows():
                win.dispatch_events()  # pump events on pyglet windows

            # else:
            if not getTime:
                return copy.copy(mouseButtons)
            else:
                return copy.copy(mouseButtons), copy.copy(mouseTimes)
Esempio n. 11
0
    def input(self, event):
        self.x_speed = 0.0
        self.y_speed = 0.0
        x, y = mouse.get_pos()

        if event.type == MOUSEBUTTONDOWN and event.button == MOUSE.MIDDLE:
            self.x_first = x
            self.y_first = y
        elif event.type == MOUSEBUTTONUP and event.button == MOUSE.MIDDLE:
            self.x_first = None
            self.y_first = None
        elif event.type == MOUSEMOTION and mouse.get_pressed()[1] and \
            self.x_first and self.y_first:
            self.x_delta = x - self.x_first
            self.y_delta = y - self.y_first
        else:
            if mouse.get_focused():
                if x > self.w - self.scroll_width and x < self.w:
                    self.x_speed = self.speed
                elif x < self.scroll_width:
                    self.x_speed = -self.speed
                if y > self.h - self.scroll_width:
                    self.y_speed = self.speed
                elif y < self.scroll_width:
                    self.y_speed = -self.speed

            if key.get_focused():
                if key.get_pressed()[K_RIGHT]:
                    self.x_speed = self.speed
                elif key.get_pressed()[K_LEFT]:
                    self.x_speed = -self.speed
                if key.get_pressed()[K_DOWN]:
                    self.y_speed = self.speed
                elif key.get_pressed()[K_UP]:
                    self.y_speed = -self.speed
Esempio n. 12
0
    def update(self):
        if self.countFrames >= 1800:
            self.countFrames = 0

        self.on_key_press()
        if mouse.get_pressed()[0]:
            if not self.player.l_mouse_pressed:
                self.player.l_mouse_pressed = True
                self.on_l_mouse_click()
        else:
            self.player.l_mouse_pressed = False

        if self.countFrames <= 0:
            res = requests.get(f'{server_base_url}full').json()
            for x in range(grid_size):
                for y in range(grid_size):
                    self.grid[x][y].color = res[x][y]
            self.countFrames = 0

        for x in range(grid_size):
            for y in range(grid_size):
                self.grid[x][y].update()

        self.player.update()
        self.countFrames += 1
Esempio n. 13
0
 def update(self):
     print self.get_lock()
     if not self.get_lock():
         if mouse.get_pressed()[0]:
             self.toggle_lock()
             self.click()
     self.draw(util.enums.SCREEN)
Esempio n. 14
0
	def blit(self):
		if self.small:
			if self.small_button.is_clicked():
				self.click()
			img_copy = pygame.transform.rotate(self.smol, self.angle)
			self.scr.blit(img_copy, (self.x - int(img_copy.get_width() / 2), self.y - int(img_copy.get_height() / 2)))
			self.angle += self.factor * (time() - self.last)
			self.last = time()
			if self.angle > self.angle_max:
				self.factor = self.base_factor * -1
			elif self.angle < -self.angle_max:
				self.factor = self.base_factor
		elif self.big:
			for i in range(0, len(self.big_letter) - 1, 1):
				self.big_letter[i].blit()
			move = self.get_move()
			for obj in self.big_letter:
				if self.done > 0:
					obj.move_y(move) 
					self.done -= -move
			mouse = get_pos()
			click = get_pressed()
			x, y, w, h = self.big_letter[-1].rect
			if self.big_button.is_clicked() and self.done <= 0:
				self.deactivate()
		else:
			self.game.active_letter = Letter_Placeholder()
		return
Esempio n. 15
0
    def input(self, event, next_state):
        next_state = super(Editor, self).input(event, next_state)

        self.camera.input(event)

        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                self.tilemgr.save_tiles("map1.map")
                next_state = set_next_state(next_state, STATES.MENU)
        elif event.type == MOUSEBUTTONDOWN:
            if event.button == MOUSE.LEFT:
                self.set_tile()
            elif event.button == MOUSE.RIGHT:
                self.get_tile()
            elif event.button == MOUSE.WHEELUP:
                self.current_tile -= 1
                if self.current_tile < 0:
                    self.current_tile = self.tilemgr.total_tile_kinds - 1
            elif event.button == MOUSE.WHEELDOWN:
                self.current_tile += 1
                if self.current_tile > self.tilemgr.total_tile_kinds - 1:
                    self.current_tile = 0
        elif event.type == MOUSEMOTION and mouse.get_pressed()[0]:
            self.set_tile()

        return next_state
Esempio n. 16
0
 def update(self):
     """
     function that checks if the button was clicked and draws the button
     """
     if mouse.get_pressed()[0]:
         self.click()
     self.draw(util.enums.SCREEN)
Esempio n. 17
0
    def move_indicator(self, x: int, y: int, event: event) -> None:
        """Moves the indicator on the x axis and saves the changes."""
        b = mouse.get_pressed()[0]

        if b and self.click:
            if (x > self.x and x <
                (SliderProperties.body_width + SliderProperties.body_x) -
                    self.width_i):
                self.x_i = x
                self.slider_indicator = Rect(self.x_i, self.y_i, self.width_i,
                                             self.height_i)

                self.volume = int(
                    (100 / (self.width - self.width_i - 3)) * (x - self.x))

                if self.number == 1:
                    user_data.sound_volume = self.volume
                else:
                    user_data.music_volume = self.volume
                Sound.update()

        elif b:
            self.click = self.slider_body.collidepoint(
                x, y) or self.slider_indicator.collidepoint(x, y)
        else:
            self.click = False
Esempio n. 18
0
def save(cls):
    global get
    mouse_get = mouse.get_pressed()[2]

    if mouse_get and get:
        usr = input("Do you want to save?(Y/N) :- ")

        if usr.upper() == "Y":
            file_name = input("Enter save file name: ")

            data = {"object_list": []}

            for i in cls.object_list:
                a = {
                    "ctrl": i.ctrl,
                    "collision": i.collision,
                    "gravity": i.gravity,
                    "mass": i.mass,
                    "coords_tuple": [i.Pos.x, i.Pos.y],
                    "vel_tuple": [i.Vel.x, i.Vel.y],
                    "acc_tuple": [i.Acc.x, i.Acc.y],
                    "theta": i.theta,
                    "omega": i.omega,
                    "alpha": i.alpha,
                    "color": i.color,
                    "radius": i.radius
                }

                data["object_list"].append(a)

            with open(f"E:\my_python\pythonprojects\PyBox\saves\{file_name}",
                      "w") as jsn:
                json.dump(data, jsn, indent=2)

            get = False
Esempio n. 19
0
    def _calc_movement(self, screen, newRoom):
        x = 0
        y = 0
        buttons = mouse.get_pressed()
        keys = key.get_pressed()
        if keys[pygame.K_LEFT] or keys[pygame.K_a]:
            x = -self._data.vel
        if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
            x = self._data.vel
        if keys[pygame.K_UP] or keys[pygame.K_w]:
            y = -self._data.vel
        if keys[pygame.K_DOWN] or keys[pygame.K_s]:
            y = self._data.vel
        if keys[pygame.K_SPACE] or buttons[0] == 1 and not newRoom:
            self._weapon.fire(self._angle, self._data.attack_speed, self.rect)

        if x != 0 and y != 0:
            x *= 0.7071
            y *= 0.7071

        self._data.pos = self._data.pos + Vector2(x, y)

        # must be called in this order, considering fixing later
        self._calc_rotation()
        self._check_walls(screen)
Esempio n. 20
0
 def get_mouse_click_stage(self):
     stage_node_index, stage_node_rect = self.get_mouse_over_stage()
     if stage_node_index is not None:
         if mouse.get_pressed(num_buttons=3)[0] and self.debounce_time():
             print('click')
             self.last_updated = time.get_ticks()
             return stage_node_index, stage_node_rect
     return None, None
 def update(self):
     if self.debounce_time():
         self.button.clicked = mouse.get_pressed(
             num_buttons=3)[0] and self.button.rect.collidepoint(
                 mouse.get_pos())
         self.button.mouse_over = self.button.rect.collidepoint(
             mouse.get_pos())
         self.reset_ui_elements()
Esempio n. 22
0
 def check_click(self):
     # check if the button is being click
     mouse = get_pos()
     x, y, w, h = self.rect
     if x + w > mouse[0] > x:
         if y + h > mouse[1] > y:
             if get_pressed()[0] == 1:
                 return True
     return False
Esempio n. 23
0
    def update(self, time_delta):
        self.rect.center = mouse.get_pos()
        self.dirty = True

        pressed = mouse.get_pressed()
        if pressed[0] and self.bullet_delay > self.bullet_limiter:
            Bullet(self.scene, self.rect.midtop)
            self.bullet_delay = 0
        self.bullet_delay += time_delta
Esempio n. 24
0
def check_for_reset():
    pressed = mouse.get_pressed()
    if pressed[0]:  # Check for left click
        robotObject.x = 0  # Set the robot to the starting position
        robotObject.y = 0
        robotObject.a = 0
        robotObject.odo_a = 0
        robotObject.odo_x = 0
        robotObject.odo_y = 0
Esempio n. 25
0
    def update(self, entities, center):
        # Update the mouse cursor target to the current mouse position
        self.target.update(center)

        # Call Entity.update()
        super(Fighter, self).update(entities, center)

        # If the player hit the left mouse button, fire the railgun
        if mouse.get_pressed()[0]:
            self.railgun.fire(entities)
Esempio n. 26
0
    def change_cell(cell, info):

        # 检测鼠标动作
        change = None
        if mouse.get_pressed()[0]:
            change = True
        if mouse.get_pressed()[2]:
            change = False

        if not change is None:
            pos = ChangeCell.get_pos_on_game(info)

            # 判断这个细胞是否无效
            if pos[0] >= 0 and pos[1] >= 0 and pos[0] <= info[
                    'cell_size'] and pos[1] <= info['cell_size']:
                index = PlotCell.pos_to_index(info, pos)
                cell[index] = change

        return cell
Esempio n. 27
0
    def move(self, delta):
        button = mouse.get_pressed()[self.button - 1]
        if self.auto or button:
            pos = mouse.get_pos()
            if self.mouse_position != pos:
                self.vector = self.get_vector(pos)

            if self.mouse_position.distance_to(self.sprite._center) > self.within:
                self.sprite._center += self.vector * (delta * self.thrust)
                self.sprite.set_position(self.sprite._center, "center")
Esempio n. 28
0
 def update(self, event):
     MouseOver = self.getMouseOver()
     if MouseOver == True:
         if event.type == pl.MOUSEBUTTONDOWN and mouse.get_pressed()[0]:
             self.image = self.button_frame[3]
         else:
             self.image = self.button_frame[1]
     else:
         self.image = self.button_frame[0]
     
     return MouseOver
Esempio n. 29
0
	def update(self) -> Optional[Scene]:
		(x, y) = mouse.get_pos()
		(w, h) = self.screen.get_size()
		if (w // 2 - x) ** 2 + (h // 2 - y) ** 2 < self.radius ** 2:
			self.radius = 220
		else:
			self.radius = 200

		(x, _, _) = mouse.get_pressed()
		if x and self.radius == 220:
			return Arena(self.screen)
Esempio n. 30
0
    def Update(self, screen, debugMode, deltaTime, scaleFactor):
        self.TimeInState += deltaTime
        self.TimeSinceLastHold += deltaTime

        self.Pos = [
            int(self.BasePos[0] * scaleFactor),
            int(self.BasePos[1] * scaleFactor)
        ]
        self.Size = [
            int(self.BaseSize[0] * scaleFactor),
            int(self.BaseSize[1] * scaleFactor)
        ]

        pos = mouse.get_pos()
        mouseDown = mouse.get_pressed()[0]
        mouseOverButton = (pos[0] > self.Pos[0]
                           and pos[0] < self.Pos[0] + self.Size[0]
                           and pos[1] > self.Pos[1]
                           and pos[1] < self.Pos[1] + self.Size[1])

        if mouseOverButton:
            if self.LastFrameMouseDown and not mouseDown:
                self.TriggerOnClick(True)
            if self.State == UiPiece.eState.press and self.TimeInState >= self.MinHoldTime:
                self.TriggerOnHold()

        if mouseOverButton and mouseDown:
            self.State = UiPiece.eState.press

        elif self.GetIsFade != None and self.GetIsFade():
            self.State = UiPiece.eState.Fade

        elif mouseOverButton and not mouseDown:
            self.State = UiPiece.eState.Hover

        else:
            self.State = UiPiece.eState.Normal

        if self.State != self.LastState:
            self.TimeInState = 0

        if self.AudioPlayer != None:
            if self.State == UiPiece.eState.press and self.LastState != UiPiece.eState.press:
                self.AudioPlayer.PlayEvent(self.ButtonDownAudioEvent)

            elif self.State != UiPiece.eState.press and self.LastState == UiPiece.eState.press:
                self.AudioPlayer.PlayEvent(self.ButtonUpAudioEvent)

        self.LastState = self.State

        self.LastFrameMouseDown = mouseDown

        self.Draw(screen, debugMode)
        return self.Selectable and self.State == UiPiece.eState.press
Esempio n. 31
0
    def update(self, event):
        MouseOver = self.getMouseOver()
        if MouseOver == True:
            if event.type == pl.MOUSEBUTTONDOWN and mouse.get_pressed()[0]:
                self.image = self.button_frame[3]
            else:
                self.image = self.button_frame[1]
        else:
            self.image = self.button_frame[0]

        return MouseOver
Esempio n. 32
0
 def check(self, mouse_pos):
     m_x = mouse_pos[0]
     m_y = mouse_pos[1]
     if self.x + self.width > m_x > self.x and self.y + self.height > m_y > self.y:
         if self.change:
             self.color = ((self.r + 10) % 256, (self.g + 10) % 256,
                           (self.b + 10) % 256)
         if mouse.get_pressed()[0]:
             return True
     else:
         self.color = self.default_color
Esempio n. 33
0
    def simulate(self, time_delta):
        mouse_x, mouse_y = mouse.get_pos()
        diff_x = max(min(mouse_x - self.rect.centerx, 10), -10)
        diff_y = max(min(mouse_y - self.rect.centery, 10), -10)
        self.rect.centerx += diff_x
        self.rect.centery += diff_y

        pressed = mouse.get_pressed()
        if pressed[0] and (self.laser_delay >= self.laser_limiter):
            Laser(self.scene, self.rect.midtop)
            self.laser_delay = 0
        self.laser_delay += time_delta
Esempio n. 34
0
    def pause(self, screen):
        """
        screen the pause for the level
        """
        _mouse = mouse.get_pressed()
        if _mouse[0]:
            action = self.pauseScreen.buttonAction()
            if action:
                return action

        self.pauseScreen.draw(screen)
        return PAUSE
Esempio n. 35
0
    def handle_input(self, game, event):

        mouse_buttons = mouse.get_pressed()

        if event.type == QUIT:
            # Exit if the quit button is pressed

            game.exit()

        if event.type == KEYUP:
            # Check for a keyboard button coming up

            if event.key == K_ESCAPE:
                # The escape key

                self.game.state = MenuState(self.game, self.ui_config)

        if event.type == MOUSEMOTION:
            # Check for mouse movement

            # Check the right button on moused pressed
            if mouse_buttons[2]:

                self.game_map.move_surface(event)

            self.mouse_movement(event)

        if event.type == MOUSEBUTTONUP:
            # Check for a mouse click

            moused_butt = self.interface.get_moused_button()

            if moused_butt:

                moused_butt.left_clicked()

        if event.type == MOUSEBUTTONDOWN:
            # Check for mouse button down

            if event.button == 4:
                # Mouse wheel up

                self.game_map.zoom_in()
                self.game_map.render()

            if event.button == 5:
                # Mouse wheel down

                self.game_map.zoom_out()
                print self.game_map.zoom
                self.game_map.render()

        return False
Esempio n. 36
0
    def simulate(self, time_delta):
        mouse_x, mouse_y = mouse.get_pos()
        diff_x = max(min(mouse_x - self.rect.centerx, 5), -5)
        diff_y = max(min(mouse_y - self.rect.centery, 5), -5)
        self.rect.centerx += diff_x
        self.rect.centery += diff_y

        pressed = mouse.get_pressed()
        if pressed[0] and (self.bullet_delay >= self.bullet_limiter):
            Bullet(self.scene, self.rect.midtop)
            self.bullet_delay = 0
        self.bullet_delay += time_delta
Esempio n. 37
0
 def respond(self):
     mouse_buttons = mouse.get_pressed()
     mouse_position = mouse.get_pos()
     if mouse_buttons[0] and not self.button_pressed:
         self.button_pressed = True
         target = EmptyTarget(Vector(*mouse_position))
         for sprite in self.targets.sprites():
             if sprite.rect.collidepoint(mouse_position):
                 target = sprite
                 break
         self.actor.target = target
     if not mouse_buttons[0] and self.button_pressed:
         self.button_pressed = False
Esempio n. 38
0
	def handle_mouse_events(self):
		"""
		- Creates obstacles on left clicks
		- Removes obstacles on right clicks
		"""
		pressed = mouse.get_pressed()
		x, y = mouse.get_pos()
		size = self.settings["cell_size"]
		cell = self.world[(x/size, y/size)]
		if pressed[0]:
			cell.make_obstacle()
		elif pressed[2]:
			if cell.is_obstacle():
				cell.remove_obstacle()
Esempio n. 39
0
    def poll(self, pos):
        if self._images[0].get_rect().collidepoint(pos):
            event.get()
            pressed = mouse.get_pressed()[0]
        else:
            pressed = False

        changed = False
        if self._pressed != pressed:
            self._pressed = pressed
            changed = True

        if self._pressed:
            self._down()

        return changed
Esempio n. 40
0
 def updateControls(self):
     bools = key.get_pressed()
     self.up = bools[pygame.K_UP] or bools[pygame.K_w]
     self.down = bools[pygame.K_DOWN] or bools[pygame.K_s] 
     self.left = bools[pygame.K_LEFT] or bools[pygame.K_a]
     self.right = bools[pygame.K_RIGHT] or bools[pygame.K_d]
     self.w = bools[pygame.K_w]
     self.s = bools[pygame.K_s]
     self.a = bools[pygame.K_a]
     self.d = bools[pygame.K_d]
     self.f = bools[pygame.K_f]
     self.p[0] = bools[pygame.K_p]
     m = mouse.get_pressed()
     self.mClicked = m[0]
     self.mloc = mouse.get_pos()
     self.space = bools[pygame.K_SPACE] or bools[pygame.K_RETURN]
     self.one[0] = bools[pygame.K_1]
Esempio n. 41
0
    def input_mouse(self, event):
        x, y = mouse.get_pos()
        x += self.camera.rect.x
        y += self.camera.rect.y

        if event.type == MOUSEMOTION and mouse.get_pressed()[0]:
            self.mouse_rect.x = min(self.x_first, x)
            self.mouse_rect.w = abs(self.x_first - x)
            self.mouse_rect.y = min(self.y_first, y)
            self.mouse_rect.h = abs(self.y_first - y)

        if event.type == MOUSEBUTTONDOWN and event.button == MOUSE.LEFT:
            self.mouse_rect.x = x
            self.mouse_rect.y = y
            self.mouse_rect.w = 0
            self.mouse_rect.h = 0
            self.x_first = x
            self.y_first = y
Esempio n. 42
0
def _foo(e):
	global _Clic,_Ticks,_Inactiv,_ButtonTick
	if e.type==NOEVENT:
		_Inactiv+=_NoEvent_Clock.tick()

		if _Inactiv>=ButtonDelay and _Inactiv>=_ButtonTick:
			_ButtonTick+=ButtonRepeat
			e.dict.update({'inactiv':_Inactiv,'repeat_buttons':mouse.get_pressed(),'mouse_pos':mouse.get_pos()})
		else:
			e.dict.update({'inactiv':_Inactiv,'repeat_buttons':[0,0,0,0,0],'mouse_pos':mouse.get_pos()})
	else:
		_Inactiv = 0
		_ButtonTick = ButtonDelay
		if e.type==MOUSEBUTTONDOWN:
			if  _Ticks[e.button].tick()>LAPS or e.button!=_Clic[0]: _Clic=[e.button,0,0,0,0,0]
		elif e.type==MOUSEBUTTONUP:
			if _Ticks[e.button].tick()>LAPS: _Clic=[e.button,0,0,0,0,0]
			else:
				_Clic[e.button]+=1
			e.dict.update({'click':_Clic})
Esempio n. 43
0
    def update(self):
        """
        function to be run every tick to keep the object up to date
        """
        pos = mouse.get_pos()
        mp_sz = get_map_size()
        x = int(pos[0] / TILE_W)
        y = int(pos[1] / TILE_H)
        btns = mouse.get_pressed()
        if btns[0] and pos[0] < mp_sz[0] and pos[1] < mp_sz[1] \
           and self.state == Tower.PLACEMENT:
            self.state = Tower.CHECKING
        screen_cover_up(self.location, (self.width,
                                        self.height))
        if btns[2] and self.state == Tower.PLACEMENT:
            util.enums.SPRITES[0].pop()
            util.enums.MONEY += self.cost
            return
        elif btns[0] and (self.state == Tower.IDLE or
                          self.state == Tower.ATTACKING):
            self.click()

        if self.state == Tower.PLACEMENT:
            self.location = pos
        elif self.state == Tower.CHECKING:
            if pos[0] < mp_sz[0] and pos[1] < mp_sz[1]:
                if self.check_under(x, y):
                    self.location = (x * TILE_W, y * TILE_H)
                    self.add_to_bg()
                    self.state = Tower.IDLE
                    self.select()
                else:
                    self.state = Tower.PLACEMENT
        elif self.state == Tower.IDLE:
            if self.frame != 0:
                self.frame = 0
        elif self.state == Tower.ATTACKING:
            map_cover_up(self.location, (self.width, self.height))
            self.animate(10)
        self.srf = self.frames[self.frame]
        self.draw(util.enums.SCREEN)
Esempio n. 44
0
    def update(self):
        """
        Get User input and propagate to childs
        """
        mousebut = mouse.get_pressed()
        mouse.b1, mouse.b2, mouse.b3 = mousebut       

        # If focused, run mouse callbacks
        topmost = self.findTopMost(mouse.get_pos())
        if topmost == self: 
            if self.onMouseMove:
                self.onMouseMove(mouse.get_pos(), mousebut)
            
            if mousebut[0] and not self.mousedown[0] and self.onMouseDown:
                self.onMouseDown(mouse.get_pos(), 1)
            elif not mousebut[1] and self.mousedown[0] and self.onClick:
                self.onClick(mouse.get_pos(), mousebut)
                
            self.mousedown[0] = mousebut[0]
                
            if mousebut[1] and not self.mousedown[1] and self.onMouseDown:
                self.onMouseDown(mouse.get_pos(), 2)
            self.mousedown[1] = mousebut[1]
            
            if mousebut[2] and not self.mousedown[2] and self.onMouseDown:
                self.onMouseDown(mouse.get_pos(), 3)
            self.mousedown[2] = mousebut[2]      
        
        # Change focus onClick        
        if mousebut[0]:                    
            if self.focused and self.focused != self:
                if topmost != self.focused.parent:
                    if hasattr(self.focused, 'lostFocus'):
                        self.focused.lostFocus()
                    self.focused = topmost
            else: 
                self.focused = topmost
            topmost = None        
            
        CContainer.update(self, topmost)
Esempio n. 45
0
while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False
        elif event.type == KEYDOWN:
            if event.key == K_q:
                quit_game()
            if event.key == K_u:
                for t in enums.SPRITES[0].list:
                    t.upgrade()
            if event.key == K_a:
                for t in enums.SPRITES[0].list:
                    t.set_state(3)
        elif event.type == MOUSEBUTTONDOWN:
            b1, b2, b3 = mouse.get_pressed()
            if b1:
                if argv[1] == "ui":
                    clicked += 1
                    bunch_cntr.change_text(":  " + str(clicked), True)
                    heart = hearts[-(clicked % len(hearts))]
                    if heart.get_heart() == Heart.FULL:
                        heart.set_heart(Heart.HALF)
                    elif heart.get_heart() == Heart.HALF:
                        heart.set_heart(Heart.EMPTY)
                    else:
                        heart.set_heart(Heart.FULL)
                    btn.update()
            if b2:
                for t in enums.SPRITES[0]:
                    t.upgrade()
Esempio n. 46
0
def main():
    term = Color()
    init()
    screen = display.set_mode((800, 600))
    finished = False
    sprDimension = 20
    R = 255
    G = 0
    B = 0
    RedKey = 114
    GreenKey = 103
    BlueKey = 98
    UP = 273
    DOWN = 274
    colorFocus = ""

    while not finished:
        for ev in event.get():
            if ev.type == QUIT:
                finished = True
            elif ev.type == MOUSEBUTTONDOWN:
                if mouse.get_pressed()[0] == 1:
                    draw.rect(
                        screen, (R, G, B), (mouse.get_pos()[0], mouse.get_pos()[1], sprDimension, sprDimension), 0
                    )
            elif ev.type == KEYDOWN:
                print ev.key
                if ev.key == RedKey:
                    colorFocus = "r"
                elif ev.key == GreenKey:
                    colorFocus = "g"
                elif ev.key == BlueKey:
                    colorFocus = "b"
                elif ev.key == UP and colorFocus != "":
                    if colorFocus == "r":
                        if R == 255:
                            R = 0
                        else:
                            R += 1

                    if colorFocus == "g":
                        if G == 255:
                            G = 0
                        else:
                            G += 1

                    if colorFocus == "b":
                        if B == 255:
                            B = 0
                        else:
                            B += 1

                elif ev.key == DOWN and colorFocus != -1:
                    print ev.key

                    if colorFocus == "r":
                        if R == 0:
                            R = 255
                        else:
                            R -= 1

                    if colorFocus == "g":
                        if G == 0:
                            G = 255
                        else:
                            G -= 1

                    if colorFocus == "b":
                        if B == 0:
                            B = 255
                        else:
                            B -= 1

        print R, G, B

        draw.rect(screen, (R, G, B), (screen.get_width() - sprDimension, 0, screen.get_width(), sprDimension), 0)
        display.update()
        draw.rect(screen, (0, 0, 0), screen.get_rect(), 0)

        sleep(0.4)
Esempio n. 47
0
     print("saving screenshot to {}".format(filepath))
     pygame.image.save(screenshot, filepath)
 if event.type == pl.KEYDOWN and event.key == pl.K_F3:
     '''
     debugging function
     '''
     if DEBUG_MODE:
         DEBUG_MODE = False
         CLEAR_DEBUG = True
         allSprites.remove(fpsdisplay)
         print("debug mode off")
     else:
         DEBUG_MODE = True
         allSprites.add(fpsdisplay, layer = DEBUG_LAYER)
         print("debug mode on")
 if event.type == pl.MOUSEBUTTONDOWN and mouse.get_pressed()[0]:
     '''
     This is where the button's destination kicks in
     Unfortunately, we have to check each button separately,
     as the pygame.sprite.Group.update() can't return sprites' .update()
     return values.
     What happens here:
     When the user clicks a button: 
     1. all buttons are checked (one by one) to see which one the mouse is on,
     2. the background is drawn over it (and only it)
     3. the button updates
     4. the button gets put into the buttonToDraw one-sprite-only group
     5. buttonToDraw draws it onto the screen
     6. the display updates only on it
     7. then the destination is checked, and except for two special cases, new buttons are
     loaded from menuCreator (that is, all existing buttons removed, and new ones drawn on screen)
Esempio n. 48
0
 def _reaction_time(self):
     if self.current_state_key == STATE_PRESSED:
         if get_pressed()[0]:
             self.father._drag_element.shift(-parameters.CLICK_LIFT_REPEAT)
Esempio n. 49
0
 def render_mouse_rect(self, camera):
     if mouse.get_pressed()[0] and (self.mouse_rect.w or self.mouse_rect.h):
         pos = Rect(self.mouse_rect.x - camera.rect.x,
             self.mouse_rect.y - camera.rect.y, self.mouse_rect.w,
             self.mouse_rect.h)
         draw.rect(self.resourcemgr.screen, BLUE, pos, 5)
Esempio n. 50
0
def main():
    makeCave()
    
    map(spawnEnemy(), range(5))
    
    player.setPos((5,5))
    player.movement=PathMove(player, [])
    player.setColor((0,255,0))
    
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                return
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    return
                elif event.key == K_SPACE:
                    world.randomize()
                elif event.key == K_RETURN:
                    world.reset()
#                elif event.key == K_LEFT:
#                    player.move(LEFT)
#                elif event.key == K_RIGHT:
#                    player.move(RIGHT)
#                elif event.key == K_UP:
#                    player.move(UP)
#                elif event.key == K_DOWN:
#                    player.move(DOWN)
                    
            elif event.type == MOUSEBUTTONDOWN:
                if event.button==LEFT:
                    1
                elif event.button==RIGHT:
                    target=camera.getWorld(pygame.mouse.get_pos())
                    path=aStarPath(player.getPos(), target)
                    player.movement.setPath(path)
#            elif event.type == MOUSEBUTTONUP:
        
        #screen.blit(background, (0, 0))
        
        if mouse.get_pressed()[2]:
            world.getTile(camera.getWorld(pygame.mouse.get_pos())).setType("Ground")
        if mouse.get_pressed()[0]:
            mousepos=camera.getWorld(pygame.mouse.get_pos())
            world.digFour(mousepos[0], mousepos[1])
        
        key=pygame.key.get_pressed()
        
        
        updateGameObjects()
        camera.set(player.getPos())
        
        #drawing here
        world.render()
        renderGameObjects()  
        
        
        pygame.display.flip()
        clock.tick(60)
    pygame.display.quit()
    pygame.quit()
Esempio n. 51
0
def go():
    
                     
    # START
    
    # Fairly obvious, initialize the pygame library
    pygame.init()
    
    # Create the world in which all physical things reside. It is our coordinate system and universe.
    world = World(vector((20.0, 20.0, 2000.0)), vector((-10.0, 0.0, 10.0)))
    
    # Create startup cameras and make the world visible to them
    eyecam = Camera()
    eyecam.registerObject(world)
    scopecam = Camera()
    scopecam.registerObject(world)
    
    # Setup the program window (just a special case of a View)
    screen = Screen(eyecam, vector((1000,800,0)), -1.0)
    screen.display = pygame.display.set_mode((1000, 800))
    
    # Setup the display surfaces to be drawn to screen and list them
    main_dim = vector((1000,800,0.0))
    scope_dim = vector((240,240,0.0))
    mainview = View(eyecam, main_dim, zero_vector, 1.0)
    scopeview = Scope(scopecam, scope_dim, (main_dim - scope_dim) / 2.0, 4.0)
    views = [ mainview, scopeview ]
    
    # Hide the cursor
    mouse.set_visible(False)
    
    # Let's set up some useful variables
    now = pygame.time.get_ticks()   # The current program time
    shot_fired = False              #
    chase_bullet = False
    hide_scope = True
    lock_mouse = False
    power = 100.0
    #mainview.reposition(eyecam)
    scopeview.setPower(power)
    timescale = 1.0
    tot_mag = 0.0
    tot_dur = 0.0
    frames = 0
    
    if lock_mouse:
        mouse.set_pos((scope_dim / 2.0).xy())
    
    while 1:
        
    
    
        last_t = now
        now = pygame.time.get_ticks()
        t_length = float(now - last_t)
        
        if world.has_hit:
            shot_end = now
            #break
        
        if world.bullet.position.z() > world.target.position.z() + 1000.0:
            #world.bullet.position = vector((world.bullet.position.x(), world.bullet.position.y(), world.target.position.z() - 0.01))
            shot_end = now
            break
            #pass
                
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.dict['button'] == 4:
                    power += 1.0
                if event.dict['button'] == 5:
                    power -= 1.0
                power = scopeview.setPower(power)
                print power
            
            if event.type == pygame.QUIT:
                sys.exit()
                
        
        
        sx, sy = (0.5 * mainview.dimensions).xy()
        if lock_mouse:
            mx, my = mouse.get_rel()
            mouse.set_pos(sx, sy)
            r = (1.0 / (10000 * power))* (vector((sx - mx, sy - my, 0)))
            scopecam.rotation += r
            eyecam.rotation += r
        else:
            mx, my = mouse.get_pos()
            r = (1.0 / (1000 * power))* (vector((sx - mx, sy - my,  0)))
            scopecam.rotation = r
            eyecam.rotation = r
        
        world.bullet.rotation = scopecam.rotation
        scopeview.reposition(scopeview.camera)
        mainview.reposition(mainview.camera)
          
        b1, b2, b3 = mouse.get_pressed()
        if b1 and not shot_fired:
            shot_fired = True
            shot_start = now
            world.bullet.velocity = rotate(vector((0.0,0.0,800.0)), (-world.bullet.rotation - scopeview.tweaks))
            print 'Start Velocity: ' + str(world.bullet.velocity.magnitude())
            #mainview.camera.rotation = zero_vector
            mainview.setPower(50.0)
            #scopeview.reposition(view.camera)
            #scopeview.overlay = []    # hide scope
            world.movers += [world.bullet]
            
    
        # Move everything. The world does most of the work once we tell it to,
        # we just need to handle the less tangible stuff.
        world.moveObjects(timescale * (t_length / 1000.0))
            
        # Bullet chasing
        if shot_fired:
            #scopecam.rotation = world.bullet.rotation
            
            if hide_scope:
                scopeview.visible = False
                
            bp = world.bullet.position
            lbp = world.bullet.last_position
            diff = bp - lbp
            mag = diff.magnitude()
            magxz = sqrt(diff.x()**2 + diff.z()**2)
            
            frames += 1
            tot_mag += mag
            tot_dur += t_length * timescale
                        
            if chase_bullet and mag > 0.0:
                h = arctan2(diff.x(), diff.z())
                e = arcsin(diff.y() / mag)
                eyecam.rotation = vector((h, -e, 0))
                eyecam.position = bp & vector((1,1,1))
                mainview.setPower(10.0)
                mainview.reposition(mainview.camera)
            
            #print eyecam.position
            #scopeview.reposition(eyecam)
            
        
        # Grab each view's camera image, then draw them to the program window in sequence
        
        for view in views:
            view.updateDisplay()
            view.draw(screen.display)
        
        # 
        fps = 1000.0 / (t_length + (1 if t_length == 0 else 0))
        screen.drawOverlay((fps,))
        
        
        pygame.display.flip()
             
             
    
    for view in views:
        view.updateDisplay()              
        view.draw(screen.display, (screen.dimensions - view.dimensions) / 2.0)         
             
    pygame.display.flip()
    
    
    print "Flight time: " + str(tot_dur / 1000.0) + " s" 
    print "Impact energy: " + str(.5 * world.bullet.mass * world.bullet.velocity.magnitude() ** 2) + " J"
    
    print 'End Position'
    print world.bullet.position
    print 'End Velocity: ' + str(world.bullet.velocity.magnitude())
    print "Average frame time: " + str((tot_dur / 1000.0) / float(frames))
    print "Average FPS: " + str(float(frames) / tot_dur * 1000)
    print "Average distance per frame: " + str(tot_mag / float(frames))
            
    pygame.time.delay(1000)    
    
    pygame.display.quit()
    pygame.quit()
Esempio n. 52
0
 def buttons_down(self): return mouse.get_pressed()
 @property