python curses - .getch() in newwin not working - python

I am attempting to make menu system using the curses module. I have the following code:
import sys, os, traceback, curses
def main(scrn):
screen = scrn
screen.border(0)
curses.start_color()
curses.init_pair(2,curses.COLOR_WHITE,curses.COLOR_BLUE)
while True:
event = screen.getch()
if event == ord("q"):
break
elif event == curses.KEY_RIGHT:
#enter function containing while loop, passing job
job_sub()
#loop to hand the subscreen for a job element
def job_sub():
screen = curses.newwin(5, 10, 3, 3)
screen.box()
objects =["RUN", "MAINTAIN", "EDIT"]
for i in range( len(objects) ):
if i == 0:
screen.addstr(i+1,1, objects[i], curses.color_pair(2))
else:
screen.addstr(i+1,1, objects[i])
screen.refresh()
while True:
event = screen.getch()
if event == curses.KEY_LEFT:
break
screen.erase()
return
if __name__=='__main__':
try:
# Initialize curses
screen=curses.initscr()
curses.noecho()
curses.cbreak()
screen.keypad(1)
main(screen)
screen.keypad(0)
curses.echo()
curses.nocbreak()
curses.endwin()
except:
# In event of error, restore terminal to sane state.
screen.keypad(0)
curses.echo()
curses.nocbreak()
curses.endwin()
traceback.print_exc()
The program runs until I hit the right arrow key. After that, it freezes, like it's stuck in a loop. It won't respond to any more input. Any help is appreciated.

In your job_sub() function you create a new window but you don't enable the keypad for it. As a result the arrow key is not sending a curses.KEY_LEFT value.

Related

python keyboard wont stop once key is pressed

I have an endless loop in MAIN and ive looked at it so many times.
def click(x,y):
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
time.sleep(0.05)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
def click_x_box(Box_x_axis, X_axis, Y_Axis_top, Y_Axis_bottom):
#[Check if pixel is RED from top]
while pyautogui.pixel(X_axis, Y_Axis_top)[0] == 255 and pyautogui.pixel(X_axis, Y_Axis_top)[1] != 255:
# click function has no loops
click(Box_x_axis, Y_Axis_top)
Y_Axis_top += 19
print("finished top-down loop")
#[Check if pixel is RED from bottom]
while pyautogui.pixel(X_axis, Y_Axis_bottom)[0] == 255 and pyautogui.pixel(X_axis, Y_Axis_bottom)[1] != 255:
click(Box_x_axis, Y_Axis_bottom)
Y_Axis_bottom -= 19
print("finished bottom-up loop")
After I press 'q' once the "keyboard.is_pressed" line will keep re-going through, I dont know why it keeps getting through if 'q' is not being held down?
def main():
# Continue unticking boxes while 'q' is held
print("Hold 'q' to start clearing out the page of red")
while True:
if keyboard.is_pressed("q") == True:
print("q is pressed")
click_x_box(Box_x_axis, X_axis, Y_Axis_top, Y_Axis_bottom)
if __name__ == "__main__":
main()
EDIT
Ive figured out that when for whatever reason the click function is still engaging despite there being no 255,0,0 (red) on screen...

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.

Is there any way to detect mouse move in python curses? [duplicate]

I want to detect mouse movement events with python-curses. I don't know how to enable these events. I tried to enable all mouse-events as follows:
stdscr = curses.initscr()
curses.mousemask(curses.REPORT_MOUSE_POSITION | curses.ALL_MOUSE_EVENTS)
while True:
c = stdscr.getch()
if c == curses.KEY_MOUSE:
id, x, y, z, bstate = curses.getmouse()
stdscr.addstr(curses.LINES-2, 0, "x: " + str(x))
stdscr.addstr(curses.LINES-1, 0, "y: " + str(y))
stdscr.refresh()
if c == ord('q'):
break
curses.endwin()
I only get mouse-events when a mouse-button is clicked, pushed-down, etc but no mouse move events. How do I enable these events?
I got it to work by changing my $TERM env var / terminfo. On Ubuntu it worked by simply setting TERM=screen-256color, but on OSX I had to edit a terminfo file, using the instructions here:
Which $TERM to use to have both 256 colors and mouse move events in python curses?
but for me the format was different so I added the line:
XM=\E[?1003%?%p1%{1}%=%th%el%;,
To test it, I used this Python code (note screen.keypad(1) is very necessary, otherwise mouse events cause getch to return escape key codes).
import curses
screen = curses.initscr()
screen.keypad(1)
curses.curs_set(0)
curses.mousemask(curses.ALL_MOUSE_EVENTS | curses.REPORT_MOUSE_POSITION)
curses.flushinp()
curses.noecho()
screen.clear()
while True:
key = screen.getch()
screen.clear()
screen.addstr(0, 0, 'key: {}'.format(key))
if key == curses.KEY_MOUSE:
_, x, y, _, button = curses.getmouse()
screen.addstr(1, 0, 'x, y, button = {}, {}, {}'.format(x, y, button))
elif key == 27:
break
curses.endwin()
curses.flushinp()

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 to enable mouse movement events in python-curses

I want to detect mouse movement events with python-curses. I don't know how to enable these events. I tried to enable all mouse-events as follows:
stdscr = curses.initscr()
curses.mousemask(curses.REPORT_MOUSE_POSITION | curses.ALL_MOUSE_EVENTS)
while True:
c = stdscr.getch()
if c == curses.KEY_MOUSE:
id, x, y, z, bstate = curses.getmouse()
stdscr.addstr(curses.LINES-2, 0, "x: " + str(x))
stdscr.addstr(curses.LINES-1, 0, "y: " + str(y))
stdscr.refresh()
if c == ord('q'):
break
curses.endwin()
I only get mouse-events when a mouse-button is clicked, pushed-down, etc but no mouse move events. How do I enable these events?
I got it to work by changing my $TERM env var / terminfo. On Ubuntu it worked by simply setting TERM=screen-256color, but on OSX I had to edit a terminfo file, using the instructions here:
Which $TERM to use to have both 256 colors and mouse move events in python curses?
but for me the format was different so I added the line:
XM=\E[?1003%?%p1%{1}%=%th%el%;,
To test it, I used this Python code (note screen.keypad(1) is very necessary, otherwise mouse events cause getch to return escape key codes).
import curses
screen = curses.initscr()
screen.keypad(1)
curses.curs_set(0)
curses.mousemask(curses.ALL_MOUSE_EVENTS | curses.REPORT_MOUSE_POSITION)
curses.flushinp()
curses.noecho()
screen.clear()
while True:
key = screen.getch()
screen.clear()
screen.addstr(0, 0, 'key: {}'.format(key))
if key == curses.KEY_MOUSE:
_, x, y, _, button = curses.getmouse()
screen.addstr(1, 0, 'x, y, button = {}, {}, {}'.format(x, y, button))
elif key == 27:
break
curses.endwin()
curses.flushinp()

Categories

Resources