2014-04-16 40 views
0

当我使用箭头键时,我的精灵不移动?我看了我的代码,我不能为我的生活工作出什么问题呢?任何帮助将大量提前预先感谢!!:D在Pygame中,我无法让我的精灵移动?这是我的代码吗?

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

'IndentationError'? – That1Guy

回答

0

检查您的缩进。它看起来像你的for循环,它检查你的事件不在你的while循环中,你的代码也不会移动你的精灵或更新你的屏幕。

0

参考您的标题第一:如果有什么不工作,机会是,它真的是因为你的代码;)

Indendation在Python极其重要的。这部分在这里:

x+=movex 
y+=movey 

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

pygame.display.update() 

是在while循环之外!

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. 

你必须indend我张贴以上,因此在同一indendation水平为

if event.type == ... 

块代码的一部分。现在安排它的方式,x + = movex .....部分正在等待直到while循环结束 - 并且这不会真的发生,所以不会更新x/y值和blitting。

+0

非常感谢?我敢肯定,你可以告诉我对pygame是新手,但是我应该从我的python经验中知道这一点:(谢谢 – user3542499

+0

呃,比你想象的更频繁地发生:D就在昨天,我在这里问了一些问题,有人指出,那只是传递给某个方法的某些变量的顺序是错误的,实际上没有代码或者我做它的方式... –

+0

我现在有另一个问题,我得到以下错误消息:Traceback(最近调用最后一次): File“ C:\ Python27 \ reddwarf.py“,第25行,在 elif event.key == KEY_RIGHT: NameError:名称'KEY_RIGHT'未定义 – user3542499

0

看起来像一个缩进错误。你需要把你的

x+=movex 
y+=movey 

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

在while循环。

相关问题