简体   繁体   中英

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

    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.

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. 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!

Python works as follows:

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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