Skip to content

Instantly share code, notes, and snippets.

@allcaps
Created January 4, 2018 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allcaps/8f570c638b58fa6aee304625560b74a3 to your computer and use it in GitHub Desktop.
Save allcaps/8f570c638b58fa6aee304625560b74a3 to your computer and use it in GitHub Desktop.
import sys
import math
import pygame
from itertools import combinations
pygame.init()
maxfps = 30
size = width, height = 320, 240
black = 0, 0, 0
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Click and drag to create a gesture')
dont_burn_my_cpu = pygame.time.Clock()
def square_distance(p1, p2):
((x1, y1), (x2, y2)) = (p1, p2)
return math.hypot(x2 - x1, y2 - y1)
def max_distance_pair(points):
if len(points) <= 1:
raise ValueError("Expects iterable with multiple values")
max_pair = points[:2]
max_square_distance = 0
for pair in combinations(points, 2):
if square_distance(*pair) > max_square_distance:
max_square_distance = square_distance(*pair)
max_pair = pair
return max_pair
def get_angle(p1, p2):
""" The angle between two points where north is 0 degrees """
((x1, y1), (x2, y2)) = (p1, p2)
x = x2 - x1
y = y2 - y1
angle = math.degrees(math.atan2(y, x))
angle += 90
if angle < 0:
angle += 360
return angle
class GestureFactory:
bodies = []
points = None
def add_body(self, body):
self.bodies.append(body)
if len(self.bodies) > 10:
self.bodies.pop(0)a
self.find_gestures()
def clear_bodies(self):
self.bodies = []
def find_gestures(self):
if len(self.bodies) >= 3:
p1, p2 = max_distance_pair(self.bodies)
distance = square_distance(p1, p2)
if distance > 100:
angle = get_angle(p1, p2)
print("{}'".format(angle))
self.points = (p1, p2)
self.clear_bodies()
gesture_factory = GestureFactory()
pygame.mouse.set_visible(True)
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# Somehow Pygame doesn't update the mouse pos. Only on drag.
if event.type == pygame.MOUSEBUTTONDOWN:
gesture_factory.clear_bodies()
elif event.type == pygame.MOUSEBUTTONUP:
gesture_factory.clear_bodies()
else:
pos = pygame.mouse.get_pos()
print("pos", pos)
gesture_factory.add_body(pos)
screen.fill(black)
if gesture_factory.points:
pygame.draw.line(screen, (255, 255, 255), gesture_factory.points[0], gesture_factory.points[1], 18)
pygame.draw.circle(screen, (255, 0, 0), gesture_factory.points[1], 24, 0)
pygame.display.flip()
dont_burn_my_cpu.tick(maxfps)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment