按键可使图像在屏幕上移动

时间:2013-09-11 06:57:32

标签: python pygame

之前我有这个脚本工作,但现在它不起作用。早些时候,图像在屏幕上移动很好,但现在它甚至都不会移动,当我向上或向下或向左或向右键按下时,图像只是停留在角落里根本不移动

import pygame, sys
from pygame.locals import *
pygame.init()

bifl = 'screeing.jpg'
milf = 'char_fowed_walk1.png'

screen = pygame.display.set_mode((640, 480))
background = pygame.image.load(bifl).convert()
mouse_c = pygame.image.load(milf).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 =- 0.3
            elif event.key == K_RIGHT:
                movex =+ 0.3
            elif event.key == K_UP:
                movey =- 0.3
            elif event.key == K_DOWN:
                movey =+ 0.3

        if event.type == KEYDOWN:
            if event.key == K_LEFT:
                movex = 0
            elif event.key == K_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()

我正在使用python 2.7

1 个答案:

答案 0 :(得分:1)

您需要做的就是将第二个KEYDOWN更改为KEYUP,这样只要您按一个键,您的移动速度就不会设置为0.

编辑:此外,您的代码中有一些奇怪的语法。 =-=+不是Python运算符。我认为你的意思是+=-=。还要记住尽可能使用elif语句而不是if语句。这不仅可以优化您的代码,还可以使您更容易理解和调试。

import pygame, sys
from pygame.locals import *
pygame.init()

bifl = 'screeing.jpg'
milf = 'char_fowed_walk1.png'

screen = pygame.display.set_mode((640, 480))
background = pygame.image.load(bifl).convert()
mouse_c = pygame.image.load(milf).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 -= 0.3
            elif event.key == K_RIGHT:
                movex += 0.3
            elif event.key == K_UP:
                movey -= 0.3
            elif event.key == K_DOWN:
                movey += 0.3

        elif event.type == KEYUP:
            if event.key == K_LEFT:
                movex = 0
            elif event.key == K_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()