【问题标题】:Python/Pygame Why aren't my sprites moving?Python/Pygame 为什么我的精灵不动?
【发布时间】:2014-06-25 22:17:06
【问题描述】:

我的代码应该在计算机随机选择的 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.2 秒移动一次,而不是 1 秒。如果玩家正确,他的分数将增加 1。15 分钟后,猜对的总数就是他的分数。这有帮助吗?
  • 如果您更改 token.rect.x 并调用 pygame.display.update() 您不会移动令牌。您必须重新绘制令牌。但可能你也必须重新绘制其他元素(灰色背景、黑色矩形、所有标记)
  • 使用当前代码和循环中的time.sleep,您必须等待 19 秒才能获得按键。

标签: python python-2.7 pygame sprite


【解决方案1】:

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

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

【讨论】:

  • 非常感谢你是神。还有一个问题:我在结果文件中添加了一些打印内容,但我无法让它打印“正确的一面”。问题是当tokens_to_move = 0时确定正确的一面,并且播放器在此之前选择了一面,并且在此之前打印了文件中的内容。你能帮我解决这个问题,以及在一切结束时打印玩家得分吗?我还希望在两次试验之间有 1 秒的延迟,它会打印(“正确!”)或(“不正确!”)如果你能为我做这些最后的事情,我会喜欢
  • 你永远永远。我上传了一个新问题 furas 是最好的。使用我的新代码(或者我会在几分钟内,因为问题的时间会重置)
  • 您可以添加新状态 - 我们称之为state_gameover - 并使用它将结果写入文件并以 1 秒的时间在屏幕上打印结果。通过电子邮件给我写信:furas@tlen.pl。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-15
  • 2023-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多