How to use long key presses in python and raspberry pi? - python

I have a raspberry pi with a few motors. I have tried pynput but when I hold a button it continuously activates the function. I want to make it activate a function until I let go of the button. How would I go about doing that?
This is the janky code I have right now.
def show(key):
if key == Key.delete:
return False
elif key == Key.up:
print("forward")
left_turn(0.1)
elif key == Key.right:
print("right")
forward(0.1)
elif key == Key.left:
print("left")
reverse(0.1)
elif key == Key.down:
print("reverse")
right_turn(0.1)
# Collect all event until released
with Listener(on_press = show) as listener:
listener.join()

Related

create a button that can only be pressed once

i am trying to create a button that can only be pressed once for a game in python but i cant figure out how to set a variable that works in the def and does not change every time the function is run.
tut = turtle.Screen()._root
def bt1():
pressed = 1
x_turn = True
if (pressed == 1):
if (x_turn is True):
print("this button has not been pressed as player1")
x_turn == False
pressed = 0
else:
print ("this button has not been pressed as player2")
pressed = 0
x_turn == True
else:
print("this button has been pressed")
photo1 = Image.open(r"C:\image.png")
resize_photo1 =photo1.resize((50,50), Image.ANTIALIAS)
print_photo1 = itk.PhotoImage(resize_photo1)
Button(tut, image= print_photo1,command=bt1).pack(side= LEFT)
what i am gathering is that when this button is pressed you want it to set pressed to 0 so it can not run again but since you put the variable at the top every time the button is bressed it will set it to 1. to fix this all you want to do is....
tut = turtle.Screen()._root
global pressed
pressed = 1
global x_turn
x_turn = True
def bt1():
if (pressed == 1):
if (x_turn is True):
print("this button has not been pressed as player1")
x_turn == False
pressed = 0
This might work let me know if it does
x_turn = True
Try using this :
x_turn == True
I think here you’re missing the equals to sign and that’s why it is creating a problem.

User key keyboard input

How do I get a user keyboard input with python and print the name of that key ?
e.g:
user clicked on "SPACE" and output is "SPACE"
user clicked on "CTRL" and output is "CTRL".
for better understanding i'm using pygame libary. and i built setting controller for my game. its worked fine but i'm able to use only keys on my dict. i dont know how to add the other keyboard keys.
see example:
class KeyboardSettings():
def __init__(self,description,keyboard):
self.keyboard = keyboard
self.default = keyboard
self.description = description
self.active = False
def activate_change(self,x,y):
fixed_rect = self.rect.move(x_fix,y_fix)
pos = pygame.mouse.get_pos()
if fixed_rect.collidepoint((pos)):
if pygame.mouse.get_pressed()[0]:
self.active = True
elif pygame.mouse.get_pressed()[0]:
self.active = False
This is a part of my class. in my script i loading all related object to that class. the related object are the optional keys in the game.
e.g
SHOOT1 = KeyboardSettings("SHOOT","q")
move_right = KeyboardSettings("move_right","d")
#and more keys
key_obj_lst = [SHOOT1,move_right....]
#also i built a dict a-z, 0,9
dict_key = { 'a' : pygame.K_a,
'b' : pygame.K_b,
'c' : pygame.K_c,
...
'z' : pygame.K_z,
'0' : pygame.K_0,
...
'1' : pygame.K_1,
'9' : pygame.K_9,
then in game loop:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
for k in key_obj_lst:
#define each key by user
if k.active:
k.keyboard = event.unicode
default = False
if k.keyboard in dict_key:
if event.key == dict_key[k.keyboard]:
if k.description == 'Moving Right':
moving_right = True
if k.description == 'SHOOT':
SHOOT = True
The code worked perfectly but i trully dont know how to add keys that not letters and numbers such as "ENTER","SPACE" etc.
pygame provides a function for getting the name of the key pressed:
pygame.key.name
And so you can use it to get the name of the key, there is no need to use a dictionary for this:
import pygame
pygame.init()
screen = pygame.display.set_mode((500, 400))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.KEYDOWN:
key_name = pygame.key.name(event.key)
print(key_name)
pip install keyboard
import keyboard #use keyboard module
while True:
if keyboard.is_pressed('SPACE'):
print('You pressed SPACE!')
break
elif keyboard.is_pressed("ENTER"):
print("You pressed ENTER.")
break
Use keyboard module
import keyboard
while True:
print(f"You pressed {keyboard.get_hotkey_name()})

Simultaneous mouse press events in Python using Pynput

I am using scrcpy to mirror an Android phone to my computer in order to play a game. The issue is that scrcpy does not support keyboard mapping natively, so I'm writing a Python script to map the keyboard to execute the key presses I need to play the game (using WASD to move around, space to jump, etc.).
I'm fairly new to programing in general and to Python in particular, but so far it's been going pretty well using Pynput. Basically, I am mapping different keys on my keyboard to correspond to mouse clicks on different areas of the screen. My issue is that, as written, my script can only push one left mouse press event at a time.
For example, pressing "w" (to move forward) and space (jump) at the same time will move the cursor to different areas on the screen, and will therefore not result in the desired outcome. The game itself supports simultaneous touch input when played on an Android screen (I can press different areas on the screen at the same time to execute certain actions), so ideally I would need my script to be able to recreate this behavior.
I was wondering if there was a way to do this in Python?
from pynput.mouse import Button, Controller
from pynput.keyboard import Key, KeyCode, Listener
global MOUSE
MOUSE = Controller()
global CENTER
global HEIGHT
CENTER = 315
HEIGHT = 800
global LISTEN
def cust_click(x,y):
MOUSE.position = (x,y)
MOUSE.press(Button.left)
def cust_mvmt_click(x, y):
MOUSE.position = (CENTER, HEIGHT)
MOUSE.press(Button.left)
MOUSE.move(x, y)
#WASD movement
def w():
cust_mvmt_click(0, -100)
def s():
cust_mvmt_click(0, 100)
def a():
cust_mvmt_click(-100, 0)
def d():
cust_mvmt_click(100, 0)
#Miscellaneous
def space():
cust_click(CENTER*5.75,HEIGHT*0.95)
def c():
cust_click(CENTER*5.15, HEIGHT*1.2)
#Weapon controls
def r():
cust_click(CENTER*4.75, HEIGHT*1.15)
def f():
cust_click(CENTER*0.5, HEIGHT*0.7)
def ctrl():
cust_click(CENTER*5.15, HEIGHT)
def q():
cust_click(CENTER*5.3, HEIGHT*0.77)
def switch1():
cust_click(CENTER*2.75, HEIGHT*1.15)
def switch2():
cust_click(CENTER*3.3, HEIGHT*1.15)
def switch3():
cust_click(CENTER*3, HEIGHT*1.05)
def on_press(key):
if key == KeyCode(char='w'):
w()
elif key == KeyCode(char='f'):
f()
elif key == Key.shift_l:
ctrl()
elif key == KeyCode(char='q'):
q()
elif key == KeyCode(char='s'):
s()
elif key == KeyCode(char='a'):
a()
elif key == KeyCode(char='d'):
d()
elif key == KeyCode(char='c'):
c()
elif key == KeyCode(char='r'):
r()
elif key == Key.space:
space()
elif key == KeyCode(char='1'):
switch1()
elif key == KeyCode(char='2'):
switch2()
elif key == KeyCode(char='3'):
switch3()
elif key == Key.tab:
LISTEN.stop()
def on_release(key):
if key == Key.shift_l or key == KeyCode(char='1') or key == KeyCode(char='f') or key == KeyCode(char='2') or key == KeyCode(char='3') or key == KeyCode(char='r') or key == KeyCode(char='c') or key == KeyCode(char='s') or key == KeyCode(char='a') or key == KeyCode(char='d') or key == Key.space or key == KeyCode(char='q') or key == KeyCode(char='w'):
MOUSE.release(Button.left)
MOUSE.position = (CENTER*390/100,HEIGHT*70/100) #1235, 565
# Collect events until released
with Listener(
on_press=on_press,
on_release=on_release) as LISTEN:
LISTEN.join()
You can use pydirectinput or pydirectinput-rgx for clicking. Check
https://www.google.com/url?sa=t&source=web&rct=j&url=https://pypi.org/project/PyDirectInput/&ved=2ahUKEwi9sbb7w6b6AhXE23MBHV85ChgQFnoECBEQAQ&usg=AOvVaw2EChi0UGXZlMafbw1aHhod
for its documentation.

How do i detect which specific button in my controller is being released in pygame

i am trying to detect which button is being pressed from my controller and when it is released.
This is how far i have managed to get.
import pygame
pygame.init()
j = pygame.joystick.Joystick(0)
j.init()
try:
while True:
events = pygame.event.get()
for event in events:
if event.type == pygame.JOYBUTTONDOWN:
if j.get_button(1):
print("x")
elif j.get_button(2):
print("a")
elif event.type == pygame.JOYBUTTONUP:
print("button released")
except KeyboardInterrupt:
print("EXITING NOW")
j.quit()
i am new to programming and i dont entirely understand this piece of code.
this detects if x or a is being pressed and if any button is being released. I want it to detect if x or a is being pressed and when they are released.
Thanks for reading!
pygame.event.get() returns a list of events(events are a type of structure/object of pygame generated when the user does something moves mouse / presses buttons e.t.c.).then for each of those events you check if the they are the event you want(pygame.JOYBUTTONDOWN or event.type,pygame.JOYBUTTONUP).
you can only check if a button is pressed and then see which button is pressed.
if event.type == pygame.JOYBUTTONDOWN:
if j.get_button(1):
print("x")
elif j.get_button(2):
print("a")
to see when buttons get released best way i can think off is having a list of Button Status .When the status for a button changes you do something .
ButtonStatus[2];
ButtonStatus[0]=get_button(1);#a
ButtonStatus[1]=get_button(2);#x
if event.type == pygame.JOYBUTTONUP:
if ButtonStatus[0]!=get_button(1)
#status changed do yr code for button release a
pass;
if ButtonStatus[1]!=get_button(2)
#status changed do yr code for button release b
pass;
above code is a sample not actually compiled . general idea is to check when a button is released,check which button changes status and execute code accordingly.
So, i coded what i needed with the help of the other answers!
import pygame
pygame.init()
j = pygame.joystick.Joystick(0)
j.init()
r = 2
t = 5
b = 1
x = 3
try:
while True:
events = pygame.event.get()
for event in events:
if event.type == pygame.JOYBUTTONDOWN:
if j.get_button(1):
print("B")
b = 2
elif j.get_button(2):
print("X")
x = 5
elif event.type == pygame.JOYBUTTONUP:
if b == r :
print("b2")
b = 1
if x == t:
print("x2")
x = 3
except KeyboardInterrupt:
print("EXITING NOW")
j.quit()
This isn't robust in any way. You need to make new strings for every button you need.
You do that by copying the button with the biggest variables and just adding 3 to every variable in the code you coppied. Please answer the original post if you can give a better answer (which probably exists).Also, when u press multiple buttons at the same time and u release atleast one it thinks you have realeased all of them.

How do I make it so that while a key is pressed and another key is released an action occurs? (Pygame/python)

So basically I'm making a quiz game in which the user must "lock in" their answer. In order to do that the user must press a certain key while pressing another. For example: holding the "w" key while pressing and letting go of the space bar.But when I try to achieve this, nothing happens. Here is what I have so far:
if (event.type == pygame.KEYDOWN) and (event.key == pygame.K_w) and (event.type == pygame.KEYUP) and (event.key == pygame.K_SPACE):
print(1)
why doesn't this work?
One way is to use pygame.key.get_pressed(). Example -
keys = pygame.keys.get_pressed()
if keys[pygame.K_w] and keys[pygame.K_SPACE]:
print(1)
EDIT : This is how I implemented it -
#!/usr/bin/python3
import pygame
from pygame.locals import *
from sys import exit
#initializing variables
pygame.init()
screen=pygame.display.set_mode((640,480),0,24)
pygame.display.set_caption("Key Press Test")
f1=pygame.font.SysFont("comicsansms",24)
#main loop which displays the pressed keys on the screen
while True:
for i in pygame.event.get():
a=100
screen.fill((255,255,255))
if pygame.key.get_focused():
press=pygame.key.get_pressed()
# checking if they are pressed at the same time or not.
if press[pygame.K_w] and press[pygame.K_SPACE]:
print (1)
for i in xrange(0,len(press)):
if press[i]==1:
name=pygame.key.name(i)
text=f1.render(name,True,(0,0,0))
screen.blit(text,(100,a))
a=a+100
pygame.display.update()
question_num = general_knowlege_questions[0]
keys = pygame.key.get_pressed()
if keys[pygame.K_w] and (General_knowledge[question_num][5] == "a"):
test = 1
if keys[pygame.K_d] and (General_knowledge[question_num][5] == "b"):
test = 1
if keys[pygame.K_s] and (General_knowledge[question_num][5] == "c"):
test = 1
if keys[pygame.K_a] and (General_knowledge[question_num][5] == "d"):
test = 1
so basically this is my code to recognize my answer for the quiz, but it ends up not recognizing the correct answer. Btw the General_knowledge variable is a list, question number is self explanitory and 5 is the index that contains the answer.

Categories

Resources