Draw a sequence of polygons by repeating the same component - How?

OS: Win10
PsychoPy version: v2020.2.8

Hello everybody,
I just started using PsychoPy builder and I am trying to draw a sequence of rectangles, one after the other, along the X axis. In other words, I am trying to repeat the same polygon component of width w and height h, by shifting it to the right of +w units each time.
The end result should look like a piano keyboard, running from the left side of the screen to the right side of the screen. The “keyboard” should stay on screen throughout the trial.

I had started adding polygons into the trial routine, but then ended up giving up as I realised that I should have drawn too many polygons (n = 90).
Thus, I thought I could possibly achieve my goal by using a for loop and drawing the same polygon and opened the PsychoPy Coder.

I thought I could wrap a for-loop around the code in the Run Routine “trial” chunk (see snippet below), but that did not work.

    # *myRectangle* updates
    if myRectangle.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        myRectangle.frameNStart = frameN  # exact frame index
        myRectangle.tStart = t  # local t and not account for scr refresh
        myRectangle.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(myRectangle, 'tStartRefresh')  # time at next scr refresh
        myRectangle.setAutoDraw(True)

Could anybody give me any advice on how to draw the “piano keyboard” on the screen?
Any hint is welcome and apologies for the basic question.

Thank you all very much!
Valerio

Just had a crack at this in Builder, I think if you put this in the Begin Routine tab of a Code component it should draw roughly what you want:

# Specify keyboard properties
nKeys = 90
width = 2
padding = 0.2 # Proportional to keysize
# Create blank array to store keys in
keys = [None]*nKeys
# for each key...
for n in range(nKeys):
    # Calculate key position and width
    x = n*(width/nKeys)-width/2
    w = (width-padding*width)/nKeys
    # Draw key
    keys[n] = visual.Rect(win,
        size=(w, 0.5),
        pos=(x, 0),
        fillColor="white",
        units="height",
        autoDraw=True)

just replace nKeys, width and padding with whatever values you need.

1 Like