Python 如何使图像移动

Python 如何使图像移动,python,pygame,Python,Pygame,所以我有一个图像,我想用WASD键移动它。我不完全理解如何做到这一点,我有一个主循环。 这就是我的形象,它是占有的 no_image = pygame.image.load("Ideot.png").convert x_coord = 500 y_coord = 250 no_position = [x_coord,y_coord] 此代码位于主循环后面。在主循环之后,我实际上通过 screen.blit(no_image,no_position) 这就是我的循环看起来的样子 完成=错误

所以我有一个图像,我想用WASD键移动它。我不完全理解如何做到这一点,我有一个主循环。 这就是我的形象,它是占有的

no_image = pygame.image.load("Ideot.png").convert
x_coord = 500 
y_coord = 250
no_position = [x_coord,y_coord]
此代码位于主循环后面。在主循环之后,我实际上通过

screen.blit(no_image,no_position)
这就是我的循环看起来的样子 完成=错误

while not done:
   for event in pygame == pygame.Quit:
       done = True

你能演示如何使用WASD移动图像吗?首先,我将介绍当前的评论。MattDMo是对的,这不是一个代码编写服务,而是一种帮助人们理解他们的问题或事情为什么起作用或为什么不起作用的方法。最好先尝试一下,如果你想不出来,再问你的问题。marienbad的链接确实使图像移动了,但方式不方便。该链接的代码将在每次按下某个键时移动您的图像(很有用,我建议您查看它),但在按住某个键的同时移动图像很好

让图像在按住键的同时移动是一件棘手的事情。我喜欢用布尔语

如果您没有正在使用的勾选方法,请立即停止并将其设置到位。查看pygame.org/docs了解如何操作,它们有很好的示例代码。如果没有它,移动将无法按您所希望的方式工作,因为如果您不限制它,该循环将以计算机所能处理的速度运行,因此您甚至可能看不到您的移动

from pygame.locals import * # useful pygame variables are now at your disposle without typing pygame everywhere.

speed = (5, 5) # Amount of pixels to move every frame (loop).
moving_up = False
moving_right = False
moving_down = False
moving_left = False # Default starting, so there is no movement at first.
上面的代码用于while循环之外。您的event for循环将需要稍微更改,为了改进代码,我建议在这里使用函数,或者使用字典来消除所有这些if语句的需要,但我不仅仅是为了让我的答案更简单,让大家明白这一点。我省略了一些细节,比如event.quit,因为您已经有了它们

如果你不包括键控部分,你的角色将永远不会停止移动

for event in pygame.event.get():
    if event.type == KEYDOWN:
        if event.key == K_w:
            moving_up = True
        if event.key == K_d
            moving_right = True
        if event.key == K_s:
            moving_down = True
        if event.key == K_a:
            moving_left = True

    if event.type == KEYUP:
       if event.key == K_w:
            moving_up = False # .. repeat this for all 4.
然后在后面的循环中

if moving_up:
    y_coord += -speed[1] # Negative speed, because positive y is down!
if moving_down:
    y_coord += speed[1]
if moving_right:
    x_coord += speed[0]
if moving_left:
    x_coord += -speed[0]

现在,当x/y坐标设置为“移动”时,它们将发生变化,这将用于blit图像!请确保在此场景中不使用elif,如果您持有两个键,您希望能够通过组合键(例如向右键和向上键)移动,以便可以向东北移动。

堆栈溢出不是代码编写或教程服务。请提出您的问题,并发布您迄今为止尝试过的内容,包括示例输入、预期输出以及任何错误或回溯的全文。[链接]很抱歉写这篇文章,,,我实际上是通过谷歌搜索找到的,我的错。谢谢你的回答!