我试图使红色矩形向右移动,通过使用 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()
Run Code Online (Sandbox Code Playgroud)
带有 .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()
Run Code Online (Sandbox Code Playgroud)
为什么有两个函数基本上做同样的事情。
不,他们做的不是同一件事。绘制pygame.draw.rect统一颜色的矩形是一种用于绘制位图图像pygame.Surface.blit的方法。pygame.Surface
rect(surface, color, rect) -> Rect
在给定的表面上绘制一个矩形。
blit(source, dest, area=None, special_flags=0) -> Rect
将源 Surface 绘制到此 Surface 上
在你的例子中,看起来他们正在做同样的事情,因为你的Surface对象均匀地填充了一种颜色。
当您使用 加载位图图像时,行为会完全改变pygame.image.load。您不能使用 绘制图像pygame.draw.rect,但可以使用blit。
何时使用pygame.draw.rect,请参阅:
何时使用blit,请参阅: