Python / Pygame为什么我的精灵没有移动?

时间:2014-06-25 22:17:07

标签: python python-2.7 pygame sprite

我的代码应该在计算机随机选择的11,15或19个精灵中产生,其中一个正在移动,然后它停止工作。我不在乎看到精灵移动,只要它们实际上正在改变x坐标。他们应该只是跳到新的位置。我正在使用python 2.7和pygame。如果您发现我的代码有问题,我很乐意听到它!我是一般的编码新手,我希望自己变得更好。谢谢! 我的代码如下:

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_delta = 0
t_target = 60*15
t_start = time.time()

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()

'''t_end = time.time() + 60*15
while time.time() < t_end: (other method for determining 15 minute timer)'''

while t_delta < t_target:

    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()
    #draws three squares on screen

    if len(token_list) == 0:
        n = random.randint(1,3)
        if n == 1:
            n=11
        elif n == 2:
            n = 15
        elif n == 3:
            n = 19
    #chooses amount of tokens

    x_coords = [265, 305, 345, 385, 425, 265, 305, 345, 385, 425, 265, 305, 345, 385, 425, 265, 305, 345, 385] 
    y_coords = [170, 170, 170, 170, 170, 210, 210, 210, 210, 210, 250, 250, 250, 250, 250, 290, 290, 290, 290]
    # initial x y coords for token 

    left_score = 0
    right_score = 0

    if len(token_list) < n:
        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)



    if len(token_list) == n:
        token_list.draw(screen)
        pygame.display.update()
        for i in token_list:
            token_direction = random.randint(1,2)
            if token_direction == 1:
                token.rect.x -= 230
                pygame.display.update()
                left_score += 1
                time.sleep(1)

            if token_direction == 2:
                token.rect.x += 230
                pygame.display.update()
                right_score += 1
                time.sleep(1)

    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)
                token_list.empty()
                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)
                token_list.empty()
                pygame.display.update()
                time.sleep(1)

        t_delta = time.time() - t_start

1 个答案:

答案 0 :(得分:0)

还有很多工作要做,但至少令牌正在移动。

import pygame
from pygame.locals import *

import random

#----------------------------------------------------------------------

class Tokens(pygame.sprite.Sprite):

    def __init__(self, color, x, y, width, height):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.Surface([width, height])
        self.image.fill(color)

        self.rect = self.image.get_rect(x=x, y=y)

#----------------------------------------------------------------------

# constants (uppercase names)

GRAY  = (220, 220, 220)
BLACK = (  0,   0,   0)
BLUE  = (  0,   0, 255)
RED   = (255,   0,   0)
WHITE = (255, 255, 255)

#----------------------------------------------------------------------

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()

g = 0

# initial x y coords for token 

x_coords = [265, 305, 345, 385, 425, 265, 305, 345, 385, 425, 265, 305, 345, 385, 425, 265, 305, 345, 385] 
y_coords = [170, 170, 170, 170, 170, 210, 210, 210, 210, 210, 250, 250, 250, 250, 250, 290, 290, 290, 290]

#----------------------------------------------------------------------

# start program

pygame.init()

screen = pygame.display.set_mode((720, 480))

clock = pygame.time.Clock()

state_reset = True

current_time = pygame.time.get_ticks()
end_time = current_time + 60*15*1000 # ms

# --- mainloop ---

while current_time < end_time:

    if state_reset:
        # chooses amount of tokens

        tokens_to_move = random.choice( (11,15,19) )

        tokens_left = 0
        tokens_right = 0

        # create tokens

        tokens_list = []
        tokens_group = pygame.sprite.Group()

        for i in range(tokens_to_move):
            token = Tokens((255,120,0), x_coords[i], y_coords[i], 20, 20)
            tokens_list.append( token )
            tokens_group.add( token )

        move_speed = 1000

        current_time = pygame.time.get_ticks()
        time_to_move = current_time + move_speed # ms

        selected_side = None

        state_selected = False
        state_reset = False


    # --- DRAWS ---

    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)))

    if state_selected:
        if selected_side == 'left':
            pygame.draw.rect(screen, BLUE, Rect((30,140), (200,200)))

        elif selected_side == 'right':
            pygame.draw.rect(screen, BLUE, Rect((490,140), (200,200)))

    tokens_group.draw(screen)

    pygame.display.update()

    # --- CHANGES ---

    if state_selected:
        if selected_time <= current_time:
            state_selected = False

    # moves token

    if tokens_to_move:
        if time_to_move <= current_time:
            time_to_move = current_time + move_speed
            tokens_to_move -= 1
            print 'tokens_to_move:', tokens_to_move
            if random.randint(1,2) == 1:
                tokens_list[tokens_to_move].rect.x -= 230
                tokens_left += 1
            else:
                tokens_list[tokens_to_move].rect.x += 230
                tokens_right += 1
    else:
        state_reset = True

    # --- EVENTS ---

    for event in pygame.event.get():
        if event.type == KEYDOWN:
            g += 1

            if event.key == K_ESCAPE:
                pygame.quit()
                exit()

            elif event.key == pygame.K_SPACE:
                print 'reset'
                state_reset = True

            if not selected_side:
                if event.key == K_LEFT:
                    answer = "left"
                    f = open("results", "a")
                    f.write(str(g) + ", left\n")
                    f.close()
                    selected_side = 'left'
                    print("You picked left!")
                    selected_time = current_time + 1000 # ms
                    move_speed = 0.1
                    state_selected = True

                elif event.key == K_RIGHT:
                    answer = "right"
                    f = open("results", "a")
                    f.write(str(g) + ", right\n")
                    f.close()
                    selected_side = 'right'
                    print("You picked right!")
                    selected_time = current_time + 1000 # ms
                    move_speed = 0.1
                    state_selected = True


    # --- CLOCK ---

    clock.tick(20) # 20 FPS 

    current_time = pygame.time.get_ticks()
    #print 'current_time:', current_time