python心理学实验程序
使用pygame做了个小实验。
任务主要包括:选词任务;呈现图片和字母,对字母进行判断;选数任务。
选词任务:10个词语呈现顺序随机,选择其中3个。
字母判断任务:字母Q或O出现在图片的左边或右边,判断字母为哪个。20张图片字母q/o字母位置左右 = 80种条件。80种随机,同时不能连续呈现一样的图片。
选数任务:从1-7选择一个数字。
程序中涉及实验材料的部分被省略。
本实验的psychopy版本在我的另一篇文章中,
原文链接:https://blog.youkuaiyun.com/qinglinc/article/details/105035920
pygame写的程序可以很方便地打包为exe程序,
而psychopy写的程序打包时总会遇到各种问题。
(欢迎读者与我交流)
# import libraries
from base64 import b64decode
from random import shuffle
import pygame
from pygame.locals import *
# trial list
group_list = ['11', '12', '22', '21']
wordtrials = [……] # 略
letter_trials = [['L', 'Q'],
['L', 'O'],
['R', 'Q'],
['R', 'O']]
pictrials_prac = [[ele7, 'ele', '7'],
[ele27, 'ele', '27'],
[sex3, 'sex', '3'],
[sex15, 'sex', '15']]
pictrials = [[ele2, 'ele', '2'],……] # 略
# wait for a key press
def wait4key(duration, keys_allowed):
""" wait for a key response.
duration: wait for how long
keys_allowed: which keys are allowed,
keys_allowed should be list, such as [K_z, K_SLASH]. """
got_key = False
time_out = False
t_start = pygame.time.get_ticks()
pygame.event.clear()
while not (got_key or time_out):
# check for time out
t_now = pygame.time.get_ticks()
if t_now - t_start >= duration:
time_out = True
# check for key responses
for ev in pygame.event.get():
if ev.type == KEYDOWN:
if ev.key in keys_allowed:
resp_time = t_now - t_start
resp_key = pygame.key.name(ev.key)
got_key = True
if got_key:
return [resp_key, resp_time]
else:
return [None, None]
# run a single trial
def run_pictrial(pars, letter_pars, data_file):
""" pars should be list that specifies the
location and color of the stimulus, as well as
the correct key response, such as ['R', 'B', '/']"""
file, catog, num = pars
lll, letter = letter_pars
if lll == 'R': loo = right
if lll == 'L': loo = left
img_data = b64decode(file) # 图片的编码此处略
with open('001.jpg', 'wb') as f:
f.write(img_data)
# present the fixation
win.fill(black)
text_msg('+', (scr_width/2, scr_height/2), 48, False)
pygame.display.update()
pygame.time.wait(1000)
# picture
pic = pygame.image.load('001.jpg')
win.fill(black)
win.blit(pic, (scr_width/2 - pic.get_width() / 2, scr_height/2 - pic.get_height() / 2))
pygame.display.update()
pygame.time.wait(50)
# picture & letter
text_msg(letter, loo, 48, False)
pygame.display.update()
pygame.time.wait(50)
# present picture
win.fill(black)
win.blit(pic, (scr_width/2 - pic.get_width() / 2, scr_height/2 - pic.get_height() / 2))
pygame.display.update()
tar_resp = wait4key(1200, [K_q, K_o, K_z, K_0])# K_SLASH
win.fill(black)
pygame.display.update()
pygame.time.wait(500)
# write data to file
if tar_resp[0] == None:
acc = '0'
rrr = 0
else:
rrr = tar_resp