Pygame on psychopy

OS: MacOS Monterey and Windows 11 Pro
PsychoPy version: 2021.2.3
Standard Standalone? : yes
What are you trying to achieve?: My python script runs without errors outside PsychoPy (on PyCharm, VSCode, etc.). Now because of my experiment design, I need to add it on PsychoPy Builder. It’s an interactive script which gets mouse clicks and creates a route. On every session, I need to create this route and then keep it on the screen for my task, which is navigating on this route.

What specifically went wrong when you tried that?: I can’t even import pygame on psychopy builder. Also, I don’t know which part of the script to insert into “Begin Experiment”, “Begin routine”, “each frame”, etc.

Here’s the script:

import pygame
from scipy import interpolate
import numpy as np

def B_spline(waypoints):
    x = []
    y = []
    for point in waypoints:
        x.append(point[0])
        y.append(point[1])
    tck, *rest = interpolate.splprep([x, y])
    u = np.linspace(0, 1, num = 500)
    smooth = interpolate.splev(u, tck)
    return smooth

smooth = []
controlpoints = []

pygame.init()
pygame.display.set_caption("RRT path planning")
map = pygame.display.set_mode((800, 512))
map.fill((255, 255, 255))
running = True
while (running):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()
            pygame.draw.circle(map, (0,0,0), pos, 7 , 0)
            controlpoints.append(pos)
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE: 
                smooth = B_spline(controlpoints)
                x_smooth, y_smooth = smooth
                map.fill((255, 255, 255))
                for x, y in zip(x_smooth, y_smooth):
                    pygame.draw.circle(map, (255, 0, 0), (x, y), 2, 0)
                for point in controlpoints:
                    pygame.draw.circle(map, (0, 0, 0), point, 7, 0)

    pygame.display.update()

Were you ever able to solve this? I’m having a very similar issue. Thanks!