File size: 30,117 Bytes
99a62a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0601423
99a62a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
092c1f0
99a62a6
 
 
 
 
 
 
 
 
 
 
 
2710b11
 
4d41dfd
99a62a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
import streamlit as st
import random
import time

st.title('Brain Training Exercises')

st.write('This app provides a comprehensive survey of brain-training exercises designed to enhance various cognitive skills. Select a category below to view the exercises and try them out!')

categories = ['Attention', 'Brain Speed', 'Memory', 'People Skills', 'Intelligence', 'Navigation']
choice = st.sidebar.selectbox('Select a category', categories)

if choice == 'Attention':
    st.header('Attention Exercises')
    
    st.subheader('Focus Flexibility Drill')
    st.write('Scientific Principles: Based on the ability of the brain to switch focus from one task to another, enhancing cognitive flexibility.')
    st.write('Cognitive Skills: Focus shifting, sustained attention, and task switching.')
    st.write('Exercise Task: Switch between reading a book and solving a puzzle every 3 minutes for 30 minutes daily.')
    
    if st.button('Start Focus Drill'):
        st.write('Read a page from a book for 3 minutes')
        time.sleep(180)
        st.write('Now solve a puzzle for 3 minutes')
        time.sleep(180)
        st.write('Drill complete! Practice this daily to improve your focus flexibility.')
        
    st.subheader('Dual N-Back')
    st.write('Scientific Principles: Improves working memory and fluid intelligence by requiring the user to remember two separate sequences of stimuli.')
    st.write('Cognitive Skills: Working memory, attention span, and concentration.')
    st.write('Exercise Task: On a computer program, respond whenever the current visual and auditory stimuli match the one from N steps earlier.')
    
    if st.button('Play Dual 2-Back'):
        positions = ['left', 'right']
        sounds = ['high', 'low']
        
        if 'score' not in st.session_state:
            st.session_state.score = 0
        
        prev_position = ''
        prev_sound = ''
        
        for i in range(10):
            position = random.choice(positions)
            sound = random.choice(sounds)
            
            st.write(f'Round {i+1}')
            if position == 'left':
                st.write('◀️')
            else:
                st.write('▢️')
                
            if sound == 'high':  
                st.write('High tone')
            else:
                st.write('Low tone')
            
            if i >= 2:
                if st.button('Match', key=f'{i}a'):
                    if position == prev_position and sound == prev_sound:
                        st.session_state.score += 1
                        st.write('Correct! 1 Point')
                    else:
                        st.write('Incorrect, no points')
                if st.button('No Match', key=f'{i}b'):
                    if position != prev_position or sound != prev_sound:
                        st.session_state.score += 1
                        st.write('Correct! 1 Point')  
                    else:
                        st.write('Incorrect, no points')
            else:
                time.sleep(1)
                        
            prev_position = position      
            prev_sound = sound
        
        st.write(f'Game Over. Final Score: {st.session_state.score}/8')
    
    st.subheader('Selective Attention Field')
    st.write('Scientific Principles: Enhances the ability to focus on relevant stimuli while ignoring distractions.')
    st.write('Cognitive Skills: Selective attention, focus, and concentration.')  
    st.write('Exercise Task: Identify specific letters or numbers within a field of various characters for a set duration daily.')

    if st.button('Start Attention Field'):
        chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
        target = random.choice(chars)
        st.write(f'Your target is: {target}')
        
        field = ''
        for i in range(500):
            field += random.choice(chars)
        st.write(field)
        
        count = st.number_input('How many times did the target appear?')
        if count == field.count(target):
            st.write('Correct!')
        else:
            st.write(f'Incorrect. The target appeared {field.count(target)} times.')

elif choice == 'Brain Speed':
    st.header('Brain Speed Exercises')

    st.subheader('Rapid Visual Processing')
    st.write('Scientific Principles: Based on the temporal dynamics of visual perception and decision-making.')
    st.write('Cognitive Skills: Processing speed, visual scanning, and quick decision-making.')
    st.write('Exercise Task: Identify and click on sequences of numbers as fast as possible from a larger group.')
    
    if st.button('Start RVP Test'):
        numbers = '0123456789'
        sequence = ''
        for i in range(3):
            sequence += random.choice(numbers)
        
        st.write('Click when you see this sequence:')
        st.write(sequence)
        time.sleep(2)

        if 'start_time' not in st.session_state:
            st.session_state.start_time = 0
        
        if 'end_time' not in st.session_state:  
            st.session_state.end_time = 0
        
        stream = ''
        for i in range(200):
            stream += random.choice(numbers) 
            
        start = stream.index(sequence)
        end = start + len(sequence)
        stream = stream[:start] + sequence + stream[end+1:]
        
        display = st.empty()
        
        for i in range(len(stream)):
            display.write(stream[i])
            if stream[i:i+len(sequence)] == sequence and st.session_state.start_time == 0:
                st.session_state.start_time = time.time()  
            
            time.sleep(0.1)
        
        st.session_state.end_time = time.time()
        
        if st.button('Click Here', key='s') and st.session_state.start_time != 0:
            reaction_time = round(st.session_state.end_time - st.session_state.start_time, 3)  
            st.write(f'Reaction Time: {reaction_time} seconds')
        
    st.subheader('Reaction Time Ruler Drop Test')
    st.write('Scientific Principles: Measures the speed of response to a visual stimulus.')
    st.write('Cognitive Skills: Reaction time, hand-eye coordination.')
    st.write('Exercise Task: Catch a falling ruler as quickly as possible after it is released without warning.')
    
    st.subheader('Speed Trivia')
    st.write('Scientific Principles: Encourages rapid information retrieval and processing.')
    st.write('Cognitive Skills: Processing speed, memory recall, and decision-making under pressure.')
    st.write('Exercise Task: Answer as many trivia questions as possible within a set time limit.')
    
    if st.button('Start Speed Trivia'):
        questions = [
            {'question': 'What is the capital of France?', 'answer': 'Paris'},
            {'question': 'What is the largest planet in our solar system?', 'answer': 'Jupiter'},
            {'question': 'What is the smallest country in the world?', 'answer': 'Vatican City'},
            {'question': 'What is the currency of Japan?', 'answer': 'Yen'},
            {'question': 'What is the largest desert in the world?', 'answer': 'Antarctica'},
            {'question': 'What is the tallest mammal?', 'answer': 'Giraffe'},
            {'question': 'What is the most populated country in the world?', 'answer': 'China'},
            {'question': 'What is the chemical symbol for gold?', 'answer': 'Au'},
            {'question': 'What is the largest ocean in the world?', 'answer': 'Pacific'},
            {'question': 'What is the capital of Australia?', 'answer': 'Canberra'}
        ]
        
        score = 0
        start_time = time.time()
        
        while time.time() - start_time < 60:
            question = random.choice(questions)
            user_answer = st.text_input(question['question'])
            
            if user_answer.lower() == question['answer'].lower():
                score += 1
                st.write('Correct!')
            else:
                st.write(f"Incorrect. The answer was {question['answer']}")
                
        st.write(f'Time is up! You answered {score} questions correctly.')

elif choice == 'Memory':
    st.header('Memory Exercises')
    
    st.subheader('Mnemonic Visualization')
    st.write('Scientific Principles: Utilizes vivid imagery and association to enhance recall.')
    st.write('Cognitive Skills: Long-term memory, associative learning, and visualization.')
    st.write('Exercise Task: Create vivid images or stories linking unrelated items in a list to remember them.')
    
    if st.button('Try Mnemonic Visualization'):
        items = ['apple', 'bicycle', 'cat', 'dragon', 'elephant']
        st.write(f'Memorize this list of items: {", ".join(items)}')
        
        time.sleep(10)
        
        st.write('Now visualize a story connecting the items, like:')
        st.write('An APPLE riding a BICYCLE chasing a CAT who is flying on a DRAGON that is stepping on an ELEPHANT.')
        
        time.sleep(10)
        
        recalled = st.text_input('Type out the original list of items')
        recalled_list = [item.strip() for item in recalled.split(',')]
        
        correct = 0
        for item in recalled_list:
            if item in items:
                correct += 1
                
        st.write(f'You recalled {correct} out of {len(items)} items correctly!')
        
    st.subheader('Chunking Practice')  
    st.write('Scientific Principles: Based on the concept of working memorys limited capacity and enhancing it by grouping information.')
    st.write('Cognitive Skills: Short-term memory, organization, and recall efficiency.')
    st.write('Exercise Task: Break down complex information into smaller, manageable chunks for study or memorization.')
    
    if st.button('Start Chunking'): 
        number = ''
        for i in range(12):
            number += str(random.randint(0,9))
            
        st.write(f'Memorize this number: {number}')
        time.sleep(10)
        
        chunked = ''
        for i in range(0, len(number), 3):
            chunked += number[i:i+3] + ' '
        
        st.write('Now think of it as chunked into groups of 3:')    
        st.write(chunked)
        
        time.sleep(10)
        
        recalled = st.text_input('Enter the original 12-digit number')
        
        if recalled == number:
            st.write('Perfect recall! Chunking makes memorization easier.')
        else:
            st.write(f'Not quite, the original number was {number}. Keep practicing chunking!')
            
    st.subheader('Spatial Recall')
    st.write('Scientific Principles: Engages and improves spatial memory and visual-spatial reasoning.')
    st.write('Cognitive Skills: Spatial memory, spatial reasoning, and visualization.')
    st.write('Exercise Task: Memorize and recall the location of objects in a space after brief exposure.')
    
    if st.button('Test Spatial Recall'):
        grid = [
            ['🍎','','','🍌'],
            ['','πŸ‡','🍊',''], 
            ['','','','πŸ“'],
            ['','πŸ‰','','']
        ]
        
        for row in grid:  
            st.write('|'.join(cell if cell else '   ' for cell in row))
        
        time.sleep(10)
        
        for row in grid:
            st.write('|'.join('   ' for cell in row))
            
        st.write('Enter the coordinates of each fruit, like A1 for top-left')
        
        answers = {
            'apple': 'A1',
            'banana': 'A4', 
            'grapes': 'B2',
            'orange': 'B3',
            'strawberry': 'C4',
            'watermelon': 'D2'
        }
        
        score = 0
        for fruit, location in answers.items():
            answer = st.text_input(f'Where was the {fruit}?')
            if answer.upper() == location:
                score += 1
                
        st.write(f'You got {score} out of {len(answers)} correct!')
        
        
elif choice == 'People Skills':
    st.header('People Skills Exercises')
    
    st.subheader('Emotion Recognition Training')
    st.write('Scientific Principles: Enhances emotional intelligence and empathy by recognizing and interpreting emotions in others.')
    st.write('Cognitive Skills: Emotional intelligence, empathy, and social cues interpretation.')
    st.write('Exercise Task: Identify emotions from facial expressions, tone of voice, or body language in photos, videos, or in-person interactions.')
    
    # Coding implementation for emotion recognition omitted here as it would require an image dataset and ML model
    
    st.subheader('Perspective-Taking Scenarios')
    st.write('Scientific Principles: Develops empathy and understanding by considering different viewpoints.')
    st.write('Cognitive Skills: Empathy, perspective-taking, and critical thinking.')  
    st.write('Exercise Task: Analyze written scenarios from multiple characters viewpoints to understand their perspectives and motivations.')
    
    if st.button('Try Perspective-Taking'):
        scenario = '''
        John and Mary are colleagues at work. John has been working on a major project for months, staying late and coming in on weekends. The day before the project is due, Mary points out a significant flaw in John's work that requires him to make major revisions. John gets upset with Mary, accusing her of sabotaging his work at the last minute. Mary is surprised by John's reaction and feels her feedback was necessary for the success of the project.
        '''
        
        st.write(scenario)
        
        perspective1 = st.text_area("Describe John's perspective")
        perspective2 = st.text_area("Describe Mary's perspective")
        
        if perspective1 and perspective2:
            st.write("Johns perspective likely centers around feeling overwhelmed, frustrated that a flaw was found last-minute after so much hard work, and possibly betrayed or attacked by Mary's feedback. He may feel Mary was being overly critical or should have brought this up sooner.")
            st.write("Marys perspective is likely that she was just trying to help ensure the projects success, not attack John. She was doing her job by providing feedback, and didn't intend for it to be last-minute - she may have only just noticed the issue. She seems surprised John took it so personally.")
            st.write("Considering both sides, the conflict likely stems from John perceiving Marys feedback as a personal slight due to the stress and personal investment he had in the project. Mary didnt intend it that way, but could perhaps work on delivering constructive criticism.")



def stroop_test():
    colors = ["RED", "BLUE", "GREEN", "YELLOW"] 
    color_text = ["blue", "green", "yellow", "red"]
    score = 0
    for word, color in zip(colors, color_text):
        response = st.text_input(f"Enter the color of the text '{word}': ")
        if response.lower() == color:
            score += 1
    st.write(f"Score: {score} out of {len(colors)}")

def flanker_task():
    targets = ["<", ">"]
    conditions = ["congruent", "incongruent"] 
    score = 0
    for _ in range(10):
        target = random.choice(targets)
        condition = random.choice(conditions)
        stim = target*5 if condition == "congruent" else target.replace(">","<") + target + target.replace(">","<")*3
        response = st.text_input(f"Enter the central arrow direction in '{stim}': ")
        if response == target:
            score += 1
    st.write(f"Score: {score} out of 10")

def attentional_blink():
    letters = "ABCDEFGHJKLMNOPQRSTUVWXYZ"
    target1, target2 = random.sample(letters,2)
    stimuli = random.choices(letters, k=18) 
    stimuli.insert(random.randint(3,7), target1)
    stimuli.insert(random.randint(8,15), target2)
    st.write(f"Your targets are: {target1} and {target2}. Press Enter to start...")
    for letter in stimuli:
        st.write(letter)
        time.sleep(0.1)
    response1 = st.text_input("What was the first target letter? ")
    response2 = st.text_input("What was the second target letter? ")
    score = int(response1==target1) + int(response2==target2)
    st.write(f"Score: {score} out of 2")

def simple_reaction_time():
    st.write("Press Enter to begin when you see the prompt. Your reaction time will be measured.")
    time.sleep(random.randint(2,5))
    start = time.time()
    st.text_input("Press Enter now!")
    end = time.time()
    rt = round((end - start)*1000)
    st.write(f"Your reaction time: {rt} milliseconds")

def go_nogo_task():
    stim = ["Go", "No-Go"]
    score = 0
    st.write("Press Enter for 'Go' stimuli. Do not press for 'No-Go'! You have 0.5s to respond.")
    for _ in range(10):
        stimulus = random.choice(stim)
        st.write(stimulus)
        start = time.time()
        response = st.text_input("")
        end = time.time()
        rt = end - start
        if stimulus == "Go" and rt < 0.5:
            score += 1
        elif stimulus == "No-Go" and response == "":
            score += 1
    st.write(f"Score: {score} out of 10")

def choice_reaction_time():
    stim = ["Left", "Right", "Up", "Down"]
    keys = ["a", "d", "w", "s"]
    score = 0
    st.write("Press the correct key (a/d/w/s) depending on the word shown. You have 0.8s to respond.")
    for _ in range(10):
        stimulus = random.choice(stim)
        st.write(stimulus)
        start = time.time()
        response = st.text_input("")
        end = time.time()
        rt = end - start
        if response == keys[stim.index(stimulus)] and rt < 0.8:
            score += 1
    st.write(f"Score: {score} out of 10")

def n_back():
    digits = list(range(10))
    n = 2
    sequence = random.choices(digits, k=15)
    st.write(f"Enter 'yes' if the current number is the same as the number {n} steps back in the sequence.")
    score = 0
    for i in range(n,len(sequence)):
        st.write(sequence[i])
        response = st.text_input("")
        if response == "yes" and sequence[i] == sequence[i-n]:
            score += 1
        elif response == "" and sequence[i] != sequence[i-n]:
            score += 1
    st.write(f"Score: {score} out of {len(sequence)-n}")

def corsi_block_tapping():
    blocks = list(range(9))
    sequence = []
    for span in range(2,10):
        st.write(f"\nSpan length: {span}. Watch the block sequence...")
        sequence = random.sample(blocks, span)
        st.write(sequence)
        response = st.text_input("Reproduce the sequence (enter digits with spaces): ")
        if response == ' '.join(map(str,sequence)):
            st.write("Correct!")
        else:
            st.write(f"Incorrect. The sequence was {sequence}")
            break
    st.write(f"Your maximum span: {len(sequence)-1}")

def paired_associates():
    pairs = [("cat", "meow"), ("dog", "bark"), ("bird", "chirp"), ("pig", "oink"), ("cow", "moo")]
    st.write("Study the word pairs:")
    st.write(*[f"{pair[0]} - {pair[1]}" for pair in pairs], sep='\n')
    st.text_input("\nPress Enter to start the recall test...")
    score = 0
    for i in range(5):
        cue, target = random.choice(pairs)
        pairs.remove((cue, target))
        response = st.text_input(f"\nWhat word was paired with '{cue}'? ")
        if response == target:
            st.write("Correct!")
            score += 1
        else:
            st.write(f"Incorrect. The pair was: {cue} - {target}")
    st.write(f"\nScore: {score} out of 5")

def reading_the_mind_in_the_eyes():
    eyes = {
        "Image1": ["playful", "comforting", "irritated", "bored"],
        "Image2": ["terrified", "upset", "arrogant", "annoyed"],
        "Image3": ["joking", "flustered", "desire", "convinced"],
        "Image4": ["joking", "insisting", "amused", "relaxed"],
        "Image5": ["irritated", "sarcastic", "worried", "friendly"]
    }
    score = 0
    for image, words in eyes.items():
        target = words[0]
        random.shuffle(words)
        st.write(f"\n{image}:")
        st.write(*[f"{i+1}. {word}" for i,word in enumerate(words)], sep='\n')
        response = int(st.text_input("Which word best describes the person's mental state? ")) - 1
        if words[response] == target:
            st.write("Correct!")
            score += 1
        else:
            st.write(f"Incorrect. The best answer is: {target}")
    st.write(f"\nScore: {score} out of {len(eyes)}")

def faux_pas_recognition():
    stories = [
        ("Alice was at a party when she saw an old friend, Bob. 'Hi, nice to see you!' Alice said. 'You look great! How's the new job going?' Bob looked confused and said, 'I don't have a new job. I've been unemployed for months.'", True),
        ("John was at the grocery store when he ran into his neighbor, Sarah. They chatted for a few minutes about their weekend plans and the nice weather. Then they said goodbye and continued their shopping.", False),
        ("Mary was having lunch with her coworkers. 'I love your new haircut,' she said to Emily. 'It really suits you!' Emily smiled and said, 'Thanks, I got it cut last week.' Then Emily turned to Jane and said, 'I wish I could say the same for you, Jane. Your hair looks like a mess!'", True)
    ]
    score = 0
    for story, faux_pas in stories:
        st.write(f"\n{story}")
        response = st.text_input("\nDid someone say something they shouldn't have? (yes/no): ")
        if response == "yes" and faux_pas == True:
            explanation = st.text_input("Explain what was said that was socially incorrect: ")
            st.write(f"Correct! {explanation}")
            score += 1
        elif response == "no" and faux_pas == False:
            st.write("Correct, there was no faux pas in this story.")
            score += 1
        else:
            st.write("Incorrect. Let's move on to the next story.")
    st.write(f"\nScore: {score} out of {len(stories)}")

def interpersonal_perception_task():
    videos = {
        "Video1": (
            "Emma and Liam are sitting at a cafe, drinking coffee and chatting. Emma is smiling and leaning forward while telling a story. Liam has his arms crossed and is frowning slightly as he listens.",
            {
                "How engaged does Emma seem in the conversation?": ["Very engaged", "Somewhat engaged", "Not very engaged", "Not at all engaged"],
                "How interested does Liam seem in what Emma is saying?": ["Very interested", "Somewhat interested", "Not very interested", "Not at all interested"]
            },
            ["Very engaged", "Not very interested"]
        ),
        "Video2": (
            "Olivia and Ethan are in a heated discussion. Olivia is gesturing with her hands and looks frustrated. Ethan has his hands on his hips and is shaking his head.",
            {
                "What emotion is Olivia most likely expressing?": ["Anger", "Sadness", "Fear", "Joy"],
                "Does Ethan seem to agree with what Olivia is saying?": ["Definitely agrees", "Probably agrees", "Probably disagrees", "Definitely disagrees"]
            },
            ["Anger", "Definitely disagrees"]
        )
    }

    score = 0
    for video, (description, questions, answers) in videos.items():
        st.write(f"\n{video}: {description}")
        for question, choices in questions.items():
            st.write(f"\n{question}")
            st.write(*[f"{i+1}. {choice}" for i,choice in enumerate(choices)], sep='\n')
            response = int(st.text_input("Enter the number of your answer: ")) - 1
            if choices[response] == answers[list(questions.keys()).index(question)]:
                st.write("Correct!")
                score += 1
            else:
                st.write(f"Incorrect. The best answer is: {answers[list(questions.keys()).index(question)]}")
    st.write(f"\nScore: {score} out of {sum([len(q) for _,q,_ in videos.values()])}")

def ravens_progressive_matrices():
    matrices = [
        (
            ["πŸ”΄πŸ”΄πŸ”΄","🟒🟒🟒","πŸ”΅πŸ”΅πŸ”΅"],
            ["🟒🟒🟒","πŸ”΅πŸ”΅πŸ”΅",""],
            ["πŸ”΄πŸ”΄πŸ”΄","🟠🟠🟠","🟑🟑🟑","βšͺβšͺβšͺ"]
        ),
        (
            ["πŸ”Ί","πŸ”ΊπŸ”Ί","πŸ”ΊπŸ”ΊπŸ”Ί"],
            ["πŸŸ₯","πŸŸ₯πŸŸ₯",""],
            ["πŸ”»","πŸ”»πŸ”»","πŸ”»πŸ”»πŸ”»","⬜"]
        )
    ]
    score = 0
    for matrix, problem, choices in matrices:
        st.write("\nComplete the matrix:")
        for row in matrix:
            st.write("".join(row))
        for row in problem:
            st.write("".join(row))
        st.write("\nChoices:")
        for i, choice in enumerate(choices):
            st.write(f"{i+1}. {choice}")
        response = int(st.text_input("Enter the number of your answer: ")) - 1
        if choices[response] == choices[-1]:
            st.write("Correct!")
            score += 1
        else:
            st.write(f"Incorrect. The correct answer is: {choices[-1]}")
    st.write(f"\nScore: {score} out of {len(matrices)}")

def main():
    st.title("Brain Training Exercises")
    st.sidebar.title("Select an Exercise")

    exercise = st.sidebar.selectbox("", [
        "Stroop Test",
        "Flanker Task",
        "Attentional Blink",
        "Simple Reaction Time",
        "Go/No-Go Task",
        "Choice Reaction Time",
        "N-Back",
        "Corsi Block Tapping",
        "Paired Associates",
        "Reading the Mind in the Eyes",
        "Faux Pas Recognition",
        "Interpersonal Perception Task",
        "Raven's Progressive Matrices"
    ])

    st.header(exercise)

    if exercise == "Stroop Test":
        st.markdown("""
        ## 🎨 Stroop Test
        - πŸ“ Words for colors are shown in different colored text
        - πŸ–±οΈ Select the color of the text, not the word itself
        - 🧠 Tests selective attention and inhibitory control
        """)
        stroop_test()
    elif exercise == "Flanker Task":
        st.markdown("""
        ## 🎯 Flanker Task
        - β¬…οΈβž‘οΈ Targets (arrows) are flanked by distractors facing the same or opposite direction
        - πŸ–±οΈ Select the central target quickly while ignoring the flankers
        - 🧠 Tests focused attention and filtering out irrelevant stimuli
        """)
        flanker_task()
    elif exercise == "Attentional Blink":
        st.markdown("""
        ## 😡 Attentional Blink
        - πŸ”  Detect two targets in a rapid stream of letters
        - ⏱️ The second target follows shortly after the first
        - 🧠 Tests temporal limitations of attention in processing successive targets
        """)
        attentional_blink()
    elif exercise == "Simple Reaction Time":
        st.markdown("""
        ## ⏰ Simple Reaction Time
        - ▢️ Respond as quickly as possible to a stimulus
        - πŸ–±οΈ Press Enter when you see the prompt
        - 🧠 Measures basic psychomotor speed
        """)
        simple_reaction_time()
    elif exercise == "Go/No-Go Task":
        st.markdown("""
        ## 🚦 Go/No-Go Task
        - βœ… Respond quickly to 'Go' stimuli
        - ❌ Withhold response to 'No-Go' stimuli
        - 🧠 Measures action restraint and response inhibition
        """)
        go_nogo_task()
    elif exercise == "Choice Reaction Time":
        st.markdown("""
        ## πŸŽ›οΈ Choice Reaction Time
        - πŸ”  Make the appropriate response depending on the stimulus shown
        - ⌨️ Press the correct key (a/d/w/s) for each word
        - 🧠 Measures decision speed and response selection
        """)
        choice_reaction_time()
    elif exercise == "N-Back":
        st.markdown("""
        ## πŸ”™ N-Back
        - πŸ”’ Stimuli are presented sequentially
        - πŸ–±οΈ Respond when the current stimulus matches the one from N steps back
        - 🧠 Tests working memory updating and monitoring
        """)
        n_back()
    elif exercise == "Corsi Block Tapping":
        st.markdown("""
        ## 🧱 Corsi Block Tapping
        - πŸ“‹ Blocks are tapped in a sequence
        - πŸ–±οΈ Reproduce the sequence by tapping the blocks in the same order
        - 🧠 Tests visuospatial sketchpad capacity in working memory
        """)
        corsi_block_tapping()
    elif exercise == "Paired Associates":
        st.markdown("""
        ## 🀝 Paired Associates
        - πŸ“š Study a list of word pairs
        - πŸ–±οΈ When cued with one word, recall the paired associate
        - 🧠 Tests associative memory and encoding/retrieval processes
        """)
        paired_associates()
    elif exercise == "Reading the Mind in the Eyes":
        st.markdown("""
        ## πŸ‘€ Reading the Mind in the Eyes
        - πŸ˜”πŸ˜„πŸ˜ πŸ˜Œ View images of eyes expressing a mental state
        - πŸ–±οΈ Select the word that best describes the person's feelings or thoughts
        - 🧠 Tests theory of mind and emotion recognition
        """)
        reading_the_mind_in_the_eyes()
    elif exercise == "Faux Pas Recognition":
        st.markdown("""
        ## 😳 Faux Pas Recognition
        - πŸ“– Read brief stories, some containing a social faux pas
        - πŸ–±οΈ Detect the faux pas and explain why it occurred
        - 🧠 Tests understanding of social norms and recognition of social errors
        """)
        faux_pas_recognition()
    elif exercise == "Interpersonal Perception Task":
        st.markdown("""
        ## πŸ—£οΈ Interpersonal Perception Task
        - πŸŽ₯ Watch brief videos of social interactions
        - πŸ–±οΈ Answer questions about the thoughts, feelings, and intentions of the people
        - 🧠 Tests social perception and understanding of nonverbal cues
        """)
        interpersonal_perception_task()
    elif exercise == "Raven's Progressive Matrices":
        st.markdown("""
        ## 🧩 Raven's Progressive Matrices
        - πŸ”³πŸ”² Complete a matrix or pattern by identifying the missing element
        - πŸ–±οΈ Select the choice that satisfies the rule
        - 🧠 Tests abstract reasoning and fluid intelligence
        """)
        ravens_progressive_matrices()

if __name__ == "__main__":
    main()