我试图让一个红色矩形向右移动,通过使用 pygame.move.rect 或 .blit,我能够完成同样的事情。我能够显示红色矩形并通过按向右箭头将其向右移动。但是,我应该知道这两个功能之间有什么区别吗?为什么有 2 个函数基本上做同样的事情。
使用 pygame.move.rect 编写代码
import pygame
import sys
pygame.init()
#obtain the surface and rect for screen
screen_surface = pygame.display.set_mode((1200,800))
pygame.display.set_caption("Hi")
#Obtain Surface and rect for the rectangle
red_rectangle = pygame.Surface((600,400))
red_rectangle_rect = red_rectangle.get_rect()
#make the rectangle surface red
red_rectangle.fill((255,0,0))
move_right = False
while True:
#event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
move_right = True
print(event.type)
print(event.key)
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
move_right = False
#rectangle move to right when right arrow is pressed
if move_right:
red_rectangle_rect.x += 10
print(red_rectangle_rect.x)
screen_surface.fill((255,255,255))
# the difference between this function and the .blit
pygame.draw.rect(screen_surface,(255,0,0),red_rectangle_rect)
pygame.display.flip()
用 .blit 编码
import pygame
import sys
pygame.init()
#obtain the surface and rect for screen
screen_surface = pygame.display.set_mode((1200,800))
pygame.display.set_caption("Hi")
#Obtain Surface and rect for the rectangle
red_rectangle = pygame.Surface((600,400))
red_rectangle_rect = red_rectangle.get_rect()
#make the rectangle surface red
red_rectangle.fill((255,0,0))
move_right = False
while True:
#event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
move_right = True
print(event.type)
print(event.key)
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
move_right = False
#rectangle move to right when right arrow is pressed
if move_right: then
red_rectangle_rect.x += 10
print(red_rectangle_rect.x)
screen_surface.fill((255,255,255))
#Difference between this and the draw function
screen_surface.blit(red_rectangle,red_rectangle_rect)
pygame.display.flip()
最佳答案
Why are there 2 functions that basically do the same thing.
不,他们做的不是一回事。同时pygame.draw.rect
绘制统一颜色的矩形,pygame.Surface.blit
是 pygame.Surface
的一种方法用于绘制位图图像。
参见 pygame.draw.rect
:
rect(surface, color, rect) -> Rect
Draws a rectangle on the given surface.
blit(source, dest, area=None, special_flags=0) -> Rect
Draws a source Surface onto this Surface
在您的情况下,看起来他们在做同样的事情,因为您的Surface 对象均匀地填充了一种颜色。
当您使用 pygame.image.load
加载位图图像时,行为会完全改变。 .您不能使用 pygame.draw.rect
绘制图像,但可以使用 blit
。
什么时候使用pygame.draw.rect
,见:
什么时候使用blit
,见:
关于python - pygame.draw.rect 和 screen_surface.blit() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65964467/