简体   繁体   English

在Pygame中,我无法移动子画面? 是我的代码吗?

[英]In Pygame i cannot make my sprite move?? is it my code?

my sprite doesnt move when i use the arrow key?? 使用箭头键时,我的精灵不会移动? i have looked at my code and i cannot for the life of me work out what is wrong with it?? 我已经查看了我的代码,但我终生无法解决它的问题所在? any help would be apreciated massively thanks in advance!!:D 任何帮助将不胜感激在此先感谢!!:D

    bif="cloud.jpg"
    mif="reddwarf.png"

import pygame,sys
from pygame.locals import *

pygame.init()

DISPLAYSURF=screen=pygame.display.set_mode((813,555),32,0)
background=pygame.image.load(bif).convert()
mouse_c=pygame.image.load(mif).convert_alpha()

x,y=0,0
movex, movey=0,0

while True:

for event in pygame.event.get():
    if event.type == QUIT:
        pygame.quit()
        sys.exit()
    if event.type ==KEYDOWN:
        if event.key==K_LEFT:
            movex=-1
        elif event.key==KEY_RIGHT:
            movex=+1
        elif event.key==K_UP:
            movey=-1
        elif event.key==K_DOWN:
            movey=+1
    if event.type==KEYUP:
        if event.key==K_LEFT:
            movex=0
        elif event.key==KEY_RIGHT:
            movex=0
        elif event.key==K_UP:
            movey=0
        elif event.key==K_DOWN:
            movey=0

x+=movex
y+=movey

screen.blit(background,(0,0))
screen.blit(mouse_c,(x,y))

pygame.display.update()

Check your indentation. 检查您的缩进。 It looks like your for loop which checks your events isn't inside your while loop, and neither is your code which moves your sprite or updates your screens. 看起来,用于检查事件的for循环不在while循环内,并且您的代码也不可移动您的精灵或更新屏幕。

Referring to your title first: If something doesn't work, chances are, that it really is due to your code ;) 首先提到您的标题:如果某事不起作用,则很有可能这确实是由于您的代码所致;)

Indendation is extremely important in Python. 内在化在Python中极为重要。 This part here: 这部分在这里:

x+=movex
y+=movey

screen.blit(background,(0,0))
screen.blit(mouse_c,(x,y))

pygame.display.update()

is outside the while loop! 在while循环之外!

Python works as follows: Python的工作方式如下:

while True:
    do_something()
    #this code will run while the condition remains true
do_something_else()
#code with this indendation level will run AFTER the while loop has finished.
#It's on the same indendation level like while.

You have to indend the part of your code I posted above so it is on the same indendation level as the 您必须使用我上面发布的代码的一部分,因此它与

if event.type == ...

blocks. 块。 The way it is arranged now, the x+=movex ..... parts are waiting till the while loop ends - and that's not really ever going to happen, so there's no update of the x/y values and the blitting. 现在它的排列方式是,x + = movex .....部分一直等到while循环结束时-这实际上永远不会发生,因此没有更新x / y值和闪烁。

Looks like an indentation error. 看起来像是缩进错误。 You need to put your 你需要把你的

x+=movex
y+=movey

screen.blit(background,(0,0))
screen.blit(mouse_c,(x,y))

In the while True loop. 在while True循环中。

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

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