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

如何在 pygame 上移动图像?

如何解决如何在 pygame 上移动图像?

我是 pygame 的新手。我以前在 Python 上编码过,但从未在 pygame 中编码过。 我编写了一个代码,当单击某些键时会播放声音,现在我尝试在每次用户用鼠标单击时使图像移动。

import pygame,os,sys

pygame.init()
screen = pygame.display.set_mode((1300,1300))
screen.fill((250,250,250))

img = pygame.image.load(os.path.join(sys.path[0],"fonddecran.v1.jpg"))
screen.blit(img,(0,0))
pygame.display.flip()
barrel=pygame.image.load(os.path.join(sys.path[0],"barrel-man.jpg"))
pygame.display.flip()
pygame.mixer.init()

it = true
while it:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            it=False

        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 3:
                pygame.mixer.music.load(os.path.join(sys.path[0],"Mi-mineur.mp3"))
                pygame.mixer.music.play()
            elif event.button == 1:
                screen.blit(barrel,event.pos)
                pygame.display.flip()

        elif event.type == pygame.KEYUP:
            if event.key == ord('b'):
                pygame.mixer.music.load(os.path.join(sys.path[0],"Mi-mineur.mp3"))
                pygame.mixer.music.play()
pygame.quit()

不幸的是,图像每次只出现一次。我怎样才能删除它,让它看起来像已经移动了?

解决方法

为了能够“移动”图像,您必须在每一帧中重新绘制场景。添加一个存储图像位置的变量。单击鼠标时将变量更改为鼠标位置:

import pygame,os,sys

pygame.init()
screen = pygame.display.set_mode((1300,1300))

img = pygame.image.load(os.path.join(sys.path[0],"fonddecran.v1.jpg"))
barrel=pygame.image.load(os.path.join(sys.path[0],"barrel-man.jpg"))
pygame.mixer.init()

barrel_pos = None

it = True
while it:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            it=False

        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 3:
                pygame.mixer.music.load(os.path.join(sys.path[0],"Mi-mineur.mp3"))
                pygame.mixer.music.play()
            elif event.button == 1:
                barrel_pos = event.pos

        elif event.type == pygame.KEYUP:
            if event.key == ord('b'):
                pygame.mixer.music.load(os.path.join(sys.path[0],"Mi-mineur.mp3"))
                pygame.mixer.music.play()

    screen.fill((250,250,250))
    screen.blit(img,(0,0))
    if barrel_pos:
        screen.blit(barrel,barrel_pos)
    pygame.display.flip()

pygame.quit()

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