微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在此代码中添加背景而不会出现错误?

如何解决如何在此代码中添加背景而不会出现错误?

def game():
running = True
while running:
    screen.fill((0,0))
    mx,my = pygame.mouse.get_pos()
    button_3 = pygame.Rect(300,100,1300,700)
    if button_3.collidepoint((mx,my)):
        if click:
            begin()

    draw_text('game',font,(255,255,255),screen,20,20)
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                running = False


    # set the pygame window name

    img1 = pygame.image.load(r"C:\Users\ga-sa\Downloads\As.png")
    img2 = pygame.image.load(r"C:\Users\ga-sa\Downloads\AssetsXOR.png")
    img3 = pygame.image.load(r"C:\Users\ga-sa\Downloads\AssetsNOT.png")
    img4 = pygame.image.load(r"C:\Users\ga-sa\Downloads\AssetsAND.png")

    images = [img1,img2,img3,img4]

    current_image = -1
    img_rects = [images[i].get_rect(topleft=(20 + 40 * i,20)) for i in range(len(images))]

    LeftButton = 0
    while 1:
        for e in pygame.event.get():
            if e.type == QUIT:
                pygame.quit()
                exit(0)

            if e.type == pygame.MOUSEBUTTONDOWN:
                mouse_rect = pygame.Rect(e.pos,(1,1))
                current_image = mouse_rect.collidelist(img_rects)

            if e.type == MOUSEMOTION:
                if e.buttons[LeftButton]:
                    rel = e.rel
                    if 0 <= current_image < len(images):
                        img_rects[current_image].x += rel[0]
                        img_rects[current_image].y += rel[1]

        screen.fill(0)
        for i in range(len(images)):
            screen.blit(images[i],img_rects[i])
        pygame.display.flip()
        pygame.time.delay(30)

    screen.blit(BACKGROUND_FASE,(0,0))
    pygame.display.update()
    mainClock.tick(60)

我想在此屏幕上添加背景图像,但是每次尝试出错或没有出现错误时,如何在没有错误的情况下向该部分添加背景,代码的另一部分是一个菜单,当我单击“开始”时,将显示此屏幕,并且整个代码在此处https://pastebin.com/Rb7jh2GH

解决方法

在绘制场景之前,您必须先blit背景,并且必须在游戏循环中绘制背景。绘制背景时,它会覆盖之前绘制的所有内容:

  1. 绘制背景
  2. 绘制场景(所有对象)
  3. 更新显示

请注意,绘制背景图像时无需清除背景。如果背景图像覆盖了整个窗口,则无需清除背景。

screen.fill(0)

while running:
    # [...]

    while 1:
        for e in pygame.event.get():
            if e.type == QUIT:
                pygame.quit()
                exit(0)

        # [...]

        # draw background
        # screen.fill(0)  <--- superfluous
        screen.blit(BACKGROUND_FASE,(0,0))

        # draw scene (objects)
        for i in range(len(images)):
            screen.blit(images[i],img_rects[i])

        # update display
        pygame.display.flip()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。