【问题标题】:Why Does PyGame Trail the Image? [duplicate]为什么 PyGame 会跟踪图像? [复制]
【发布时间】:2013-02-09 13:39:29
【问题描述】:

我正在尝试使用 pygame 和 IDLE 在 python 中开发一个简单的游戏。从昨天开始,我已经查看了各种资源以了解该语言(以及一般的编程),即使如此,我还是遇到了一些问题和对它如何工作的误解。所以,如果有人能告诉我如何继续(或向我指出一些好的学习材料的方向),我将不胜感激。

到目前为止,我已经有了一些构成我的游戏理念基础的代码,所以我将在此处发布并列出我的一些问题。

import pygame

def main():


pygame.init()


logo = pygame.image.load("coolblack.jpg")
pygame.display.set_icon(logo)
pygame.display.set_caption("Battleship")


screenWidth = 800
screenHeight = 600
screen = pygame.display.set_mode((screenWidth, screenHeight))


bgd_image = pygame.image.load("grid.png")
#--------------------------------------------------------------------
#the image named 'image' should be above 'bgd_image' but below 'cv9'
#in fact, everything should be above bgd_image, especially 'cv9'
#--------------------------------------------------------------------
image = pygame.image.load("coolblack.jpg")
cv9 = pygame.image.load("ussessexcv9.gif").convert_alpha()


xposCv9 = 400
yposCv9 = 510


step_xCv9 = 1
step_yCv9 = 1


screen.blit(bgd_image, (0,0))
screen.blit(image, (400,300))
screen.blit(cv9, (xposCv9, yposCv9))


pygame.display.flip()
clock = pygame.time.Clock()
running = True

#---------------------------------------------
#I've got a pretty good idea (sort of) about
#what is happening in the section
#below this point, however it seems that
#the image 'cv9' creates a trail of itself
#every time it moves, so how could I make it 
#so that it doesn't do so?
#---------------------------------------------
while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            running = False
    if xposCv9>screenWidth-64 or xposCv9<0:
        step_xCv9 = -step_xCv9
    if yposCv9>screenHeight-64 or yposCv9<0:
        step_yCv9 = -step_yCv9
    xposCv9 += step_xCv9
    yposCv9 += step_yCv9
    screen.blit(cv9, (xposCv9, yposCv9))
    pygame.display.flip()
    clock.tick(60)


if __name__=="__main__":
    main()

【问题讨论】:

    标签: python pygame trail


    【解决方案1】:

    pygame 的工作方式是它在内部具有您正在更新的屏幕的表示形式。所以,它开始完全是黑色的,然后你做你的第一个“blit”。这将更新内部表示。然后,当您调用“pygame.display.flip”时,它会在屏幕上显示该表示。但是,这不会自动将您的表示“清除”为下一帧的全黑。因此,在下一帧中,您再次进行 blit(例如,稍微向左),而第一个 blit 仍然存在,从而创建了您的“轨迹”。

    因此,对于您正在做的事情,最好的办法是在您的循环中,在开始绘制下一帧之前清除屏幕的内部表示。您可以通过用单一颜色填充屏幕来“清除”屏幕,就像这样......

    BLACK = (0,0,0)
    ....
    screen.blit(cv9, (xposCv9, yposCv9))
    pygame.display.flip()
    clock.tick(60)
    screen.fill(BLACK) # Add this to "clear" the screen.
    

    请注意,如果您选择走这条路线,这意味着您需要在每一帧重绘所有元素(不仅仅是自上一帧以来更改的元素)。

    顺便说一句,如果您想知道,最后没有自动清除框架是有充分理由的。在某些情况下,仅更新更新的屏幕部分可能会更快。这可能会导致某些应用程序的性能加速。但是,最好从清除屏幕开始,如上例所示。

    【讨论】:

    • 非常感谢这对我帮助很大!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 2021-06-07
    相关资源
    最近更新 更多