我试图在我的基于pyGame的随机地图生成器中设置滚动。但是,我无法弄清楚如何防止显示器“涂抹”背景而不是仅仅滚动它。我已经为Stack Overflow制作了一个仅显示彩色方块的MCV示例。它有同样的问题。
如何在不弄脏屏幕的情况下进行显示滚动?
这是我滚动一下后地图生成器显示的内容:
MCV示例:
""" This example just displays colored squares. """
import pygame
import sys
def main():
pygame.init()
screen = pygame.display.set_mode((800, 800))
x_pos = 0
y_pos = 0
yellow = (255, 255, 0)
blue = (0, 0, 255)
# draw pattern of yellow and blue squares
for y in range(100):
for x in range(100):
if (y + x) % 2 == 0:
pygame.draw.rect(screen, yellow, (x_pos, y_pos, 50, 50))
else:
pygame.draw.rect(screen, blue, (x_pos, y_pos, 50, 50))
x_pos += 50
y_pos += 50
x_pos = 0
while True: # <-- the pyGame loop
event = pygame.event.poll()
pressed = pygame.key.get_pressed()
# handle window closing
if event.type == pygame.QUIT:
break
# handle scrolling
if pressed[pygame.K_UP]:
screen.scroll(0, 2)
elif pressed[pygame.K_DOWN]:
screen.scroll(0, -2)
elif pressed[pygame.K_LEFT]:
screen.scroll(2, 0)
elif pressed[pygame.K_RIGHT]:
screen.scroll(-2, 0)
# updates what the window displays
pygame.display.update()
pygame.quit()
sys.exit(0)
if __name__ == "__main__":
# runs the pyGame loop
main()
初始MCVE图像
滚动后的MCVE显示:
pygame.Surface.scroll()
不符合您的期望。它不会无缝地滚动表面。查看文档:
scroll()
将表面图像移动到位[...]未覆盖的曲面区域保留其原始像素值。 [...]
你要编写自己的滚动函数,它将表面的一部分放在你的表面的另一边。
例如写2个函数(scrollX
和scrollY
),它们可以沿轴滚动:
def scrollX(screenSurf, offsetX):
width, height = screenSurf.get_size()
copySurf = screenSurf.copy()
screenSurf.blit(copySurf, (offsetX, 0))
if offsetX < 0:
screenSurf.blit(copySurf, (width + offsetX, 0), (0, 0, -offsetX, height))
else:
screenSurf.blit(copySurf, (0, 0), (width - offsetX, 0, offsetX, height))
def scrollY(screenSurf, offsetY):
width, height = screenSurf.get_size()
copySurf = screenSurf.copy()
screenSurf.blit(copySurf, (0, offsetY))
if offsetY < 0:
screenSurf.blit(copySurf, (0, height + offsetY), (0, 0, width, -offsetY))
else:
screenSurf.blit(copySurf, (0, 0), (0, height - offsetY, width, offsetY))
if pressed[pygame.K_UP]:
scrollY(screen, 2)
elif pressed[pygame.K_DOWN]:
scrollY(screen, -2)
elif pressed[pygame.K_LEFT]:
scrollX(screen, 2)
elif pressed[pygame.K_RIGHT]:
scrollX(screen, -2)