Python TypeError:参数1必须是pygame.Surface,而不是pygame.Rect

时间:2017-06-10 09:36:09

标签: python python-3.x pygame

我无法理解Stackoverflow中的其他问题。当圆圈朝屏幕的末端移动时,它会向相反的方向移动。

import pygame
import sys
pygame.init()
screen = pygame.display.set_mode([640,480])
screen.fill([255,255,255])
circle = pygame.draw.circle(screen, [255,0,0],[100,100],30,0)
x = 50
y = 50
x_speed = 5
y_speed = 5

done = "False"
while done == "False":
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done="True"
    pygame.time.delay(20)
    pygame.draw.rect(screen,[255,255,255],[x,y,30,30],0)
    x = x + x_speed
    y = y + y_speed
    if x > screen.get_width() - 30 or x < 0:
        x_speed = -x_speed
    if y > screen.get_height() - 30 or y < 0:
        y_speed = -y_speed
    screen.blit(circle,[x,y])
    pygame.display.flip()

pygame.quit()

在未实施的情况下发出错误消息。

  

screen.blit(circle,[x,y])
  TypeError:参数1必须是pygame.Surface,而不是pygame.Rect

有什么问题?

1 个答案:

答案 0 :(得分:1)

pygame.draw.circle会返回pygame.Rect而不是pygame.Surface,而您只能blit个表面不会显示(这是追溯告诉您的内容)。因此,创建一个表面对象,使用pygame.draw.circle在其上绘制一个圆,然后将此表面blit到主循环中的屏幕上。

import pygame
import sys

pygame.init()
screen = pygame.display.set_mode([640,480])
screen.fill([255,255,255])

# A transparent surface with per-pixel alpha.
circle = pygame.Surface((60, 60), pygame.SRCALPHA)
# Draw a circle onto the `circle` surface.
pygame.draw.circle(circle, [255,0,0], [30, 30], 30)

x = 50
y = 50
x_speed = 5
y_speed = 5

done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    pygame.time.delay(20)
    screen.fill((40, 40, 40))
    x = x + x_speed
    y = y + y_speed
    if x > screen.get_width() - 60 or x < 0:
        x_speed = -x_speed
    if y > screen.get_height() - 60 or y < 0:
        y_speed = -y_speed
    # Now blit the surface.
    screen.blit(circle, [x, y]) 
    pygame.display.flip()

pygame.quit()
sys.exit()