Python TypeError:参数 1 必须是 pygame.表面,而不是pygame.rect



我无法理解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](
类型错误:参数 1 必须是 pygame。表面,而不是游戏。矩形

怎么了?

pygame.draw.circle返回pygame.Rect而不是pygame.Surface,并且您只能blit曲面而不是矩形(这就是回溯告诉您的(。因此,创建一个表面对象,使用pygame.draw.circle在其上绘制一个圆,然后将此表面块状到主循环中的屏幕上。

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

最新更新