Is there any way I can speed up my macro that records keyboard and mouse movements? (Python) - performance

I was creating this keyboard and mouse macro that I could use. I wanted to be able to speed the process up. The playback isn't very fast because it only goes as fast as I can record it. I would want to make sure that both the mouse and keyboard are faster so they can sync. Is there any way that is possible? Such as clicking the space button will make it go 1.5x faster.
My code:
import mouse
import keyboard
import pyautogui
keyboard.wait('delete')
currentMouseX1, currentMouseY1 = pyautogui.position()
mouse_events = []
mouse.hook(mouse_events.append)
keyboard.start_recording()
keyboard.wait("delete")
mouse.unhook(mouse_events.append)
keyboard_events = keyboard.stop_recording()
#Keyboard threadings:
while True:
pyautogui.moveTo(currentMouseX1, currentMouseY1)
k_thread = threading.Thread(target = lambda :keyboard.play(keyboard_events))
k_thread.start()
#Mouse threadings:
m_thread = threading.Thread(target = lambda :mouse.play(mouse_events))
m_thread.start()
#waiting for both threadings to be completed
k_thread.join()
m_thread.join()```

Related

GODOT - Full Attack Animation Not Playing

I have this simple game i made in Godot Game Engine, and i have implemented some animations in my game's main character.
1. Run
This is a simple run animation i've added, which is played when the character is moving
2. Idle
This animation is more like a single image which is played when the character is not moving
3. Attack
This animation is played when user presses Left Mouse Button.
I am having my issue in attack animation, when i press Left Mouse Button my Animation doesn't play, instead i get first frame of the animation and then character goes back to idle Animation.
This is how it looks like:
This is my Character's Code:
extends KinematicBody2D
var _inputVec = Vector2.ZERO
var VELOCITY = Vector2.ZERO
var LAST_INPUT = Vector2.ZERO
const MAX_SPEED = 70
const ACCELERATION = 500
const FRICTION = 500
onready var animationPlayer = $AnimationPlayer
func _ready():
print("game started!")
func _physics_process(delta):
_inputVec.x = Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left")
_inputVec.y = Input.get_action_strength("ui_down") - Input.get_action_strength("ui_up")
_inputVec = _inputVec.normalized()
if _inputVec != Vector2.ZERO:
if _inputVec.x > 0:
animationPlayer.play("playerRunRight")
elif _inputVec.y < 0:
animationPlayer.play("playerRunUp")
elif _inputVec.y > 0:
animationPlayer.play("playerRunDown")
else:
animationPlayer.play("playerRunLeft")
VELOCITY = VELOCITY.move_toward(_inputVec * MAX_SPEED, ACCELERATION * delta)
LAST_INPUT = _inputVec
else:
VELOCITY = VELOCITY.move_toward(Vector2.ZERO, FRICTION * delta)
if Input.is_action_just_pressed("ui_lmb"):
if LAST_INPUT.x > 0:
animationPlayer.play("playerAttackRight")
elif LAST_INPUT.y < 0:
animationPlayer.play("playerAttackUp")
elif LAST_INPUT.y > 0:
animationPlayer.play("playerAttackDown")
else:
animationPlayer.play("playerAttackLeft")
else:
if LAST_INPUT.x > 0:
animationPlayer.play("playerIdleRight")
elif LAST_INPUT.y < 0:
animationPlayer.play("playerIdleUp")
elif LAST_INPUT.y > 0:
animationPlayer.play("playerIdleDown")
else:
animationPlayer.play("playerIdleLeft")
VELOCITY = move_and_slide(VELOCITY)
Full Project is Available at my Github Repo
Remember that _physics_process runs once per (physics) frame.
So, one frame you pressed the left mouse button, and this line got to execute:
animationPlayer.play("playerAttackRight")
But next (physics) frame, you had not just pressed the left mouse button, so this conditional is false:
if Input.is_action_just_pressed("ui_lmb"):
And then this line get to execute:
animationPlayer.play("playerIdleRight")
As a result, you only see about one frame of the "playerAttackRight" animation.
You are going to need to keep track of the current state (running, attacking, idle). The rule is that you can change from running to idle immediately, but you can only change from attacking to idle, when the attack animation ends.
You can keep track of the current state with a variable, of course. You can take input and the value of the state of the variable to decide the new state. Then separately read the state variable and decide which animation to play. You may also want to set the state variable when some animations end.
And to do something when an animation ends, you can either resource to yield:
yield(animationPlayer, "animation_finished")
Which will have your code resume after it receives the "animation_finished" signal.
Or, otherwise you can connect to the "animation_finished" signal.
By the way, you can also queue animations:
animationPlayer.queue("name_of_some_animation")
While using AnimationPlayer like you do is OK. When it gets complex, there is another tool you should consider: AnimationTree.
Create an AnimationTree node, give it your animation player, and set the root to a new AnimationNodeStateMachine. There you can create your state machine, and configure if the transition between them is immediate or at the end.
Then, from code, you can get the state machine playback object, like this:
var state_machine = $AnimationTree.get("parameters/playback")
You can ask it what the current state is with:
var state:String = state_machine.get_current_node()
Which you can use as part of the decision of which state you want to go to. And then tell it you want it to go to a different state, like this:
state_machine.travel("name_of_some_state")
And using that it will respect the transitions you set, so you do not have to worry about it in code.
You can find more information about using AnimationTree at:
Using AnimationTree
Controlling Animation States

What is a reasonable widget count in a GTK3 application?

We have a Python GTK application with a large number of widgets 3-4k.
When porting from GTK2 to GTK3 we noticed a rather big performance hit when:
Adding widgets.
Simply showing (not creating) windows.
My question is: Is this a bug, or is it simply unreasonable to use many thousands of widgets in a GTK3 application?
The following test program perf.py shows both problems:
import sys
import gi
import time
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class DialogExample(Gtk.Dialog):
def __init__(self, parent):
Gtk.Dialog.__init__(self, "My Dialog", parent, 0,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_OK, Gtk.ResponseType.OK))
label = Gtk.Label("The snappiness of this dialog depends on the number of \nwidgets in the main program.")
self.get_content_area().add(label)
self.show_all()
class DialogWindow(Gtk.Window):
def __init__(self, count):
Gtk.Window.__init__(self, title="Dialog Example")
box = Gtk.Box()
self.add(box)
button = Gtk.Button("Open dialog")
button.connect("clicked", self.on_button_clicked)
box.pack_start(button, expand=False, fill=True, padding=0)
# Add dummy widgets to show effect
for n in xrange(count):
button = Gtk.Button(str(n))
button.set_no_show_all(True)
t = time.time()
box.pack_start(button, expand=False, fill=True, padding=0)
print('{}\t{:.3f}'.format(n, 1000*(time.time()-t)))
def on_button_clicked(self, widget):
dialog = DialogExample(self)
dialog.run()
dialog.destroy()
count = int(sys.argv[1])
win = DialogWindow(count)
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
The time to add a widget increases for each widget.
The time it takes to display a dialog is affected by the total widget count in the application.
The Python script takes a command line parameter which is the number of (hidden) widgets to create and prints the existing widget count and the time to add it.
$ python perf.py 20000
0 0.026
1 0.021
...
20000 1.700
At 20000 widgets, point 1 is pretty clear even on fast hardware. Point 2 might require slower hardware or double the widget count to be clearly visible.
The image below displays the widget creation time that goes from around 20 microseconds to 6 ms.
Number one is only somewhat unexpected, but the second point was totally unexpected to me.
I have tested this in Gtk 3.18 on three different machines.
Part of the main application window:

Link a tkinter button to seperate script

I have a tkinter interface with a few entry widgets as inputs. Upon clicking a button I would like those inputs to be sent to a separate script to be processed and a value printed and potentially returned back to the button (I am looking at this for a dual accuracy assessment statistic)
This is a lower scale example of what I have so far and am looking to accomplish
Example Secondary Script: GUI_ConnectorScript
def calculate():
global result
result = int(entry.get())
result += 1
print result
Primary Script: GUI_ConnectorScript
from Tkinter import *
import GUI_ConnectorScript
background = "#A8A8A8"
master = Tk()
screen_width = master.winfo_screenwidth()
screen_height = master.winfo_screenheight()
width = int(screen_width*0.7)
height = int(screen_height*0.7)
size = "%sx%s"%(width,height)
master.geometry(size)
master.title("GIS Display")
text = Text(master, width = 80, height = 40, background = background)
text.pack(expand = TRUE, fill = BOTH)
entry = Entry(master, width=5).place(x=100,y=100)
button = Button(master, text="Calculate", command=GUI_ConnectorScript).place(x=500,y=500)
mainloop()
I have been trying to figure this out for awhile and have look around a lot for an answer. I have found examples similar but I am having an issue getting it to work for my application.
I agree with Parviz, whenever GUI programs get too complicated you should use Object-Oriented Programming.
I can further advice that you use kivy (if possible) instead of tkinter, its much better for bigger projects

How to handle sprite animation in Kivy

I am coding a game using Kivy. I have a Screen class where I put my animation code. It's not a usual game, it's more like several screens, each with its own animation, with button commands for going back and forth to different screens.
It works ok, but when I make more classes like this and put it all in a ScreenManager, the animation is disrupted with random white screens.
class Pas(Screen):
def __init__(self, **kwargs):
super(Pas, self).__init__(**kwargs)
Clock.schedule_interval(self.update, 1 / 60.0)
self.ani_speed_init = 15
self.ani_speed = self.ani_speed_init
self.ani = glob.glob("img/pas_ani*.png")
self.ani.sort()
self.ani_pos = 0
self.ani_max = len(self.ani)-1
self.img = self.ani[0]
self.update(1)
back = Button(
background_normal=('img/back-icon.png'),
background_down=('img/back-icon.png'),
pos=(380, 420))
self.add_widget(back)
def callback(instance):
sm.current = 'game'
back.bind(on_press=callback)
def update(self, dt):
self.ani_speed -= 1
if self.ani_speed == 0:
self.img = self.ani[self.ani_pos]
self.ani_speed = self.ani_speed_init
if self.ani_pos == self.ani_max:
self.ani_pos = 0
else:
self.ani_pos += 1
with self.canvas:
image = Image(source=self.img, pos=(0, 0), size=(320, 480))
What am I doing wrong? I am also accepting ideas for a different way of doing this.
If you want to use Screen and ScreenManager for your screens, it would be better to use the transition system they define and use, so, to define your own Transitions, and apply them. If you want more control, i would advise getting ride of Screen and ScreenManager, and just using Widgets, to control the whole drawing/positioning process.
Also, Clock.schedule_interval(self.update, 0) is equivalent to the call you are making, the animation will be called each frame, and you can use dt to manage the animation progress.
Also, kivy can manage gifs, as well as zip archives of images to directly do animations (useful to have animated pngs), you can let kivy manage the whole animation process this way.

How to Get a Window or Fullscreen Screenshot (without PIL)?

With python 3, I'd like to get a handle to another window (not part of my application) such that I can either:
directly capture that window as a screenshot, or
determine its position and size and capture it some other way
In case it is important, I am using Windows XP (edit: works in Windows 7 also).
I found this solution, but it is not quite what I need since it is full screen and more importantly, PIL to the best of my knowledge does not support 3.x yet.
Here's how you can do it using PIL on win32. Given a window handle (hwnd), you should only need the last 4 lines of code. The preceding simply search for a window with "firefox" in the title. Since PIL's source is available, you should be able to poke around the ImageGrab.grab(bbox) method and figure out the win32 code you need to make this happen.
from PIL import ImageGrab
import win32gui
toplist, winlist = [], []
def enum_cb(hwnd, results):
winlist.append((hwnd, win32gui.GetWindowText(hwnd)))
win32gui.EnumWindows(enum_cb, toplist)
firefox = [(hwnd, title) for hwnd, title in winlist if 'firefox' in title.lower()]
# just grab the hwnd for first window matching firefox
firefox = firefox[0]
hwnd = firefox[0]
win32gui.SetForegroundWindow(hwnd)
bbox = win32gui.GetWindowRect(hwnd)
img = ImageGrab.grab(bbox)
img.show()
Ars gave me all the pieces. I am just putting the pieces together here for anyone else who needs to get a screenshot in python 3.x. Next I need to figure out how to work with a win32 bitmap without having PIL to lean on.
Get a Screenshot (pass hwnd for a window instead of full screen):
def screenshot(hwnd = None):
import win32gui
import win32ui
import win32con
from time import sleep
if not hwnd:
hwnd=win32gui.GetDesktopWindow()
l,t,r,b=win32gui.GetWindowRect(hwnd)
h=b-t
w=r-l
hDC = win32gui.GetWindowDC(hwnd)
myDC=win32ui.CreateDCFromHandle(hDC)
newDC=myDC.CreateCompatibleDC()
myBitMap = win32ui.CreateBitmap()
myBitMap.CreateCompatibleBitmap(myDC, w, h)
newDC.SelectObject(myBitMap)
win32gui.SetForegroundWindow(hwnd)
sleep(.2) #lame way to allow screen to draw before taking shot
newDC.BitBlt((0,0),(w, h) , myDC, (0,0), win32con.SRCCOPY)
myBitMap.Paint(newDC)
myBitMap.SaveBitmapFile(newDC,'c:\\tmp.bmp')
Get a Window Handle by title (to pass to the above function):
def _get_windows_bytitle(title_text, exact = False):
def _window_callback(hwnd, all_windows):
all_windows.append((hwnd, win32gui.GetWindowText(hwnd)))
windows = []
win32gui.EnumWindows(_window_callback, windows)
if exact:
return [hwnd for hwnd, title in windows if title_text == title]
else:
return [hwnd for hwnd, title in windows if title_text in title]
This will take a new opened window and make a screenshot of it and then crop it with PIL also possible to find your specific window with pygetwindow.getAllTitles() and then fill in your window name in z3 to get screenshot of only that window.
If you definitely not want to use PIL you can maximize window with pygetwindow module and then make a screenshot with pyautogui module.
Note: not tested on Windows XP (but tested on Windows 10)
import pygetwindow
import time
import os
import pyautogui
import PIL
# get screensize
x,y = pyautogui.size()
print(f"width={x}\theight={y}")
x2,y2 = pyautogui.size()
x2,y2=int(str(x2)),int(str(y2))
print(x2//2)
print(y2//2)
# find new window title
z1 = pygetwindow.getAllTitles()
time.sleep(1)
print(len(z1))
# test with pictures folder
os.startfile("C:\\Users\\yourname\\Pictures")
time.sleep(1)
z2 = pygetwindow.getAllTitles()
print(len(z2))
time.sleep(1)
z3 = [x for x in z2 if x not in z1]
z3 = ''.join(z3)
time.sleep(3)
# also able to edit z3 to specified window-title string like: "Sublime Text (UNREGISTERED)"
my = pygetwindow.getWindowsWithTitle(z3)[0]
# quarter of screen screensize
x3 = x2 // 2
y3 = y2 // 2
my.resizeTo(x3,y3)
# top-left
my.moveTo(0, 0)
time.sleep(3)
my.activate()
time.sleep(1)
# save screenshot
p = pyautogui.screenshot()
p.save(r'C:\\Users\\yourname\\Pictures\\\\p.png')
# edit screenshot
im = PIL.Image.open('C:\\Users\\yourname\\Pictures\\p.png')
im_crop = im.crop((0, 0, x3, y3))
im_crop.save('C:\\Users\\yourname\\Pictures\\p.jpg', quality=100)
# close window
time.sleep(1)
my.close()
The solution here gets a screenshot of a single Window (so can work if the Window is in the background).
Other solutions of this page take picture of the part of the screen the window is on, and thus need to bring the Window to the front first.
Python Screenshot of inactive window PrintWindow + win32gui

Resources