pygame.draw.rect和screen_surface.blit()有什么区别?



我试图使一个红色矩形移动到右边,并通过使用pygame.move.rect或.blit,我能够完成同样的事情。我能够显示红色矩形并通过按右箭头将其向右移动。但是,这两个函数之间有什么我应该知道的区别吗?为什么有两个函数基本上做同样的事情?

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

为什么有两个函数基本上做同样的事情?

不,它们不一样。pygame.draw.rect绘制颜色均匀的矩形,pygame.Surface.blitpygame.Surface的一种方法,用于绘制位图图像。

参见pygame.draw.rect:

rect(surface, color, rect) -> Rect
在给定的表面上绘制一个矩形。

参见pygame.Surface.blit

blit(source, dest, area=None, special_flags=0) -> Rect
在此Surface上绘制源Surface

在你的例子中,看起来它们在做同样的事情,因为你的Surface对象均匀地填充了一种颜色。
使用pygame.image.load加载位图图像时,行为完全改变。您不能使用pygame.draw.rect绘制图像,但可以使用blit

何时使用pygame.draw.rect,参见:

Pygame绘制矩形

何时使用blit,请参见:

使用pygame绘制图像的好方法是什么?

位块传输(图像(左)-在给定位置将图像绘制到屏幕上。该函数接受一个Surface或一个字符串作为其图像参数。如果image是一个str,那么命名的图像将从images/目录加载。

。rect(rect, (r, g, b))-绘制矩形的轮廓。取矩形

说明一下,

对图像使用blit,对矩形使用rect。

最新更新