Ende eines Trials durch Chance anstatt durch Anzahl

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
Stefan90
User
Beiträge: 5
Registriert: Mittwoch 24. Juni 2020, 18:06

Hallo Leute!

Ich bin mir nicht sicher ob dies das richtige Forum ist, die anderen Unterforen jedoch schienen mir noch weniger zu meinem Problem zu passen. :-)

Zur Zeit programmiere ich eine Variante der Balloon Analogue Risk Task. Es geht darum daß man 90 mal Ballons "aufbläst" und je nachdem, wie groß ein Ballon geworden ist, man einen bestimmten Geldbetrag für den Ballon bekommt. Der Ballon kann allerdings auch platzen, dann bekommt man gar nichts.

Ich bin noch ein Anfänger und habe das Platzen des Ballons bisher nur mit absoluten Werten gelöst. Ich würde es aber echt gerne mit einer gleichmäßig zunehmenden Wahrscheinlichkeit lösen, nur leider weiß ich nicht wie ich es anstellen soll die Wahrscheinlichkeit zu updaten.

Zur Zeit sieht es so aus:
while continueRoutine:
.
.
.
if event.getKeys(['space']):
nPumps=nPumps+1
if nPumps>maxPumps:
popped=True
continueRoutine=False

"nPumps" startete bei 0 und wurde bei jedem klicken der Leertaste um +1 erhöht. "maxPumps" ist in einer Exceldatei vorgegeben, je nach Condition, mit 8, 32 und 128. Ich möchte diese Werte dahingehend verändern, daß für Condition 1 die Chance, daß der Ballon platzt, bei 1/8 beginnt, bei Condition 2 1/32 und bei Conditon 3 1/128, und dass sich diese Werte mit jedem drücken der Leertaste um sich selbst erhöhen, oder der Ballon halt platzt. Tja, und das ist mein Problem, ich verstehe nicht wie ich gleichzeitig diese Zahl updaten kann und der bisher erreichte Wert gleichzeitig aber auch das Ende der Routine erwirken kann.
Könnt ihr mir einen Tipp geben?

Vielen Dank im Voraus!

Liebe Grüße,
Stefan
nezzcarth
User
Beiträge: 1764
Registriert: Samstag 16. April 2011, 12:47

Die Einfachste Variante ist, dass du mit random.random Zufallszahlen zwischen 0 und 1 erzeugst und einen Schwellwert setzt, der beim Unterschreiten zum Platzen des Ballons führt. Diesen erhöhst du dann in gleichmäßigen Abständen um einen festen Werten. Wenn du es etwas ausgefeilter machen möchtest, findest du im Random Modul zusätzlich auch verschiedene Möglichkeiten, Zufallszahlen aus einer bestimmten Wahrscheinlichkeitsverteilung zu ziehen (z.B. Normalverteilung, Dreiecksverteilung etc.).

Beispiel:

Code: Alles auswählen

#!/usr/bin/env python3
from random import random

def main():
    threshold = 0.01
    step = 0.01
    while True and threshold < 1.0:
        n = random()
        print('N:', n, 'threshold:', threshold)
        if n < threshold:
            print('Plopp!')
            break
        threshold += step


if __name__ == '__main__':
    main()

Ach, 'nPump' oder 'continueRoutine' sind keine guten Bezeichner. In Python werden Variablennamen klein mit Unterstrich geschrieben: continue_routine.
Stefan90
User
Beiträge: 5
Registriert: Mittwoch 24. Juni 2020, 18:06

Danke für deine Antwort, nezzcarth!

Verstehe ich deinen Code richtig wenn ich ihn wie folgt interpretiere?
Es wird ein Zufallswert (zwischen 0 und 1) zu Beginn jedes Trials generiert, und ich lasse mit der condition, die gerade zufällig bei dem jeweiligen Ballon dran ist, mit dem entsprechenden Wert von 0 an additiv gegen diesen Wert laufen - also bspw. 1/8 ...+ 1/8 .... + 1/8, etc?
Dann könnte der Ballon beim ersten Drücken der Leertaste theoretisch platzen, aber die Chance ist nicht 1/8, richtig?
Hm... ich nehme an daß du diese Lösung vorschlägst weil alles andere viel schwieriger wäre, oder? :D

Ach und danke für deinen Tipp! Ich muss mir die Großbuchstaben mal abgewöhnen. :-)

LG
Stefan
nezzcarth
User
Beiträge: 1764
Registriert: Samstag 16. April 2011, 12:47

Du verwendest glaube ich zu viele Fachbegriffe :) Die wenigsten hier werden wissen, wie psychologische Experimente aufgebaut sind und was du mit Trial, Condition usw. meinst. Was ich versucht habe zu zeigen, ist ein allgemeiner Mechanismus, mit dem du mit linear ansteigender Wahrscheinlichkeit eine Schleife verlassen kannst. Dies kannst du auch einfach abwandeln, indem du zum Beispiel die Art, wie der Threshold erhöht wird änderst usw. Wie du das Gezeigte in deine Simulation einbaust, kann ich auf der bisherigen Grundlage leider nicht beurteilen. Falls du die Möglichkeit hast, dein Vorhaben noch mal etwas allgemeinverständlicher zu erklären, kann man dir vielleicht gezielter helfen.
Stefan90
User
Beiträge: 5
Registriert: Mittwoch 24. Juni 2020, 18:06

Uff, bitte verzeih' mir mein Fachgelaber, das hatte ich gar nicht auf dem Schirm! :-)
Ich versuche das Geschehen ein mal ohne Fachbegriffe zu erklären, mein Gefühl sagt mir deine Erklärung ist sehr nah an dem was ich suche. :-)

Stell dir vor du bekommst einen Ballon und eine Zahl (Gewinn in €) zu sehen. Der Ballon ist schrumpelig, luftleer, und die Zahl steht bei 0€. Du kannst jetzt entscheiden, ob du die Leertaste drückst, und damit etwas Luft in den Ballon pustest, oder ob du deinen bisherigen Gewinn von 0€ behalten möchtest. Wenn du die Leertaste drückst, kann der Ballon entweder platzen, oder nicht. Wenn er nicht platzt, erhöht sich dein Geldbetrag um 50 Cent. Dann hast du wieder die Wahl, ob du den Gewinn - jetzt 50 Cent - nimmst, oder ob du nochmal pustest, den Ballon damit größer machst und insgesamt 1€ an Gewinn hast. Das kann sich "unendlich" oft wiederholen. Wenn er irgendwann platzt erhältst du nichts, und ich lege dir den nächsten Ballon vor (es gibt insgesamt 90 Ballons).

Die Chance, dass ein Ballon platzt, soll nun vor dem ersten Pusten (bei 0€) bereits eine gewisse Wahrscheinlichkeit haben: 1 zu 8, 1 zu 32, oder 1 zu 128. Diese Zahlen habe ich bereits in einem Excel-Dokument vorgegeben. Das sind meine "Conditions".
Was ich mich frage, ist, ob ich diese Wahrscheinlichkeiten linear aufaddieren lassen kann, sodaß sie bei jedem Mal wo du erneut die Leertaste drückst ein Vielfaches der genannten Basiswerte als Wahrscheinlichkeit hast, dass der Ballon platzt. Im ersten Fall startest du bei 1/8, und wenn du Glück hast kannst du 7 mal die Leertaste drücken, dann ist die Chance daß der Ballon platzt 8/8=1 und du solltest den Geldbetrag behalten und zum nächsten Ballon übergehen. :D Jedoch kann der Ballon auch schon beim ersten mal platzen, die Chance dafür sollte 1/8=12.5% sein.

Ich hoffe ich habe den Gedanken hinter dem Experiment etwas deutlicher machen können?

Edit: Ich habe dein Script jetzt endlich komplett verstanden, nachdem ich es in Python ein paar mal laufen lies. Ich glaube ich war zu fixiert auf den Gedanken, daß sich der Wert an sich erhöhen soll, weswegen ich zunächst nicht verstanden habe, wie dein Script funktioniert. Wenn ich es jetzt richtig verstehe, dann bietet es ja eine Lösung für mein Problem. :oops: Hoffentlich bin ich gerade nicht zu euphorisch (es fällt mir nicht so leicht, generelle, allgemeingültige Formeln zu verstehen), aber das wäre echt ein Traum...

Würdest du, oder jemand anders, mir erklären, was

Code: Alles auswählen

if __name__ == '__main__':
    main()
ganz am Ende des Dokuments bewirkt? Ich weiß nicht was die funktion von "__name__" ist und warum es dem Namen der Funktion gleichgesetzt wird - und warum man Unterstriche vor und hinter den Namen der Funktion macht, das wurde ja so gar nicht definiert. :oops:
nezzcarth
User
Beiträge: 1764
Registriert: Samstag 16. April 2011, 12:47

Danke für deine Erklärung. Hier noch einmal ein anderes Beispiel, das dem ersten sehr ähnlich ist, aber vielleicht konzeptuell etwas näher an dem dran ist, wie du dir das genau vorstellst (wenn ich es richtig verstanden habe):

Code: Alles auswählen

#!/usr/bin/env python3
from itertools import count
from random import random

def main():
    conditions = [1/8, 1/32, 1/128]
    
    for condition in conditions:
        print('Condition:', condition)
        for blow in count(1):
            print('Blow:', blow)
            probability = condition * blow
            print('Probability:', probability)
            n = random()
            print('N:', n)
            if n < probability:
                print('Boom!')
                break
        print('-' * 79)


if __name__ == '__main__':
    main()
Anders als im ersten Beispiel, wo konstant um 0.01 erhöht wurde, ist es hier abhängig von deiner Condition.

Python-Module können ohne weiteres in andere importiert werden. Dabei wird jedoch aller Code, der nicht in Funktionen steckt, ausgeführt, was man normalerweise nicht möchte. Daher schreibt man diesen Code in eine Funktion; Code in Funktionen wird erst ausgeführt, wenn die Funktion aufgerufen wurde. Die beiden Zeilen am Schluss sagen im Prinzip nur 'wenn das Modul direkt gestartet wurde, führe die Funktion main aus'. '__name__' ist ein in Python eingebauter Name ("Variable") -- das zeigen die Unterstriche unter anderem an -- der an den Wert '__main__' gebunden wird, wenn das Skript direkt gestartet und nicht importiert wurde. Das ist zusammen mit der main Funktion ein sehr übliches Idiom, das man in sehr vielen Python Skripten findet und sich angewöhnen sollte
Stefan90
User
Beiträge: 5
Registriert: Mittwoch 24. Juni 2020, 18:06

Vielen, vielen Dank für die Erklärung und das Beispiel mit etwas mehr Zahlen. :-) Ja, du hast mit beiden Codes ziemlich genau das getroffen, was ich brauche.
Ich schreibe morgen noch mal, ich merke daß ich viel zu müde bin und den Code nicht richtig eingebettet bekomme. Aber ich habe auch viel zu viel Python-Code, wurde alles von einem Programm ausgegeben in dem man sich Experimente über ein GUI zusammenklicken kann - und damit komme ich auf über 500 Zeilen. Und viel mehr als das, was ich beschrieben habe, ist es nicht, außer einem Introbildschirm. Da muss ich also nochmal ran. :-)
Stefan90
User
Beiträge: 5
Registriert: Mittwoch 24. Juni 2020, 18:06

Guten morgen, ich hoffe ihr verzeiht mir den Doppelpost!

Ich habe deinen Vorschlag nun "modifiziert" integriert, d.h. ich habe ihn nicht als Funktion integriert weil ich nicht weiß, ob es dann funktioniert.
Es sieht im Moment so aus:

Code: Alles auswählen

        
        if event.getKeys(['space']):
            threshold = PopChance
            step = PopChance
            while True and threshold < 1.0:
                n = random()
                if n < threshold:
                    popped=True
                    #print('Plopp!')
                    #break
                    continueRoutine=False
                threshold += step
"An sich" funktioniert das Script, nur platzt jetzt jeder Ballon beim ersten Drücken der Leertaste. Woher das kommt, weiß ich noch nicht. An den in der Excel-Datei vorgegebenen Zahlen scheint es nicht zu liegen. Die werden zwar in Excel mit Komma dargestellt, aber wenn ich bspw. aus dem Komma einen Punkt mache (weil Python für Dezimalzahlen ja Punkte verwendet), dann endet das Script komplett nach dem ersten Drücken der Leertaste. Mit Komma gibt es wenigstens die 90 Wiederholungen, aber wie gesagt, jeder Luftballon platzt sofort.
Das muss ich noch austüfteln. :-)

Liebe Grüße

Hierdrunter übrigens das ganze Script für diejenigen die interessiert sind. Wie gesagt, es wurde von einem Programm erstellt, daher ist es wahrscheinlich viel länger als es müsste. Das einzige was ich in dem Programm nicht einstellen kann ist das Problem um das es hier im Thread geht, deswegen muss ich an den Python code ran. :-)

[spoiler]

Code: Alles auswählen


from __future__ import absolute_import, division
from psychopy import locale_setup
from psychopy import prefs
from psychopy import sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED, STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np  # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average, sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os  # handy system and path functions
import sys  # to get file system encoding
from psychopy.hardware import keyboard
from random import random

# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)

# Store info about the experiment session
psychopyVersion = '2020.1.3'
expName = 'bart'  # from the Builder filename that created this script
expInfo = {'participant ID': '', 'session': '', 'gender (d/f/m)': '', 'age': ''}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
    core.quit()  # user pressed cancel
expInfo['date'] = data.getDateStr()  # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion



#def main():
#    threshold = PopChance
#    step = PopChance
#    while True and threshold < 1.0:
#        n = random()
#        if n < threshold:
#            print('Plopp!')
#            break
#        threshold += step



# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + 'data' + os.sep + '%s_%s' % (expInfo['participant ID'], expInfo['date'])

# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
    extraInfo=expInfo, runtimeInfo=None,
    originPath='C:\\Users\\Sir Quappi\\Desktop\\Python\\THE\\bart_lastrun.py',
    savePickle=True, saveWideText=True,
    dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.WARNING)
logging.console.setLevel(logging.WARNING)  # this outputs to the screen, not a file

endExpNow = False  # flag for 'escape' or other condition => quit the exp
frameTolerance = 0.001  # how close to onset before 'same' frame

# Start Code - component code to be run before the window creation

# Setup the Window
win = visual.Window(
    size=[1920, 1080], fullscr=True, screen=0, 
    winType='pyglet', allowGUI=False, allowStencil=False,
    monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
    blendMode='avg', useFBO=True)
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
    frameDur = 1.0 / round(expInfo['frameRate'])
else:
    frameDur = 1.0 / 60.0  # could not measure, so guess

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "instructions"
instructionsClock = core.Clock()
instrMessage = visual.TextStim(win=win, name='instrMessage',
    text="This is a game where you have to optimise your earnings in a balloon pumping competition.\n\nYou get prize money for each balloon you pump up, according to its size. But if you pump it too far it will pop and you'll get nothing for that balloon.\n\nBalloons differ in their maximum size - they can occasionally reach to almost the size of the screen but most will pop well before that.\n\nPress;\n    SPACE to pump the balloon\n    RETURN to bank the cash for this balloon and move onto the next\n",
    font='Arial',
    pos=[0, 0], height=0.05, wrapWidth=None, ori=0, 
    color='white', colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=0.0);
resp = keyboard.Keyboard()

# Initialize components for Routine "trial"
trialClock = core.Clock()
bankedEarnings=0.0
lastBalloonEarnings=0.0
thisBalloonEarnings=0.0
balloonSize=0.08
balloonMsgHeight=0.01
balloonBody = visual.ImageStim(
    win=win,
    name='balloonBody', 
    image='redBalloon.png', mask=None,
    ori=0, pos=[0,0], size=1.0,
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-2.0)
reminderMsg = visual.TextStim(win=win, name='reminderMsg',
    text='Press SPACE to pump the balloon\nPress RETURN to bank this sum',
    font='Arial',
    pos=[0, -0.8], height=0.05, wrapWidth=None, ori=0, 
    color='white', colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=-3.0);
balloonValMsg = visual.TextStim(win=win, name='balloonValMsg',
    text='default text',
    font='Arial',
    pos=[0,0.05], height=0.1, wrapWidth=None, ori=0, 
    color='white', colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=-4.0);
bankedMsg = visual.TextStim(win=win, name='bankedMsg',
    text='default text',
    font='Arial',
    pos=[0, 0.8], height=0.1, wrapWidth=None, ori=0, 
    color='white', colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=-5.0);
bankButton = keyboard.Keyboard()

# Initialize components for Routine "feedback"
feedbackClock = core.Clock()
feedbackText=""
from psychopy import sound
bang = sound.Sound("bang.wav")

feedbackMsg = visual.TextStim(win=win, name='feedbackMsg',
    text='default text',
    font='Arial',
    pos=[0, 0], height=0.1, wrapWidth=None, ori=0, 
    color='white', colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=-1.0);

# Initialize components for Routine "finalScore"
finalScoreClock = core.Clock()
finalScore_2 = visual.TextStim(win=win, name='finalScore_2',
    text='default text',
    font='Arial',
    pos=[0, 0], height=0.1, wrapWidth=None, ori=0, 
    color='white', colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=0.0);
doneKey = keyboard.Keyboard()

# Create some handy timers
globalClock = core.Clock()  # to track the time since experiment started
routineTimer = core.CountdownTimer()  # to track time remaining of each (non-slip) routine 

# ------Prepare to start Routine "instructions"-------
continueRoutine = True
# update component parameters for each repeat
resp.keys = []
resp.rt = []
_resp_allKeys = []
# keep track of which components have finished
instructionsComponents = [instrMessage, resp]
for thisComponent in instructionsComponents:
    thisComponent.tStart = None
    thisComponent.tStop = None
    thisComponent.tStartRefresh = None
    thisComponent.tStopRefresh = None
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
instructionsClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1

# -------Run Routine "instructions"-------
while continueRoutine:
    # get current time
    t = instructionsClock.getTime()
    tThisFlip = win.getFutureFlipTime(clock=instructionsClock)
    tThisFlipGlobal = win.getFutureFlipTime(clock=None)
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame
    
    # *instrMessage* updates
    if instrMessage.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        instrMessage.frameNStart = frameN  # exact frame index
        instrMessage.tStart = t  # local t and not account for scr refresh
        instrMessage.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(instrMessage, 'tStartRefresh')  # time at next scr refresh
        instrMessage.setAutoDraw(True)
    
    # *resp* updates
    waitOnFlip = False
    if resp.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        resp.frameNStart = frameN  # exact frame index
        resp.tStart = t  # local t and not account for scr refresh
        resp.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(resp, 'tStartRefresh')  # time at next scr refresh
        resp.status = STARTED
        # keyboard checking is just starting
        waitOnFlip = True
        win.callOnFlip(resp.clock.reset)  # t=0 on next screen flip
        win.callOnFlip(resp.clearEvents, eventType='keyboard')  # clear events on next screen flip
    if resp.status == STARTED and not waitOnFlip:
        theseKeys = resp.getKeys(keyList=None, waitRelease=False)
        _resp_allKeys.extend(theseKeys)
        if len(_resp_allKeys):
            resp.keys = _resp_allKeys[-1].name  # just the last key pressed
            resp.rt = _resp_allKeys[-1].rt
            # a response ends the routine
            continueRoutine = False
    
    # check for quit (typically the Esc key)
    if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
        core.quit()
    
    # check if all components have finished
    if not continueRoutine:  # a component has requested a forced-end of Routine
        break
    continueRoutine = False  # will revert to True if at least one component still running
    for thisComponent in instructionsComponents:
        if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
            continueRoutine = True
            break  # at least one component has not yet finished
    
    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

# -------Ending Routine "instructions"-------
for thisComponent in instructionsComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
thisExp.addData('instrMessage.started', instrMessage.tStartRefresh)
thisExp.addData('instrMessage.stopped', instrMessage.tStopRefresh)
# check responses
if resp.keys in ['', [], None]:  # No response was made
    resp.keys = None
thisExp.addData('resp.keys',resp.keys)
if resp.keys != None:  # we had a response
    thisExp.addData('resp.rt', resp.rt)
thisExp.addData('resp.started', resp.tStartRefresh)
thisExp.addData('resp.stopped', resp.tStopRefresh)
thisExp.nextEntry()
# the Routine "instructions" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# set up handler to look after randomisation of conditions etc
trials = data.TrialHandler(nReps=30.0, method='fullRandom', 
    extraInfo=expInfo, originPath=-1,
    trialList=data.importConditions('Trials.xlsx'),
    seed=None, name='trials')
thisExp.addLoop(trials)  # add the loop to the experiment
thisTrial = trials.trialList[0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
if thisTrial != None:
    for paramName in thisTrial:
        exec('{} = thisTrial[paramName]'.format(paramName))

for thisTrial in trials:
    currentLoop = trials
    # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
    if thisTrial != None:
        for paramName in thisTrial:
            exec('{} = thisTrial[paramName]'.format(paramName))
    
    # ------Prepare to start Routine "trial"-------
    continueRoutine = True
    # update component parameters for each repeat
    balloonSize=0.08
    popped=False
    nPumps=0
    bankButton.keys = []
    bankButton.rt = []
    _bankButton_allKeys = []
    # keep track of which components have finished
    trialComponents = [balloonBody, reminderMsg, balloonValMsg, bankedMsg, bankButton]
    for thisComponent in trialComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    trialClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1
    
    # -------Run Routine "trial"-------
    while continueRoutine:
        # get current time
        t = trialClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=trialClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        thisBalloonEarnings=nPumps*0.05
        balloonSize=0.1+nPumps*0.015
        
        # *balloonBody* updates
        if balloonBody.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            balloonBody.frameNStart = frameN  # exact frame index
            balloonBody.tStart = t  # local t and not account for scr refresh
            balloonBody.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(balloonBody, 'tStartRefresh')  # time at next scr refresh
            balloonBody.setAutoDraw(True)
        if balloonBody.status == STARTED:  # only update if drawing
            balloonBody.setPos([0, -0.4], log=False)
            balloonBody.setSize(balloonSize, log=False)
        
        # *reminderMsg* updates
        if reminderMsg.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            reminderMsg.frameNStart = frameN  # exact frame index
            reminderMsg.tStart = t  # local t and not account for scr refresh
            reminderMsg.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(reminderMsg, 'tStartRefresh')  # time at next scr refresh
            reminderMsg.setAutoDraw(True)
        
        # *balloonValMsg* updates
        if balloonValMsg.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            balloonValMsg.frameNStart = frameN  # exact frame index
            balloonValMsg.tStart = t  # local t and not account for scr refresh
            balloonValMsg.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(balloonValMsg, 'tStartRefresh')  # time at next scr refresh
            balloonValMsg.setAutoDraw(True)
        if balloonValMsg.status == STARTED:  # only update if drawing
            balloonValMsg.setText(u"This balloon value:\n€%.2f" %thisBalloonEarnings, log=False)
        
        # *bankedMsg* updates
        if bankedMsg.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            bankedMsg.frameNStart = frameN  # exact frame index
            bankedMsg.tStart = t  # local t and not account for scr refresh
            bankedMsg.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(bankedMsg, 'tStartRefresh')  # time at next scr refresh
            bankedMsg.setAutoDraw(True)
        if bankedMsg.status == STARTED:  # only update if drawing
            bankedMsg.setText(u"You have banked:\n€%.2f" %bankedEarnings, log=False)
        
        if event.getKeys(['space']):
            threshold = PopChance
            step = PopChance
            while True and threshold < 1.0:
                n = random()
                if n < threshold:
                    popped=True
                    #print('Plopp!')
                    #break
                    continueRoutine=False
                threshold += step

          
          #nPumps=nPumps+1
          #if nPumps>maxPumps:
          #  popped=True
          #  continueRoutine=False
        
        #*bankButton* updates
        waitOnFlip = False
        if bankButton.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            bankButton.frameNStart = frameN  # exact frame index
            bankButton.tStart = t  # local t and not account for scr refresh
            bankButton.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(bankButton, 'tStartRefresh')  # time at next scr refresh
            bankButton.status = STARTED
            # keyboard checking is just starting
            waitOnFlip = True
            win.callOnFlip(bankButton.clock.reset)  # t=0 on next screen flip
            win.callOnFlip(bankButton.clearEvents, eventType='keyboard')  # clear events on next screen flip
        if bankButton.status == STARTED and not waitOnFlip:
            theseKeys = bankButton.getKeys(keyList=['return'], waitRelease=False)
            _bankButton_allKeys.extend(theseKeys)
            if len(_bankButton_allKeys):
                bankButton.keys = _bankButton_allKeys[-1].name  # just the last key pressed
                bankButton.rt = _bankButton_allKeys[-1].rt
                # a response ends the routine
                continueRoutine = False
        
        # check for quit (typically the Esc key)
        if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
            core.quit()
        
        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in trialComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished
        
        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()
    
    # -------Ending Routine "trial"-------
    for thisComponent in trialComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    #calculate cash 'earned'
    if popped:
      thisBalloonEarnings=0.0
      lastBalloonEarnings=0.0
    else:   lastBalloonEarnings=thisBalloonEarnings
    bankedEarnings = bankedEarnings+lastBalloonEarnings
    #save data
    trials.addData('nPumps', nPumps)
    trials.addData('size', balloonSize)
    trials.addData('earnings', thisBalloonEarnings)
    trials.addData('popped', popped)
    
    
    trials.addData('balloonBody.started', balloonBody.tStartRefresh)
    trials.addData('balloonBody.stopped', balloonBody.tStopRefresh)
    trials.addData('reminderMsg.started', reminderMsg.tStartRefresh)
    trials.addData('reminderMsg.stopped', reminderMsg.tStopRefresh)
    trials.addData('balloonValMsg.started', balloonValMsg.tStartRefresh)
    trials.addData('balloonValMsg.stopped', balloonValMsg.tStopRefresh)
    trials.addData('bankedMsg.started', bankedMsg.tStartRefresh)
    trials.addData('bankedMsg.stopped', bankedMsg.tStopRefresh)
    # the Routine "trial" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()
    
    # ------Prepare to start Routine "feedback"-------
    continueRoutine = True
    routineTimer.add(1.500000)
    # update component parameters for each repeat
    if popped==True:
      feedbackText="Too greedy!"
      bang.play()
    else:
      feedbackText=u"You banked €%.2f" %lastBalloonEarnings
    
    feedbackMsg.setText(feedbackText)
    # keep track of which components have finished
    feedbackComponents = [feedbackMsg]
    for thisComponent in feedbackComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    feedbackClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1
    
    # -------Run Routine "feedback"-------
    while continueRoutine and routineTimer.getTime() > 0:
        # get current time
        t = feedbackClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=feedbackClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame
        
        # *feedbackMsg* updates
        if feedbackMsg.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
            # keep track of start time/frame for later
            feedbackMsg.frameNStart = frameN  # exact frame index
            feedbackMsg.tStart = t  # local t and not account for scr refresh
            feedbackMsg.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(feedbackMsg, 'tStartRefresh')  # time at next scr refresh
            feedbackMsg.setAutoDraw(True)
        if feedbackMsg.status == STARTED:
            # is it time to stop? (based on global clock, using actual start)
            if tThisFlipGlobal > feedbackMsg.tStartRefresh + 1.5-frameTolerance:
                # keep track of stop time/frame for later
                feedbackMsg.tStop = t  # not accounting for scr refresh
                feedbackMsg.frameNStop = frameN  # exact frame index
                win.timeOnFlip(feedbackMsg, 'tStopRefresh')  # time at next scr refresh
                feedbackMsg.setAutoDraw(False)
        
        # check for quit (typically the Esc key)
        if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
            core.quit()
        
        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in feedbackComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished
        
        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()
    
    # -------Ending Routine "feedback"-------
    for thisComponent in feedbackComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    trials.addData('feedbackMsg.started', feedbackMsg.tStartRefresh)
    trials.addData('feedbackMsg.stopped', feedbackMsg.tStopRefresh)
    thisExp.nextEntry()
    
# completed 1.0 repeats of 'trials'

# get names of stimulus parameters
if trials.trialList in ([], [None], None):
    params = []
else:
    params = trials.trialList[0].keys()
# save data for this loop
trials.saveAsExcel(filename + '.xlsx', sheetName='trials',
    stimOut=params,
    dataOut=['n','all_mean','all_std', 'all_raw'])

# ------Prepare to start Routine "finalScore"-------
continueRoutine = True
# update component parameters for each repeat
finalScore_2.setText(u"Well done! You banked a total of\n€%2.f" %bankedEarnings)
doneKey.keys = []
doneKey.rt = []
_doneKey_allKeys = []
# keep track of which components have finished
finalScoreComponents = [finalScore_2, doneKey]
for thisComponent in finalScoreComponents:
    thisComponent.tStart = None
    thisComponent.tStop = None
    thisComponent.tStartRefresh = None
    thisComponent.tStopRefresh = None
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
finalScoreClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1

# -------Run Routine "finalScore"-------
while continueRoutine:
    # get current time
    t = finalScoreClock.getTime()
    tThisFlip = win.getFutureFlipTime(clock=finalScoreClock)
    tThisFlipGlobal = win.getFutureFlipTime(clock=None)
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame
    
    # *finalScore_2* updates
    if finalScore_2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        finalScore_2.frameNStart = frameN  # exact frame index
        finalScore_2.tStart = t  # local t and not account for scr refresh
        finalScore_2.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(finalScore_2, 'tStartRefresh')  # time at next scr refresh
        finalScore_2.setAutoDraw(True)
    
    # *doneKey* updates
    waitOnFlip = False
    if doneKey.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        doneKey.frameNStart = frameN  # exact frame index
        doneKey.tStart = t  # local t and not account for scr refresh
        doneKey.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(doneKey, 'tStartRefresh')  # time at next scr refresh
        doneKey.status = STARTED
        # keyboard checking is just starting
        waitOnFlip = True
        win.callOnFlip(doneKey.clock.reset)  # t=0 on next screen flip
        win.callOnFlip(doneKey.clearEvents, eventType='keyboard')  # clear events on next screen flip
    if doneKey.status == STARTED and not waitOnFlip:
        theseKeys = doneKey.getKeys(keyList=None, waitRelease=False)
        _doneKey_allKeys.extend(theseKeys)
        if len(_doneKey_allKeys):
            doneKey.keys = _doneKey_allKeys[-1].name  # just the last key pressed
            doneKey.rt = _doneKey_allKeys[-1].rt
            # a response ends the routine
            continueRoutine = False
    
    # check for quit (typically the Esc key)
    if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
        core.quit()
    
    # check if all components have finished
    if not continueRoutine:  # a component has requested a forced-end of Routine
        break
    continueRoutine = False  # will revert to True if at least one component still running
    for thisComponent in finalScoreComponents:
        if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
            continueRoutine = True
            break  # at least one component has not yet finished
    
    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

# -------Ending Routine "finalScore"-------
for thisComponent in finalScoreComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
thisExp.addData('finalScore_2.started', finalScore_2.tStartRefresh)
thisExp.addData('finalScore_2.stopped', finalScore_2.tStopRefresh)
# check responses
if doneKey.keys in ['', [], None]:  # No response was made
    doneKey.keys = None
thisExp.addData('doneKey.keys',doneKey.keys)
if doneKey.keys != None:  # we had a response
    thisExp.addData('doneKey.rt', doneKey.rt)
thisExp.addData('doneKey.started', doneKey.tStartRefresh)
thisExp.addData('doneKey.stopped', doneKey.tStopRefresh)
thisExp.nextEntry()
# the Routine "finalScore" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# Flip one final time so any remaining win.callOnFlip() 
# and win.timeOnFlip() tasks get executed before quitting
win.flip()

# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort()  # or data files will save again on exit
win.close()
core.quit()


[/spoiler]
Antworten