繁体   English   中英

如何在 pygame 上移动图像?

[英]How to move an image on 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()

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

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

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM