Если нажата кнопка питон

Обработка ввода и анимации¶

Взаимодействие пользователя с компьютером основано на событиях, любые действия производимые пользователем порождают события — движение мыши, нажатия клавиш, специальных кнопок. Внутри библиотеки PyGame есть инструменты для обратки событий, которые происходят внутри приложений.

Мы с вами уже знакомы с методом получения всех произошедших событий — pygame.event.get() , который возвращает события, произошедшие с последнего обращения.

Помимо событий выхода из приложения pygame.QUIT , есть множество других — например, нажатия клавиш pygame.KEYDOWN или отпускания pygame.KEYUP .

Рассмотрим взаимодействие с событиями на примере небольшой программы, в которой по нажатию клавиш показывается квадрат:

import sys import pygame pygame.init() screen = pygame.display.set_mode((640, 480)) rect = pygame.Rect(40, 40, 120, 120) color = (0, 0, 0) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: color = (255, 255, 255) pygame.draw.rect(screen, color, rect, 0) pygame.display.flip() 

В данном блоке программа занимется обработкой нажатия клавиш. Сначала мы получаем список всех событий, после чего начинаем последовательно проверять их. Если одно из событий соответствует сигналу к завершению программы, закрываем окно. Если же это нажатие клавиши — перекрашиваем прямоугольник в белый цвет.

При нажатии кнопки закрытия программы

Обработка нажатий клавиш¶

Когда мы нажимаем клавишу, в систему передаётся не только информация о том, что какая-то кнопка нажата, но и её код.

Читайте также:  Как удалить форму php

С первым мы уже знакомы, поэтому стоит внимательнее рассмотреть второй. Он позволяет получить список клавиш, которые нажаты в данный момент в виде кортежа булевых значений. Чтобы узнать нажата ли интересующая нас кнопка, необходимо проверить значение, которе содержится в данном кортеже:

keys = pygame.key.get_pressed() if keys[pygame.K_RETURN]: print("Нажата клавиша enter") 

Перемещение объектов¶

Умея получать от пользователя ввод, мы можем реализовать движения наших фигур на экране:

import sys import pygame pygame.init() screen = pygame.display.set_mode((640, 480)) rect = pygame.Rect(40, 40, 120, 120) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: rect.move_ip(-40, 0) elif event.key == pygame.K_RIGHT: rect.move_ip(40, 0) elif event.key == pygame.K_UP: rect.move_ip(0, -40) elif event.key == pygame.K_DOWN: rect.move_ip(0, 40) pygame.draw.rect(screen, (255, 0, 0), rect, 0) pygame.display.flip() 

Для движения объектов используются методы move() и move_ip() , которыми обладают объекты, созданные с помощью функций из pygame.draw . Первый создаёт новую фигуру такого же типа, находящуюся по заданному смещению, второй непосредственно изменяет положение имеющейся фигуры.

Запустив данный код, вы можете заметить, что при перемещении фигуры от неё остаётся “след”. Это связано с тем, что при перемещении объекта, мы его не перемещаем на экране, а рисуем на новом месте поверх старого кадра.

Чтобы избежать данной проблемы, надо добавить вызов метода fill() у нашего экрана, на котором мы рисуем и передать ему цвет, которым надо закрасить фон. Данное действие надо проводить каждый раз перед отрисовкой кадра:

# здесь могла быть ваша проверка событий screen.fill((0, 0, 0)) pygame.draw.rect(screen, (255, 0, 0), rect, 0) pygame.display.flip() 

Использование спрайтов¶

Спрайт — двумерное изображение, используемое в играх.

Функция для загрузки спрайта из картинки. Path — путь до изображения, возвращает объект типа Surface, который можно использовать для рисования.

Для отрисовки спрайта на экране надо вызвать метод blit() у поверхности на которой производится отрисовка и передать объект спрайта вместе с координатами на которых необходимо отрисовать:

screen = pygame.display.set_mode((640, 480)) sprite = pygame.image.load("sprite.png") screen.blit(sprite, (20, 20)) pygame.quit() 

Анимации¶

В pygame анимации создаются при помощи набора спрайтов, которые последовательно отрисовываются:

animation_set = [pygame.image.load(f"ri>.png") for i in range(1, 6)] window = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() i = 0 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() window.fill((0,0,0)) window.blit(animation_set[i // 12], (100, 20)) i += 1 if i == 60: i = 0 pygame.display.flip() clock.tick(60) 

Создаём список спрайтов, каждый из которых будет отдельным кадром анимации:

animation_set = [pygame.image.load(f"ri>.png") for i in range(1, 6)] 

Создаём часы, для ограничения количества кадров в секунду:

Вспомогательная переменная, которая поможет выбирать нужную анимацию в зависимости от номера кадра:

Выбор анимации в зависимости от номера кадра и его отрисовка:

window.blit(animation_set[i // 12], (100, 20)) 

Изменение переменной, помогающей выбрать нужный кадр:

Ограничение количества кадров в секунду, благодаря чему становится проще просчитывать анимации и синхронизировать события:

Задания¶

  1. Написать программу, которая будет писать в консоль названия нажатых клавиш. Реализовать поддержку enter, space, w, a, s, d, esc. Названия кнопок внутри библиотеки доступны в официальной документации: https://www.pygame.org/docs/ref/event.html
  2. С помощью циклов, используя квадрат 10х10 пикселей и его след, нарисовать рамку 100х100 пикселей.
  3. Написать программу, в которой по нажатию клавиш будет двигаться квадрат размером 20х20 пикселей. Учесть, что квадрат не должен выходить за границы экрана.
  4. Доработать программу, чтобы квадрат при каждом движении менял свой цвет на случайный.
  5. Реализовать анимацию движения персонажа. При движении влево или вправо должны показываться соответствующие анимации. Кадры для них взять из архива animations.zip

© Copyright Revision d00c0df4 .

Versions latest Downloads html On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.

Источник

Detect Keypress in Python

Detect Keypress in Python

  1. Detect KeyPress Using the keyboard Module in Python
  2. Detect KeyPress Using the pynput Module in Python

If you need access to the hardware like input devices such as the keyboard, there are modules available in Python which can make your lives much easier. Using such modules, you can easily perform the task you want without dealing with the complexities of the system.

In this article, you will learn how to detect keypress using modules in Python. There are many modules used to detect keypress in Python, and out of which, the two most popular and widely used modules are keyboard and pynput .

Detect KeyPress Using the keyboard Module in Python

The keyboard module allows us to take full control of the keyboard and comes with various predefined methods to choose from. These methods make it much easier for us to work with the keyboard and detect the user’s physical keypresses on the keyboard.

To install the keyboard module, execute the below command inside your command prompt or terminal.

First, you have to import the keyboard module into the program. Here, we are using three methods to detect keypress in Python read_key() , is_pressed() and on_press_key() .

import keyboard  while True:  if keyboard.read_key() == "p":  print("You pressed p")  break  while True:  if keyboard.is_pressed("q"):  print("You pressed q")  break  keyboard.on_press_key("r", lambda _:print("You pressed r")) 
You pressed p You pressed q You pressed r 

The read_key() will read which key a user has pressed on the keyboard, and if it’s that key which you wanted, in this case, p , it will print the message You pressed p . The read_key() function returns a character.

The is_pressed() takes a character as an input, and if it matches with the key which the user has pressed, it will return True and False otherwise.

The on_press_key() takes two parameters as an input, the first is the character, and the second is the function. If the user presses the key that matches the key specified as the first parameter of the on_press_key() function, it will only execute the function you have passed in as the second parameter.

Detect KeyPress Using the pynput Module in Python

The pynput module is used to detect and control input devices, mainly mouse and keyboard. But in this tutorial, you will only see how to use this module for detecting keypress on the keyboard. Before using this module, you first have to install it using the command below.

To use this module for detecting keypress, you first have to import keyboard from pynput module.

from pynput import keyboard  def on_press(key):  try:  print('Alphanumeric key pressed:  '.format(  key.char))  except AttributeError:  print('special key pressed: '.format(  key))  def on_release(key):  print('Key released: '.format(  key))  if key == keyboard.Key.esc:  # Stop listener  return False  # Collect events until released with keyboard.Listener(  on_press=on_press,  on_release=on_release) as listener:  listener.join() 
Alphanumeric key pressed: a Key released: 'a' Alphanumeric key pressed: b Key released: 'b' special key pressed: Key.ctrl_l Key released: Key.ctrl_l 

Note that the above output may vary depending upon which keys are pressed by the user.

To detect keypress, we are defining two functions, on_press and on_release . The function on_press will be executed when the user will press a button on the keyboard, and as soon as the user releases that button, the on_release function will be executed.

Both functions are only printing the keys pressed and released by the user to the console window. You can change the implementation of these two functions based on your requirements.

Then at the end, we have a Listener that will listen to the keyboard events, and it will execute the on_press and on_release functions accordingly.

Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.

Related Article — Python Input

Источник

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