Python mouse button down

Pygame – Event Handling

An event is an action that is performed by the user in order to get the desired result. For instance, if a user clicks a button then it is known as a click event. Now, all the events that are performed by the user are inserted into a queue known as an event queue. Since it is a queue, it follows the First In First Out rule i.e. element inserted first will come out first. In this case, when an event is created it is added to the back of the queue and when the event is processed then it comes out from the front. Every element in this queue is associated with an attribute which is nothing but an integer that represents what type of event it is. Let us learn a few important attributes of the common event types.

SR No. Event Attributes
1. KEYDOWN key, mod, unicode
2. KEYUP key, mod
3. MOUSEBUTTONUP pos, button
4. MOUSEBUTTONDOWN pos, button
5. MOUSEMOTION pos, rel, buttons
6. QUIT

Owing to the fact that you have understood what an event in pygame is now let us dive deep into this topic. It is essential to know that the processing of an event must be done within the main function. This is because if in case if it is done, then there is a chance of having an input lag which can result in a poor user experience. The processing is done using pygame.event.get(). This is a function that will return the list of events that can be processed one after another.

Types of Events

1) Keyboard event:

As mentioned above, an event is an action conducted by the user. So let us wonder, what actions can be performed on the keyboard? The simple answer is either pressing the key or releasing it. Pressing the key is known as KEYDOWN and releasing it is known as KEYUP. The attribute associated with these events is known as the key of type integer. Its use is to represent the key of the keyboard. The common keys are represented by a pre-defined integer constant which is a capital K. This K is followed by an underscore and then the name of the key is written. For example K_s, K_F7.

The fact of the matter is that capital letters do not have an integer constant. The solution to this problem is something known as a modifier also known as a mod which is the modifier such as for shift, alt, ctrl, etc. that are being pressed simultaneously as the key. The integer value of mod is stored in something known as KMOD_ which is followed by the name of the key. For example KMOD_RSHIFT, KMOD_CTRL, etc. Let us revise the concepts that we have learned in the keyboard event topic with the help of a small code.

Читайте также:  font-weight

Источник

Как обрабатывать события от мыши

То в консоли мы увидим кортеж из координат положения мыши относительно клиентской области окна. То есть, свойство pos хранит координаты мыши и мы ими всегда можем воспользоваться. Если вместо атрибута pos записать атрибут rel:

print("Смещение мыши: ", event.rel)

то увидим относительные смещения курсора мыши (относительно положения в предыдущем событии MOUSEMOTION). Причем, свойство rel существует только для события pygame.MOUSEMOTION. Давайте теперь рассмотрим программу, которая позволяет рисовать в окне прямоугольник с помощью мыши. Она будет следующей:

flStartDraw = False sp = ep = None sc.fill(WHITE) pygame.display.update() while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: flStartDraw = True sp = event.pos elif event.type == pygame.MOUSEMOTION: if flStartDraw: pos = event.pos width = pos[0] - sp[0] height = pos[1] - sp[1] sc.fill(WHITE) pygame.draw.rect(sc, RED, pygame.Rect(sp[0], sp[1], width, height)) pygame.display.update() elif event.type == pygame.MOUSEBUTTONUP and event.button == 1: flStartDraw = False clock.tick(FPS)

Ее работа вполне очевидна. При нажатии на левую кнопку мыши мы устанавливаем флаг flStartDraw в значение True, т.е. включаем режим рисования при перемещении мыши. Соответственно, при событии MOUSEMOTION срабатывает условие и рисуется прямоугольник от начальной координаты sp до текущей позиции pos. При отпускании левой кнопки мыши, переменная flStartDraw становится равной False. Однако, обратите внимание, события MOUSEBUTTONDOWN и MOUSEBUTTONUP срабатывают только один раз. То есть, если все время держать нажатой кнопку мыши, то произойдет только одно событие MOUSEBUTTONDOWN. А вот событие MOUSEMOTION происходит постоянно при каждом перемещении курсора мыши в клиентской области окна. Если на каждой итерации главного цикла нужно определять: нажата ли какая-либо кнопка мыши, то следует использовать модуль pygame.mouse в котором, в частности, имеется функция: pygame.mouse.get_pressed() Она работает аналогично функции pygame.key.get_pressed() – определения нажатия клавиш, о которой мы говорили на прошлом занятии. Здесь все то же самое, только с кнопками мыши. На выходе pygame.mouse.get_pressed() выдает кортеж с тремя значениями: Единица соответствует нажатой кнопке в соответствии с ее индексом:

  • 0 – левая кнопка;
  • 1 – центральная;
  • 2 – правая кнопка.
Читайте также:  Java sql time to java sql timestamp

Перепишем предыдущую программу с использованием этой функции:

sp = None sc.fill(WHITE) pygame.display.update() while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() pressed = pygame.mouse.get_pressed() if pressed[0]: pos = pygame.mouse.get_pos() if sp is None: sp = pos width = pos[0] - sp[0] height = pos[1] - sp[1] sc.fill(WHITE) pygame.draw.rect(sc, RED, pygame.Rect(sp[0], sp[1], width, height)) pygame.display.update() else: sp = None clock.tick(FPS)

Смотрите, мы здесь вначале проверяем нажатие левой кнопки мыши (индекс 0) и если величина sp равна None, то начальной позиции для рисования прямоугольника еще нет и ее нужно приравнять текущей позиции курсора. Текущая позиция определяется с помощью функции get_pos(). Затем, удерживая нажатой левую кнопку и перемещая мышь, мы будем получать другие значения pos, но начальная позиция sp будет неизменной. В результате выполняется рисование прямоугольника. При отпускании левой кнопки, значение sp вновь становится равным None. Наконец, можно скрыть курсор мыши с помощью функции: pygame.mouse.set_visible(False) И отобразить свой собственный, например, так:

pygame.mouse.set_visible(False) while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() sc.fill(WHITE) pos = pygame.mouse.get_pos() if pygame.mouse.get_focused(): pygame.draw.circle(sc, BLUE, pos, 7) pressed = pygame.mouse.get_pressed() if pressed[0]: if sp is None: sp = pos width = pos[0] - sp[0] height = pos[1] - sp[1] pygame.draw.rect(sc, RED, pygame.Rect(sp[0], sp[1], width, height)) else: sp = None pygame.display.update() clock.tick(FPS)

Источник

Mousebuttondown Event in PyGame

Mousebuttondown Event in PyGame

  1. Install PyGame in Python 2.7
  2. Install PyGame in Python 3.5
  3. Detect the MOUSEBUTTONDOWN Event in PyGame

PyGame, as its name shows, is an open-source multimedia library in Python mainly used to make video games that include graphics, sounds, visuals, etc. These days, game programming is quite successful.

It is a cross-platform library that will work on multiple platforms with a single code-base. This library contains a lot of modules for graphics and sounds, as any game is meaningless without sounds or graphics.

This tutorial demonstrates to detect the MOUSEBUTTONDOWN event using PyGame and trigger an action in response.

Install PyGame in Python 2.7

To use this library, we should install it first. If you are running Python 2.7 version, you should use the following command to install PyGame.

#Python 2.7 conda install -c cogsci pygame 

Install PyGame in Python 3.5

If you are running Python version 3.5, you should use the following command.

#Python 3.x pip3 install pygame 

Detect the MOUSEBUTTONDOWN Event in PyGame

In any game, taking input from the player and performing an action is the main part of the game. The MOUSEBUTTONDOWN event occurs when you click the mouse button, either the left or right, regardless of how much time you hold it after clicking.

Читайте также:  Python scan to text

In the following code, we set up the game window and defined the length and height of the window in pixels. We have created the main loop ( while loop) and the event loop ( for loop) to capture the events.

In the for loop, we have checked the event’s type using the if conditions. When the MOUSEBUTTONDOWN event is triggered, a message will display MOUSEBUTTONDOWN event occurred .

If the user quits the game by pressing the X button in the game’s window, the QUIT event is triggered, and in response, the game is finished, and the window will exit. Here we have pressed the mouse button one time in the PyGame window.

#Python 3.x import pygame import sys pygame.init() display = pygame.display.set_mode((500, 500)) while True:  for event in pygame.event.get():  if event.type == pygame.MOUSEBUTTONDOWN:  print("MOUSEBUTTONDOWN event occured")  if event.type == pygame.QUIT:  pygame.quit()  sys.exit() 
#Python 3.x MOUSEBUTTONDOWN event occured 

If you want to check which mouse button is pressed, left or right, you can check the values returned by the pygame.mouse.get_pressed() method. Three values are returned by this method, one for each mouse button.

Here we have stored the returned values in a list. Each mouse button has associated a value, 1, 2, 3, 4, 5 for the left mouse button, middle mouse button, right mouse button, mouse wheel up, and mouse wheel down, respectively.

In the following code, we have checked which mouse button was clicked and printed a message accordingly. We have pressed the left and right mouse buttons.

#Python 3.x import pygame import sys pygame.init() display = pygame.display.set_mode((500, 500)) while True:  for event in pygame.event.get():  if event.type == pygame.MOUSEBUTTONDOWN:  mouse_presses = pygame.mouse.get_pressed()  if mouse_presses[0]:  print("Left mouse button pressed")  if mouse_presses[2]:  print("Right mouse button pressed")  if event.type == pygame.QUIT:  pygame.quit()  sys.exit() 
#Python 3.x Left mouse button pressed Right mouse button pressed 

I am Fariba Laiq from Pakistan. An android app developer, technical content writer, and coding instructor. Writing has always been one of my passions. I love to learn, implement and convey my knowledge to others.

Related Article — Pygame Function

Источник

Оцените статью