我正在尝试在基于pyGame的随机地图生成器中设置滚动。但是,我很难弄清楚如何防止显示“抹上”背景,而不仅仅是滚动显示。我仅针对堆栈溢出制作了一个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显示:
答案 0 :(得分:1)
pygame.Surface.scroll()
并没有达到您的期望。它不能无缝滚动 roll 表面。请参阅文档:
scroll()
将表面图像移到适当位置[...]未被覆盖的表面区域保留其原始像素值。 [...]
您必须编写自己的 scroll 函数,该函数将移出的表面部分放置在表面的另一侧。
例如编写2个函数(scrollX
和scrollY
),它们可以沿轴 roll 滚动:
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)