Why isn't my break inside if statement working?

84 Views Asked by At

I have a code that has an if statment inside a for loop. This if statment has a break condition at the end of it. It isn't working and my code won't break during this condition. I have other codes similar to this and it works for them just for this case. I can't seen to understand why

Here is the snippet of code in question

# Counts when touch was outside of button 
elif distance_button.length() > button_radius:
    historylist.append(0) 
    distance_button_0 =
    pygame.math.Vector2(button_x_spacing,button_positionsy[0]) -        pygame.math.Vector2(pygame.mouse.get_pos())
    distance_button_1 =  pygame.math.Vector2(button_x_spacing,button_positionsy[1]) -     pygame.math.Vector2(pygame.mouse.get_pos())
    distance_button_2 = pygame.math.Vector2(button_x_spacing,button_positionsy[2]) - pygame.math.Vector2(pygame.mouse.get_pos())
    if distance_button_0.length() < button_radius:
        incorrectleft += 1
        timenow = time.time()
        writer.writerow([trialnum, 210, timenow - time_start])
    elif distance_button_1.length() < button_radius:
        incorrectmiddle += 1
        timenow = time.time()
        writer.writerow([trialnum, 211, timenow - time_start])
    elif distance_button_2.length() < button_radius:
        incorrectright += 1
        timenow = time.time()
        writer.writerow([trialnum, 212, timenow - time_start])       
    break

This is the total code

import pygame
import csv
import time
import sys
import os
import signal
import math
import random
from datetime import datetime
#import RPi.GPIO as GPIO
#from picamera2 import Picamera2
#from picamera2.encoders import H264Encoder


# Event Codes
# 0  ---first button display
# 1  ---second button display
# 2  ---third button display
# 100---plus sign onset
# 110---target onset
# 150---correct response 
# 200---reward onset
# 210---incorrect first button
# 211---incorrect second button
# 212---incorrect third button
# 216---never-reinforced error
# 250---timeout


# Constants
ITI = 2 # Inter-trial interval in seconds
plus = 0.5
Trial_Duration = 10
prep_time = 0
values = [0,1,2]
rewards_size = 1.2
rewardDelay = 0.5

# Reward Initialzation
#GPIO.setmode(GPIO.BCM)
#GPIO.setwarnings(False)
#rewardpin = 12
#GPIO.setup(rewardpin,GPIO.OUT)

# Initialize pygame starts
pygame.init()

# Set the dimensions of the screen
screen_width = 1275
screen_height = 750
WIDTH = 1280
HEIGHT = 720
FRAME_RATE = 60

# Set the colors
white = (255, 255, 255)
black = (0, 0, 0)
grey = (60, 60, 60)
pink = (255,127,127)
bright = (200, 200, 200)
yellow  = (255, 255, 000)
redorgreen = (255, 000, 000)
blue = (000, 000, 204)

colourlist = [yellow, redorgreen, blue]

screenfill = bright
button_colour = black

# Set the button properties
button_radius = 130
button_x_spacing = 450
button_y_spacing = 200

# Set the button positions
button_positionsy = [
    (button_y_spacing - 75),
    (button_y_spacing + 200),
    (button_y_spacing + 475)
]

button_positionsx = [
    (button_x_spacing),
    (button_x_spacing),
    (button_x_spacing)
]

# Drawing Star Function
def generate_star_points(center_x, center_y, outer_radius, inner_radius, points):
    star_points = []
    step = 2 * math.pi / points
    half_step = step / 2
    start_angle = -math.pi * 2 # Start the star with one point facing to the right

    for i in range(points):
        set_point = lambda angle, radius: (
            int(center_x + math.cos(angle - start_angle) * radius),
            int(center_y - math.sin(angle - start_angle) * radius)
        )
        outer_point_angle = i * step
        inner_point_angle = outer_point_angle + half_step
        star_points.append(set_point(outer_point_angle, outer_radius))
        star_points.append(set_point(inner_point_angle, inner_radius))

    return star_points

# Create the star points for each button
num_points = 5  # Number of points in the star
outer_radius = button_radius  # Outer radius of the star
inner_radius = button_radius * 0.5  # Inner radius of the star

# List for star points
button_star_points1 = generate_star_points(button_x_spacing, button_positionsy[0], outer_radius, inner_radius, num_points)
button_star_points2 = generate_star_points(button_x_spacing, button_positionsy[1], outer_radius, inner_radius, num_points)
button_star_points3 = generate_star_points(button_x_spacing, button_positionsy[2], outer_radius, inner_radius, num_points)
button_star_points = [button_star_points1, button_star_points2, button_star_points3]

def draw_centered_square(center_x, center_y, side_length):
    half_length = side_length / 2
    vertices = [
        (center_x - half_length, center_y - half_length),
        (center_x + half_length, center_y - half_length),
        (center_x + half_length, center_y + half_length),
        (center_x - half_length, center_y + half_length)
    ]
    return vertices

# List for square points
button_square_points1 = draw_centered_square(button_positionsx[0], button_positionsy[0], button_radius * 1.5)
button_square_points2 = draw_centered_square(button_positionsx[1], button_positionsy[1], button_radius * 1.5)
button_square_points3 = draw_centered_square(button_positionsx[2], button_positionsy[2], button_radius * 1.5)
button_square_points = [button_square_points1, button_square_points2, button_square_points3]

button_heart_points1 = []
button_heart_points2 = []
button_heart_points3 = []
num_points = 100  # Increase this value for a smoother heart shape
radius = button_radius

for i in range(num_points):
    angle = 2 * math.pi * i / num_points
    x1 = button_x_spacing + int(radius * (13 * math.cos(angle) - 5 * math.cos(2 * angle) - 2 * math.cos(3 * angle) - math.cos(4 * angle)) / 16)
    y1 = button_positionsy[0] + int(radius * math.sin(angle) ** 3)
    x2 = button_x_spacing + int(radius * (13 * math.cos(angle) - 5 * math.cos(2 * angle) - 2 * math.cos(3 * angle) - math.cos(4 * angle)) / 16)
    y2 = button_positionsy[1] + int(radius * math.sin(angle) ** 3)
    x3 = button_x_spacing + int(radius * (13 * math.cos(angle) - 5 * math.cos(2 * angle) - 2 * math.cos(3 * angle) - math.cos(4 * angle)) / 16)
    y3 = button_positionsy[2] + int(radius * math.sin(angle) ** 3)
    button_heart_points1.append((x1, y1))
    button_heart_points2.append((x2, y2))
    button_heart_points3.append((x3, y3))

button_heart_points = [button_heart_points1, button_heart_points2, button_heart_points3]

shapelist = [button_star_points, button_square_points, button_heart_points]

# Inputs
AnimalName = input("Animal Name: ")
trials = int(input("Number of trials: "))
target = int(input("Please choose the first target (star = 1, square = 2, heart = 3, yellow = 4, red/green = 5, blue = 6): " ))
target2 = int(input("Please choose the second target (star = 1, square = 2, heart = 3, yellow = 4, red/green = 5, blue = 6): " ))
target3 = int(input("Please choose the third target (star = 1, square = 2, heart = 3, yellow = 4, red/green = 5, blue = 6): " ))
target4 = int(input("Please choose the fourth target (star = 1, square = 2, heart = 3, yellow = 4, red/green = 5, blue = 6): " ))
target5 = int(input("Please choose the fifth target (star = 1, square = 2, heart = 3, yellow = 4, red/green = 5, blue = 6): " ))

targets = [target, target2, target3, target4, target5]

if target == 1:
    target_points  = button_star_points
    foil1_points  = button_square_points
    foil2_points  = button_heart_points
    color = False
elif target == 2:
    target_points  = button_square_points
    foil1_points  = button_star_points
    foil2_points  = button_heart_points
    color = False
elif target == 3:
    target_points  = button_heart_points
    foil1_points  = button_star_points
    foil2_points  = button_square_points
    color = False
elif target == 4:
    target_colour  = (255, 255, 000)
    foil1_colour = (255, 000, 000)
    foil2_colour = (000, 000, 204)
    foil = "red/green and blue"
    color = True
elif target == 5:
    target_colour = (255, 000, 000)
    foil1_colour  = (255, 255, 000)
    foil2_colour = (000, 000, 204)
    foil = "yellow and blue"
    color = True
elif target == 6:
    target_colour = (000, 000, 204)
    foil1_colour  = (255, 255, 000)
    foil2_colour = (255, 000, 000)
    foil = "yellow and red/green"
    color = True

# Setting up Camera
vidname = f"{AnimalName}_WCST_Step7_EDS&IDS_{datetime.now().strftime('%Y%m%d_%H%M%S')}_Video"

#def signal_handler(signal, frame):
#    print('Program exits normally.')
#    picam2.stop_recording()
#    picam2.stop()
#    os.system(f"ffmpeg -i {vidname}.h264 -vcodec copy {vidname}.mp4")
#    print("Save video sucessful.")
#    sys.exit(0)
#
#signal.signal(signal.SIGINT, signal_handler)
#picam2 = Picamera2()
#video_config = picam2.create_video_configuration(main={"size": (WIDTH, HEIGHT), "format": "RGB888"})
#picam2.configure(video_config)
#encoder = H264Encoder(10000000)
#picam2.start()
#picam2.set_controls({"FrameRate": FRAME_RATE})
#picam2.start_recording(encoder, f"{vidname}.h264")

# Initialize the screen
screen = pygame.display.set_mode((1080,720))

# Set the caption
pygame.display.set_caption("Marmoset Buttons")

# Set the counters
correctleft = 0
correctmiddle = 0
correctright = 0
incorrectleft = 0
incorrectmiddle = 0
incorrectright = 0
trialnum = 0
timeouts = 0
total_reward = 0
total_rewardtmp = 0
total_error = 0
total_errortmp = 0
totalresponse = 0
running_average = 0
targetindex = 0

# Set the lists
timelistleft = []
timelistmiddle = []
timelistright = []
summarysequence = []

# List of possible stimulus combinations  
stimlist =     [((1, 1, 1), (0, 2, 2), (2, 0, 0)), 
                ((1, 0, 0), (2, 1, 1), (0, 2, 2)), 
                ((1, 0, 1), (2, 2, 2), (0, 1, 0)), 
                ((2, 1, 2), (0, 2, 0), (1, 0, 1)), 
                ((2, 0, 2), (0, 1, 0), (1, 2, 1)), 
                ((1, 1, 0), (2, 2, 1), (0, 0, 2)), 
                ((0, 0, 1), (2, 2, 2), (1, 1, 0)), 
                ((0, 0, 0), (2, 1, 1), (1, 2, 2)), 
                ((0, 1, 1), (2, 2, 2), (1, 0, 0)), 
                ((2, 1, 0), (0, 2, 1), (1, 0, 2)), 
                ((2, 0, 0), (0, 1, 1), (1, 2, 2)), 
                ((2, 0, 1), (0, 2, 2), (1, 1, 0)), 
                ((1, 0, 0), (0, 1, 1), (2, 2, 2)), 
                ((1, 1, 0), (0, 2, 1), (2, 0, 2)), 
                ((0, 0, 2), (1, 1, 0), (2, 2, 1)), 
                ((2, 0, 2), (1, 1, 0), (0, 2, 1)), 
                ((2, 1, 2), (1, 2, 0), (0, 0, 1)), 
                ((1, 1, 2), (2, 2, 0), (0, 0, 1)), 
                ((2, 0, 0), (1, 1, 1), (0, 2, 2)), 
                ((2, 1, 1), (0, 2, 2), (1, 0, 0)), 
                ((0, 0, 1), (1, 2, 2), (2, 1, 0)), 
                ((0, 1, 0), (2, 2, 1), (1, 0, 2)), 
                ((1, 0, 2), (2, 1, 0), (0, 2, 1)), 
                ((0, 1, 0), (1, 2, 1), (2, 0, 2)), 
                ((2, 0, 1), (1, 2, 2), (0, 1, 0)), 
                ((1, 0, 2), (0, 1, 0), (2, 2, 1)), 
                ((1, 1, 2), (0, 2, 0), (2, 0, 1)), 
                ((0, 1, 2), (2, 2, 0), (1, 0, 1)), 
                ((1, 0, 1), (0, 2, 2), (2, 1, 0)), 
                ((0, 1, 1), (1, 2, 2), (2, 0, 0)), 
                ((2, 1, 0), (1, 2, 1), (0, 0, 2)), 
                ((2, 1, 1), (1, 2, 2), (0, 0, 0)), 
                ((0, 0, 2), (2, 1, 0), (1, 2, 1)), 
                ((0, 0, 0), (1, 1, 1), (2, 2, 2)), 
                ((0, 1, 2), (1, 2, 0), (2, 0, 1)), 
                ((1, 1, 1), (2, 2, 2), (0, 0, 0))]

datad = open("WCST_Step7_EDS&IDS_Stimuli.csv", 'w')
writer = csv.writer(datad)
writer.writerow(["Shape1", "Color1", "Shape2", "Color2", "Shape3", "Color3"])
for i in stimlist:
    writer.writerow([i[0][0], i[0][1], i[1][0], i[1][1], i[2][0], i[2][1]])
datad.close()

# Sequence of psuedorandom from 0 to 35
sequence = [20, 14, 29, 9, 23, 31, 11, 1, 28, 33, 
            3, 6, 0, 17, 35, 5, 26, 24, 22, 15, 
            2, 10, 34, 30, 8, 4, 12, 16, 7, 27, 
            25, 19, 13, 32, 21, 20, 14, 29, 9, 23, 
            31, 11, 1, 28, 33, 3, 6, 0, 17, 35, 
            5, 26, 24, 22, 15, 2, 10, 34, 30, 8, 
            4, 12, 16, 7, 27, 25, 19, 13, 32, 21]

sequence = sequence * 10

sequenceSaved = sequence

# Truncating the sequence for trial number
n = len(sequence)
for i in range(0, n - trials):
    sequence.pop()

# Binary history 0/1 for record keeping
historylist = []

# Setting up CSV title
thedatetime = datetime.now()
thetime = thedatetime.strftime("%H:%M:%S")
title = f"{AnimalName}_WCST_Step7_EDS&IDS_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"

# Write headers to csv file
data = open(title, 'w')
writer = csv.writer(data)
writer.writerow(["Trial#", "Event Code", "Time"])

#Prep time
time.sleep(prep_time)

time_start = time.time()

# For loop parsing through sequence 
for i in sequence:

    trialnum += 1
    summarysequence.append(i)

    # Writing summary csv 
    if trialnum%10 == 0:
        if trialnum == 10:
            title2 = f"{AnimalName}_WCST_Step7_EDS&IDS_{datetime.now().strftime('%Y%m%d_%H%M%S')}_Summary.txt"
            summary = open(title2, "a+")
            summary.write(f"Trial Duration: {Trial_Duration}\n")
            summary.write(f"ITI: {ITI}\n")
        if len(timelistleft) == 0:
            meanleft = 0
        else:
            meanleft = sum(timelistleft) / len(timelistleft)
        if len(timelistmiddle) == 0:
            meanmiddle = 0
        else:
            meanmiddle = sum(timelistmiddle)  / len(timelistmiddle)
        if len(timelistright) == 0:
            meanright = 0
        else:
            meanright = sum(timelistright) / len(timelistright)
        summary.write(f"Completed Trials (saved every 10th): {trialnum}\n")
        summary.write("Sequence: " + str(summarysequence) + "\n")
        summary.write(f"Correct: {correctleft},{correctmiddle},{correctright}\n")
        summary.write(f"Incorrect: {incorrectleft},{incorrectmiddle},{incorrectright}\n")
        summary.write(f"Total Reward: {correctleft+correctmiddle+correctright}\n")
        summary.write(f"Total No Reponses: {timeouts}\n")
        summary.write(f"Mean Reaction Times: {meanleft}, {meanmiddle}, {meanright}\n")
        summary.write("------------------------------------------------------------\n")
    
    if (trialnum - timeouts) >= 11 and trialnum != 1:
        if (len(historylist) > 0):
            running_average = len([num for num in historylist[-10:] if num == 1])/len(historylist[-10:])
        if running_average >= 0.8:
            if targetindex < 4:
                targetindex += 1
            else:
                targetindex = 4
            target = targets[targetindex]
            if target == 4 or target == 5 or target == 6:
                color = True
            else:
                color = False
            if target == 1:
                target_points  = button_star_points
                foil1_points  = button_square_points
                foil2_points  = button_heart_points
            elif target == 2:
                target_points  = button_square_points
                foil1_points  = button_star_points
                foil2_points  = button_heart_points
            elif target == 3:
                target_points  = button_heart_points
                foil1_points  = button_star_points
                foil2_points  = button_square_points
            if target == 4:
                target_colour  = (255, 255, 000)
                foil1_colour = (255, 000, 000)
                foil2_colour = (000, 000, 204)
                foil = "red/green and blue"
            elif target == 5:
                target_colour = (255, 000, 000)
                foil1_colour  = (255, 255, 000)
                foil2_colour = (000, 000, 204)
                foil = "yellow and blue"
            elif target == 6:
                target_colour = (000, 000, 204)
                foil1_colour  = (255, 255, 000)
                foil2_colour = (255, 000, 000)
                foil = "yellow and red/green"
        
    # Delay between buttons
    screen.fill(screenfill)
    pygame.display.update()

    # ITI
    time_before = time.time()
    writer.writerow([trialnum, i, time_before - time_start]) #trial type and ITI onset
    ITInew = ITI
    while time.time() - time_before < ITInew:
        pygame.event.pump()
        if pygame.mouse.get_pressed()[0]:
            distance_button_0 = pygame.math.Vector2(button_x_spacing, button_positionsy[0]) - pygame.math.Vector2(pygame.mouse.get_pos())
            distance_button_1 = pygame.math.Vector2(button_x_spacing, button_positionsy[1]) - pygame.math.Vector2(pygame.mouse.get_pos())
            distance_button_2 = pygame.math.Vector2(button_x_spacing, button_positionsy[2]) - pygame.math.Vector2(pygame.mouse.get_pos())
            if distance_button_0.length() < button_radius:
                writer.writerow([trialnum, 210, time.time() - time_start])
            elif distance_button_1.length() < button_radius:
                writer.writerow([trialnum, 211, time.time() - time_start])
            elif distance_button_2.length() < button_radius:
                writer.writerow([trialnum, 212, time.time() - time_start])
            else:
                writer.writerow([trialnum, 216, time.time() - time_start])


    # Baseline with plus sign
    time_base = time.time()
    writer.writerow([trialnum, 100, time_base - time_start]) #plus onset
    while time.time() - time_base < plus:
        pygame.draw.rect(screen, black, pygame.Rect(button_x_spacing - 10, button_y_spacing + 200 - button_radius + 10, 20, button_radius*2 - 20))
        pygame.draw.rect(screen, black, pygame.Rect(button_x_spacing - button_radius + 10, button_y_spacing + 200 - 10, button_radius*2 - 20, 20))
        pygame.display.update()
        pygame.time.delay(100)
        pygame.event.pump()
        if pygame.mouse.get_pressed()[0]:
            distance_button_0 = pygame.math.Vector2(button_x_spacing,button_positionsy[0]) - pygame.math.Vector2(pygame.mouse.get_pos())
            distance_button_1 = pygame.math.Vector2(button_x_spacing,button_positionsy[1]) - pygame.math.Vector2(pygame.mouse.get_pos())
            distance_button_2 = pygame.math.Vector2(button_x_spacing,button_positionsy[2]) - pygame.math.Vector2(pygame.mouse.get_pos())
            if distance_button_0.length() < button_radius:
                writer.writerow([trialnum, 210, time.time() - time_start])
            elif distance_button_1.length() < button_radius:
                writer.writerow([trialnum, 211, time.time() - time_start])
            elif distance_button_2.length() < button_radius:
                writer.writerow([trialnum, 212, time.time() - time_start])
            else:
                writer.writerow([trialnum, 216, time.time() - time_start])

    screen.fill(screenfill)
    pygame.display.update()

    # Starts Timer 
    start_time = time.time()
    reward = 0
    
    # Writing the button in csv file
    timedisplay = time.time()
    writer.writerow([trialnum, 110, timedisplay - time_start])

    # Loops while button isn't correct 
    while time.time() < start_time + Trial_Duration:
        if reward == 1:
            break
        
        # Draws the button
        if color:
            if stimlist[i][0][1] + 1 == target - 3:
                pygame.draw.polygon(screen, target_colour, shapelist[stimlist[i][0][0]][stimlist[i][0][2]])
                pygame.draw.polygon(screen, colourlist[stimlist[i][1][1]], shapelist[stimlist[i][1][0]][stimlist[i][1][2]])
                pygame.draw.polygon(screen, colourlist[stimlist[i][2][1]], shapelist[stimlist[i][2][0]][stimlist[i][2][2]])
                targetlocation = stimlist[i][0][2]
            elif stimlist[i][1][1] + 1 == target - 3:
                pygame.draw.polygon(screen, target_colour, shapelist[stimlist[i][1][0]][stimlist[i][1][2]])
                pygame.draw.polygon(screen, colourlist[stimlist[i][0][1]], shapelist[stimlist[i][0][0]][stimlist[i][0][2]])
                pygame.draw.polygon(screen, colourlist[stimlist[i][2][1]], shapelist[stimlist[i][2][0]][stimlist[i][2][2]])
                targetlocation = stimlist[i][1][2]
            elif stimlist[i][2][1] + 1 == target - 3:
                pygame.draw.polygon(screen, target_colour, shapelist[stimlist[i][2][0]][stimlist[i][2][2]])
                pygame.draw.polygon(screen, colourlist[stimlist[i][1][1]], shapelist[stimlist[i][1][0]][stimlist[i][1][2]])
                pygame.draw.polygon(screen, colourlist[stimlist[i][0][1]], shapelist[stimlist[i][0][0]][stimlist[i][0][2]])
                targetlocation = stimlist[i][2][2]
            pygame.display.update()
        else:
            if stimlist[i][0][0] + 1 == target:
                pygame.draw.polygon(screen, colourlist[stimlist[i][0][1]], target_points[stimlist[i][0][2]])
                pygame.draw.polygon(screen, colourlist[stimlist[i][1][1]], shapelist[stimlist[i][1][0]][stimlist[i][1][2]])
                pygame.draw.polygon(screen, colourlist[stimlist[i][2][1]], shapelist[stimlist[i][2][0]][stimlist[i][2][2]])
                targetlocation = stimlist[i][0][2]
            elif stimlist[i][1][0] + 1 == target:
                pygame.draw.polygon(screen, colourlist[stimlist[i][1][1]], target_points[stimlist[i][1][2]])
                pygame.draw.polygon(screen, colourlist[stimlist[i][0][1]], shapelist[stimlist[i][0][0]][stimlist[i][0][2]])
                pygame.draw.polygon(screen, colourlist[stimlist[i][2][1]], shapelist[stimlist[i][2][0]][stimlist[i][2][2]])
                targetlocation = stimlist[i][1][2]
            elif stimlist[i][2][0] + 1 == target:
                pygame.draw.polygon(screen, colourlist[stimlist[i][2][1]], target_points[stimlist[i][2][2]])
                pygame.draw.polygon(screen, colourlist[stimlist[i][1][1]], shapelist[stimlist[i][1][0]][stimlist[i][1][2]])
                pygame.draw.polygon(screen, colourlist[stimlist[i][0][1]], shapelist[stimlist[i][0][0]][stimlist[i][0][2]])
                targetlocation = stimlist[i][2][2]
            pygame.display.update()
       
        # Checks when screen is touched 
        for event in pygame.event.get():
            click = pygame.mouse.get_pressed()[0]
            if click == 1:
                click = 0

                # Distance between point touched and button 
                distance_button = pygame.math.Vector2(button_x_spacing, button_positionsy[targetlocation]) - pygame.math.Vector2(pygame.mouse.get_pos())

                # Checks if distance is within button 
                if distance_button.length() < button_radius:
                    
                    timecorrect = time.time()
                    timedifference = timecorrect - timedisplay

                    # Counts which buttons were pressed 
                    if targetlocation == 0:
                        timecorrect = time.time()
                        timedifference = timecorrect - timedisplay
                        timelistleft.append(timedifference)
                        correctleft += 1
                    elif targetlocation == 1:
                        timecorrect = time.time()
                        timedifference = timecorrect - timedisplay
                        timelistmiddle.append(timedifference)
                        correctmiddle += 1
                    elif targetlocation == 2:
                        timecorrect = time.time()
                        timedifference = timecorrect - timedisplay
                        timelistright.append(timedifference)
                        correctright += 1
                    
                    historylist.append(1)
                    timecorrect = time.time()
                    writer.writerow([trialnum, 150, timecorrect - time_start])

                    # Reward
                    #time.sleep(rewardDelay) #to give time to motor 'oops' signal
                    #timereward = time.time()
                    #writer.writerow([trialnum, 200, timereward - time_start])
                    #GPIO.output(rewardpin,GPIO.HIGH)
                    #time.sleep(rewards_size)
                    #GPIO.output(rewardpin,GPIO.LOW)
                    reward = 1
                    break 

                # Counts when touch was outside of button 
                elif distance_button.length() > button_radius:
                    historylist.append(0) 
                    distance_button_0 = pygame.math.Vector2(button_x_spacing,button_positionsy[0]) - pygame.math.Vector2(pygame.mouse.get_pos())
                    distance_button_1 = pygame.math.Vector2(button_x_spacing,button_positionsy[1]) - pygame.math.Vector2(pygame.mouse.get_pos())
                    distance_button_2 = pygame.math.Vector2(button_x_spacing,button_positionsy[2]) - pygame.math.Vector2(pygame.mouse.get_pos())
                    if distance_button_0.length() < button_radius:
                        incorrectleft += 1
                        timenow = time.time()
                        writer.writerow([trialnum, 210, timenow - time_start])
                    elif distance_button_1.length() < button_radius:
                        incorrectmiddle += 1
                        timenow = time.time()
                        writer.writerow([trialnum, 211, timenow - time_start])
                    elif distance_button_2.length() < button_radius:
                        incorrectright += 1
                        timenow = time.time()
                        writer.writerow([trialnum, 212, timenow - time_start])       
                    break

        # Time out for 15 seconds 
        seconds = (time.time() - start_time)
        if seconds >= Trial_Duration:
            timeouts +=1
            timenow = time.time()
            writer.writerow([trialnum, 250, timenow - time_start])
            break

# Closing objects 
data.close()
summary.close()
print(sequenceSaved)
#GPIO.cleanup()

It is meant to break when there is a mouse click detected at any other spot not within the button. The code however is not breaking. It does break when it hits the correct spot but I can't seem to figure out why it's not breaking in this case. My other codes work fine and use the same logic.

1

There are 1 best solutions below

0
Argetlam On

From my understanding, it appears as if you are breaking out of the event checker loop in pygame, which does not break out of the entire game loop and gets re-executed on the next iteration of the game loop. @yak explains on another stack overflow page about how to break out of entire loops:

for a in xrange(10):
  for b in xrange(20):
    if something(a, b):
        # Break the inner loop...
        break
else:
    # Continue if the inner loop wasn't broken.
    continue
# Inner loop was broken, break the outer.
break