I am new to psychopy and am trying to write an experiment.
However, when I changed my code to js, it reminded me: /* Syntax Error: Fix Python code */. I think the problem is because of the function validate_sequence(sequence) part. But I have no idea how to solve this.
Thank you very much for your help.
def generate_sequence():
Os = 24
Ss = 6
sequence = ['O'] # 第一个元素是O
if generate_valid_sequence(sequence, Os - 1, Ss): # -1 因为已经放入了第一个O
return sequence
def generate_valid_sequence(sequence, Os, Ss):
if Os == 0 and Ss == 0:
return validate_sequence(sequence + ['O']) # 最后一个元素是O
# 尝试在当前序列后面添加一个'O'
if Os > 0:
sequence.append('O')
if generate_valid_sequence(sequence, Os - 1, Ss):
return True
sequence.pop() # 回溯
# 尝试在当前序列后面添加一个'S'
if Ss > 0:
sequence.append('S')
if generate_valid_sequence(sequence, Os, Ss - 1):
return True
sequence.pop() # 回溯
return False
def validate_sequence(sequence):
# 检查第一个和最后一个是否为O
if sequence[0] == 'S' or sequence[-1] == 'S':
return False
# 检查是否有连续的两个S
i = 0
while i < len(sequence) - 1:
if sequence[i] == 'S' and sequence[i+1] == 'S':
return False
i += 1
# 检查O的最大连续数是否超过7
max_consecutive_Os = 0
current_consecutive_Os = 0
i = 0
while i < len(sequence):
if sequence[i] == 'O':
current_consecutive_Os += 1
max_consecutive_Os = max(max_consecutive_Os, current_consecutive_Os)
else:
current_consecutive_Os = 0
i += 1
if max_consecutive_Os > 7:
return False
return True
# 生成符合条件的序列
sequence = generate_sequence()
# 定义TextStim对象用于显示O或S
stim = visual.TextStim(win, text='', height=0.3, color='black')
# 定义刺激点
fixation = visual.TextStim(win, text='·', height=0.15, color='black')
# 定义反馈提示的TextStim对象
feedback = visual.TextStim(win, text='', height=0.1, font='Arial Unicode MS')
# 按顺序呈现每个刺激点和字符
i = 0
while i < len(sequence):
item = sequence[i]
# 首先呈现250ms的刺激点
fixation.draw()
win.flip()
core.wait(0.25)
# 然后呈现O或S字符
stim.text = item
stim.draw()
win.flip()
# 等待0.5秒的反应时间
keys = event.waitKeys(maxWait=0.5, keyList=['return'])
# 根据反应与字符类型显示相应的反馈
if item == 'O':
if keys: # 如果按了Enter键
feedback.text = "正确反应"
feedback.color = 'green'
else: # 如果没有按键
feedback.text = "错误,你应该做出反应"
feedback.color = 'red'
elif item == 'S':
if keys: # 如果按了Enter键
feedback.text = "错误,你应该停止反应"
feedback.color = 'red'
else: # 如果没有按键
feedback.text = "正确停止反应"
feedback.color = 'green'
# 显示反馈
feedback.draw()
win.flip()
core.wait(0.5) # 显示反馈0.5秒
# 检查退出条件,如按下'escape'键
if 'escape' in event.getKeys():
break
i += 1
# 关闭窗口
win.close()
core.quit()