简体   繁体   English

python和pygame图像移动

[英]python and pygame image movement

Ok so my code is below, right now I'm new to pygame and trying to figure out how to move images on the screen. 好的,所以我的代码在下面,现在我是pygame的新手,并试图弄清楚如何在屏幕上移动图像。 From what I've seen of pygame the following code should move the image up(the only possible movement right now). 根据我对pygame的了解,以下代码应将图像向上移动(目前唯一可能的移动)。 However when I push up the image doesn't move. 但是,当我向上推时,图像不会移动。 Python is recognizing that I'm pushing up because it prints in the system tray, however there is just no movement, can someone help? Python意识到我正在推高它,因为它在系统托盘中打印,但是没有任何移动,有人可以帮忙吗?

import pygame, sys
from pygame.locals import *

FPS = 30


WIN_WIDTH = 800
WIN_HEIGHT = 600
HALF_WIDTH = int(WIN_WIDTH / 2)
HALF_HEIGHT = int(WIN_HEIGHT / 2)

COLOR = (255, 0, 255)
IMAGE = pygame.image.load('squirrel.png')
STARTSIZE = 25

LEFT = 'left'

def main():
    pygame.init()
    FPS_CLOCK = pygame.time.Clock()
    movement = 1

    moveUp = False

    DISPLAY_SURFACE = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))

    while True:
        DISPLAY_SURFACE.fill(COLOR)

        playerObj = {'surface': pygame.transform.scale(IMAGE, (STARTSIZE, STARTSIZE)),
                     'facing': LEFT,
                     'size': STARTSIZE,
                     'x': HALF_WIDTH,
                     'y': HALF_HEIGHT}

        playerObj['rect'] = pygame.Rect( (playerObj['x'], playerObj['y'], playerObj['size'], playerObj['size']) )
        DISPLAY_SURFACE.blit(playerObj['surface'], playerObj['rect'])


        for event in pygame.event.get():

            if event.type == KEYDOWN:
                if event.key == K_UP:
                    moveUp = True

            if event.type == KEYUP:
                if event.key == K_UP:
                    moveUp = False

            elif event.type == QUIT:
                pygame.quit()
                sys.exit()

        if moveUp:
            playerObj['y'] += movement
            print("moving up")

        else:
            print('stopped')

        pygame.display.update()
        FPS_CLOCK.tick(FPS)

if __name__ == '__main__':
    main()

You're creating a new playerObj each time it iterates through the while loop so you're not going to see it move (as it is setting it's 'y' value to HALF_HEIGHT each time). 每次迭代while循环时,您都在创建一个新的playerObj,因此不会看到它移动(因为它每次都将其“ y”值设置为HALF_HEIGHT)。 Move the playerObj definition out of the while loop. 将playerObj定义移出while循环。

You must create the playerObj before you enter the while-loop, and then only draw it to the DISPLAY_SURFACE each time. 在进入while循环之前,必须先创建playerObj,然后每次仅将其绘制到DISPLAY_SURFACE Also, increasing the key y of your dictionary won't help, you must modify the rect instead. 同样,增加字典的键y也无济于事,而必须修改rect A minimally invasive solution would be: 一种微创的解决方案是:

import pygame, sys
from pygame.locals import *

FPS = 30


WIN_WIDTH = 800
WIN_HEIGHT = 600
HALF_WIDTH = int(WIN_WIDTH / 2)
HALF_HEIGHT = int(WIN_HEIGHT / 2)

COLOR = (255, 0, 255)
IMAGE = pygame.image.load('squirrel.png')
STARTSIZE = 25

LEFT = 'left'

def main():
    pygame.init()
    FPS_CLOCK = pygame.time.Clock()
    movement = 1

    moveUp = False

    DISPLAY_SURFACE = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))

    playerObj = {'surface': pygame.transform.scale(IMAGE, (STARTSIZE, STARTSIZE)),
                     'facing': LEFT,
                     'size': STARTSIZE,
                     'x': HALF_WIDTH,
                     'y': HALF_HEIGHT}

    playerObj['rect'] = pygame.Rect( (playerObj['x'], playerObj['y'], playerObj['size'], playerObj['size']) )

    while True:
        DISPLAY_SURFACE.fill(COLOR)
        DISPLAY_SURFACE.blit(playerObj['surface'], playerObj['rect'])
        for event in pygame.event.get():

            if event.type == KEYDOWN:
                if event.key == K_UP:
                    moveUp = True

            if event.type == KEYUP:
                if event.key == K_UP:
                    moveUp = False

            elif event.type == QUIT:
                pygame.quit()
                sys.exit()

        if moveUp:
            playerObj['rect'].y -= movement
            print("moving up")

        else:
            print('stopped')

        pygame.display.update()
        FPS_CLOCK.tick(FPS)

if __name__ == '__main__':
    main()

It works, I tried it myself. 它有效,我自己尝试过。 But you sould refactor your code, no need to carry along the initial x,y, etc. values in your dictionary. 但是您可以重构代码,而无需携带字典中的初始x,y等值。

EDIT With movement in all four directions this would be: 编辑在所有四个方向上移动将是:

import pygame, sys
from pygame.locals import *

FPS = 30


WIN_WIDTH = 800
WIN_HEIGHT = 600
HALF_WIDTH = int(WIN_WIDTH / 2)
HALF_HEIGHT = int(WIN_HEIGHT / 2)

COLOR = (255, 0, 255)
IMAGE = pygame.image.load('squirrel.png')
STARTSIZE = 25

LEFT = 'left'

def move_rect(rect, key, distance):
    if key == K_UP: 
        rect.y-=distance
    elif key == K_DOWN: 
        rect.y+=distance
    elif key == K_LEFT: 
        rect.x-=distance
    elif key == K_RIGHT: 
        rect.x+=distance

def main():
    pygame.init()
    FPS_CLOCK = pygame.time.Clock()
    movement = 1

    key2mvmt = {K_UP:False, K_DOWN:False, K_LEFT:False, K_RIGHT:False}

    DISPLAY_SURFACE = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))

    playerObj = {'surface': pygame.transform.scale(IMAGE, (STARTSIZE, STARTSIZE)),
                     'facing': LEFT,
                     'size': STARTSIZE,
                     'x': HALF_WIDTH,
                     'y': HALF_HEIGHT}

    playerObj['rect'] = pygame.Rect( (playerObj['x'], playerObj['y'], playerObj['size'], playerObj['size']) )

    while True:
        DISPLAY_SURFACE.fill(COLOR)
        DISPLAY_SURFACE.blit(playerObj['surface'], playerObj['rect'])
        for event in pygame.event.get():

            if event.type == KEYDOWN:
                if key2mvmt.has_key(event.key):
                    key2mvmt[event.key]= True

            if event.type == KEYUP:
                if key2mvmt.has_key(event.key):
                    key2mvmt[event.key]= False

            elif event.type == QUIT:
                pygame.quit()
                sys.exit()

        for k in key2mvmt.keys():
            if key2mvmt[k]:
                move_rect(playerObj['rect'], k, movement)

        else:
            print('stopped')

        pygame.display.update()
        FPS_CLOCK.tick(FPS)

if __name__ == '__main__':
    main()

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

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