我的精灵(代币)没有出现在屏幕上。我包含了所有代码,因为代码正文中的某些东西搞乱了。我把直接与令牌精灵有关的代码放在星星上。代码的要点是:屏幕上出现三个块,而现在我正在尝试制作11,15或21个令牌(橙色20x20像素正方形),它们在中间圆圈中展开。他们没有露面。忽略关于箭头键的代码,因为以后会这样做。我的首要任务是让精灵出现,但如果你有任何关于加快或更好地组织我的代码的建议,我很乐意听到它!感谢。
import pygame, sys
from pygame.locals import *
import pygame
import time
import random
pygame.init()
screen = pygame.display.set_mode((720, 480))
gray = pygame.Color(220, 220, 220)
black = pygame.Color(0, 0, 0)
blue = pygame.Color(0, 0, 255)
red = pygame.Color(255, 0 ,0)
white = pygame.Color(255, 255, 255)
t_end = time.time() + 60*15
g=0
f = open("results", "a")
f.write("trial number, answer, reaction time, correct answer, number of balls in left circle at response, number of balls in middle circle at response, number of balls in right circle at response\n")
f.close()
**class tokens(pygame.sprite.Sprite):
def __init__(self, color, width, height):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([width, height])
self.image.fill(color)
self.rect = self.image.get_rect()
token_list = pygame.sprite.Group()**
while time.time() < t_end:
screen.fill(gray)
pygame.draw.rect(screen, black, Rect((30,140), (200,200)))
pygame.draw.rect(screen, black, Rect((260,140), (200,200)))
pygame.draw.rect(screen, black, Rect((490,140), (200,200)))
pygame.display.update()
**n = random.randint(1,3)
if n == 1:
n=11
elif n == 2:
n = 15
elif n == 3:
n = 21
x_coords = [35, 75, 115, 155, 195, 35, 75, 115, 155, 195, 35, 75, 115, 155, 195, 35, 75, 115, 155, 195]
y_coords = [170, 170, 170, 170, 170, 210, 210, 210, 210, 210, 250, 250, 250, 250, 250, 290, 290, 290, 290, 290]
for i in range(0,n):
token = tokens((255,120,0), 20, 20)
token.rect.x = x_coords[i-1]
token.rect.y = y_coords[i-1]
token_list.add(token)**
for event in pygame.event.get():
if event.type == KEYDOWN:
g+=1
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
answer = "left"
f = open("results", "a")
f.write(str(g) + ", left\n")
f.close()
pygame.draw.rect(screen, blue, Rect((30,140), (200,200)))
print("You picked left!")
pygame.display.update()
time.sleep(1)
screen.fill(black)
pygame.display.update()
time.sleep(1)
elif keys[pygame.K_RIGHT]:
answer = "right"
f = open("results", "a")
f.write(str(g) + ", right\n")
f.close()
pygame.draw.rect(screen, blue, Rect((490,140), (200,200)))
print("You picked right!")
pygame.display.update()
time.sleep(1)
screen.fill(black)
pygame.display.update()
time.sleep(1)
答案 0 :(得分:0)
您将精灵添加到token_list
精灵组,但实际上从未实际绘制它们。
最简单的方法是在更新屏幕之前调用token_list.draw(screen)
。
此外,您的事件处理搞砸了。例如。如果您已经捕获pygame.key.get_pressed()
事件,则无需使用KEYDOWN
获取所有按键。只需检查event.key
或K_LEFT
或K_RIGHT
。