在Python的循环的多次迭代中执行一次操作

时间:2013-02-08 09:48:09

标签: python loops

我正在编写的代码在屏幕上显示一个形状,并允许通过上/下箭头键操纵形状。我一直试图让它做的是使形状的变化量取决于按键的顺序;只要输入与初始按键相同,形状变化的量就会很大。然而,当按键发生第一次'反转'时(例如,进行微调),在该点之后的每次按键(无论是否与初始按钮按下相同)都应该以更小的比例改变圆圈(不是积极的,只有0.1厘米的变化,而不是2厘米)。代码是用Psychopy编写的。

我认为我没有理解应该为此设置循环的方式,但我看不出它们如何被改变以做我想要的。对于实际代码的道歉,而不是最小的例子 - 非常感谢任何建议。

for thisTrial in trials:
    endKey = 0
    nKeypress = 0
    count = 0
    counting = 0
    if thisTrial == 'ellipse':
        ellipseHeightinit = 7.6,1.9 + (round(numpy.random.uniform(-1,1),1))
    elif thisTrial == 'circle':
        ellipseHeightinit = 7.6,7.6 + (round(numpy.random.uniform(-1,1),1))
    ellipseHeight = ellipseHeightinit
    ellipseStim.setSize(ellipseHeight, log = False) # set the initial size of the shape  
    while endKey == 0:
        ellipseStim.setAutoDraw(True)
        win.flip() # flip the window to see the stimuli
        allKeys = event.waitKeys() 
        if count < 1: #store the first keypress made
            for thisKey in allKeys:
                firstKeypress = thisKey
                count += 1
                event.clearEvents()
        for thisKey in allKeys: # change the size of the shape depending on key pressed
            if thisKey == 'up':
                nKeypress = nKeypress + 1
            elif thisKey == 'down':
                nKeypress = nKeypress - 1
            elif thisKey == 'space':
                endKey = 1
            while counting < 1: # attempt to make step size large until reversal
                if thisKey == firstKeypress:
                    ellipseHeight = 7.6, ellipseHeightinit[1] + nKeypress*20
                    break
                elif thisKey != firstKeypress:
                    ellipseHeight = 7.6, ellipseHeightinit[1] + nKeypress*0.1
                    counting += 1
                    break
       ellipseStim.setSize(ellipseHeight, log = False) # set new shape size     
    ellipseStim.setAutoDraw(False)

1 个答案:

答案 0 :(得分:1)

你应该存储最后一个按键的位置,这是上次使用的移动量。如果按下的新键相同,则会增加金额。否则,您将其设置为最小值。