generate mouse velocity when only integer steps are allowed
<p>I write a simple program in python which includes moving my mouse (I do his with <a href="https://github.com/PyUserInput/PyUserInput" rel="nofollow">PyUserInput</a>).
However: It is only allowed to move the mouse in integer steps (say pixels).
So <code>mouse.move(250.3,300.2)</code> won't work.</p>

<p>I call the move function about 30 times in a second and move the mouse a few pixels. The speed with which I move the mouse varies from 0.5-2.5px/call. Rounding gives me 1-3 (move only want ints) which does not really represent the speed.</p>

<p>I search for a solution (maybe generator?) which takes my current speed (e.g. 0.7px) and gives me back a pattern (like a PWM Signal) out of 0 and 1 (e.g. <code>1,1,0,1,1,0...</code>) which yields the 0.7px in average.
However this generator has to be adaptive because speed is constantly changing.</p>

<p>I am quite new to python and stuck with the last point: The variability of the generator function.</p>

<p>Here is what I have so far:</p>

<pre><code># for 0.75px/call
def getPWM(n):
    nums = [1,0,1,1]
    yield nums[n%4]
</code></pre>

<p>What you need to do is keep track of the previous position and the desired current position, and hand out the rounded coordinate. You could track the previous position in a function but it's much easier to do it in a class.</p>

<pre><code>class pwm:
    def __init__(self):
        self.desired_position = 0.0
        self.actual_position = 0

    def nextPWM(self, speed):
        self.desired_position += speed
        movement = round(self.desired_position - self.actual_position)
        self.actual_position += movement
        return movement
</code></pre>

python