added restrict_cursor.py and hexagon.html testpage

This commit is contained in:
merijn 2021-01-05 12:18:56 +01:00
parent cc505355b3
commit 6e6bb2a3aa
2 changed files with 129 additions and 0 deletions

53
hexagon.html Normal file
View file

@ -0,0 +1,53 @@
<style>
*{
background: #555;
}
</style>
<svg height="1000" width="1000" id="svg">
</svg>
<script>
// remember to put browser on full-screen
// define hexagon params here
let center_X = 400,
center_Y = 300,
radius = 200;
let hexa = hexa_vertices(center_X, center_Y, radius);
let svg = document.getElementById('svg');
let hexagon = document.createElementNS('http://www.w3.org/2000/svg','polygon');
hexagon.setAttribute("points",
`${hexa[0].x},${hexa[0].y}
${hexa[1].x},${hexa[1].y}
${hexa[2].x},${hexa[2].y}
${hexa[3].x},${hexa[3].y}
${hexa[4].x},${hexa[4].y}
${hexa[5].x},${hexa[5].y}
`);
hexagon.style="fill: #e5e5e5";
svg.append(hexagon)
function hexa_vertices(cX, cY, r){
let verts = [];
verts[0] = {x: cX+r*Math.cos(0), y: cY+r*Math.sin(0)};
for(let i=1; i<=6; i++){
verts[i] = {x: cX+r*Math.cos(i*2*Math.PI/6), y: cY+r*Math.sin(i*2*Math.PI/6)};
}
return verts;
}
</script>

76
restrict_cursor.py Normal file
View file

@ -0,0 +1,76 @@
import math
from pynput import mouse
from pynput.mouse import Button, Controller
ct = Controller()
# mouse position
start_pos = (500, 200)
ct.position = start_pos
# displacement margin (px)
d_margin = 2
# hexagon parameters
centerX=400
centerY=300
radius=200
def hexa_points(cx, cy, r):
points=[None]*6
points[0]=(cx+r*math.cos(0), cy+r*math.sin(0))
for i in range(1,6):
points[i]=( int(cx+r*math.cos(i*2*math.pi/6)), int(cy+r*math.sin(i*2*math.pi/6)) )
return points
hexagon = hexa_points(centerX, centerY, radius)
# print(hexagon)
def update_position(p, pi, pj):
relative=(pj[0]-pi[0], pj[1]-pi[1])
normal=(relative[1],-relative[0])
magnitude=math.sqrt((normal[0]*normal[0])+(normal[1]*normal[1]))
normal_unit=(normal[0]/magnitude, normal[1]/magnitude)
displacement=((p[0]-pi[0])*normal_unit[0])+((p[1]-pi[1])*normal_unit[1])
# print(displacement)
if (displacement > d_margin):
return ( int(p[0]-normal_unit[0]*displacement), int(p[1]-normal_unit[1]*displacement) )
else:
return False
def keep_in_hexagon(point, hexagon):
for i in range(0,6):
j=i+1
if j==6:
j=0
# print("point: "+str(point)+" pi: "+str(hexagon[i])+" pj: "+str(hexagon[j]))
updated_point=update_position(point, hexagon[i], hexagon[j])
if updated_point:
print("[OOB] "+str(point)+' => '+str(updated_point))
ct.position = updated_point
def on_move(x, y):
keep_in_hexagon((x, y), hexagon)
# click to stop listening
def on_click(x, y, button, pressed):
print('{0} at {1}'.format(
'Pressed' if pressed else 'Released',
(x, y)))
if not pressed:
return False
with mouse.Listener(
on_move=on_move,
on_click=on_click) as listener:
listener.join()