如何在Pygame中移动Sprite

问题描述 投票:0回答:3

我试图让我的图像(鸟)在屏幕上上下移动,但我不知道该怎么做,这就是我尝试过的,我确定它已经消失了,但我试图弄清楚是否有人可以提供帮助太棒了!

import pygame
import os

screen = pygame.display.set_mode((640, 400))

running = 1

while running:
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        running = 0
    screen.fill([255, 255, 255])
    clock = pygame.time.Clock()
    clock.tick(0.5)
    pygame.display.flip()

    bird = pygame.image.load(os.path.join('C:\Python27', 'player.png'))
    screen.blit( bird, ( 0, 0 ) )

    pygame.display.update()

class game(object):
    def move(self, x, y):
        self.player.center[0] += x
        self.player.center[1] += y


    if event.key == K_UP:
        player.move(0,5)
    if event.key == K_DOWN:
        player.move(0,-5)

game()

我试图让它在按下向下按钮时向下移动,在按下向上键时向上移动

python pygame sprite
3个回答
20
投票

正如 ecline6 所说,此时鸟是你最不用担心的。

考虑阅读这本书..

现在,首先让我们清理您的代码...

import pygame
import os

# let's address the class a little later..

pygame.init()
screen = pygame.display.set_mode((640, 400))
# you only need to call the following once,so pull them out of the  while loop.
bird = pygame.image.load(os.path.join('C:\Python27', 'player.png'))
clock = pygame.time.Clock()

running = True
while running:
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        running = False

    screen.fill((255, 255, 255)) # fill the screen
    screen.blit(bird, (0, 0))    # then blit the bird

    pygame.display.update() # Just do one thing, update/flip.

    clock.tick(40) # This call will regulate your FPS (to be 40 or less)

现在你的“鸟”不动的原因是:
当你blit图像时,即:

screen.blit(bird, (0, 0))

(0,0)
是恒定的,因此不会移动。

这是最终的代码,其中包含您想要的输出(尝试一下)并阅读注释:

import pygame
import os

# it is better to have an extra variable, than an extremely long line.
img_path = os.path.join('C:\Python27', 'player.png')

class Bird(object):  # represents the bird, not the game
    def __init__(self):
        """ The constructor of the class """
        self.image = pygame.image.load(img_path)
        # the bird's position
        self.x = 0
        self.y = 0

    def handle_keys(self):
        """ Handles Keys """
        key = pygame.key.get_pressed()
        dist = 1 # distance moved in 1 frame, try changing it to 5
        if key[pygame.K_DOWN]: # down key
            self.y += dist # move down
        elif key[pygame.K_UP]: # up key
            self.y -= dist # move up
        if key[pygame.K_RIGHT]: # right key
            self.x += dist # move right
        elif key[pygame.K_LEFT]: # left key
            self.x -= dist # move left

    def draw(self, surface):
        """ Draw on surface """
        # blit yourself at your current position
        surface.blit(self.image, (self.x, self.y))


pygame.init()
screen = pygame.display.set_mode((640, 400))

bird = Bird() # create an instance
clock = pygame.time.Clock()

running = True
while running:
    # handle every event since the last frame.
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit() # quit the screen
            running = False

    bird.handle_keys() # handle the keys

    screen.fill((255,255,255)) # fill the screen with white
    bird.draw(screen) # draw the bird to the screen
    pygame.display.update() # update the screen

    clock.tick(40)

0
投票

键盘事件(参见 pygame.event 模块)仅在按键状态更改时发生一次。每次按下某个键时,都会发生一次

KEYDOWN
事件。每次释放按键时都会出现一次
KEYUP
。使用键盘事件进行单个操作或逐步移动。

如果你想实现连续运动,就必须使用

pygame.key.get_pressed()
pygame.key.get_pressed()
返回包含每个键状态的列表。如果按住某个键,则该键的状态为
True
,否则为
False
。使用
pygame.key.get_pressed()
评估按钮的当前状态并获得连续移动。

另请参阅按键和键盘事件按住按键时如何使精灵移动


最小示例:

import pygame
import os

class Bird(object):
    def __init__(self):
        self.image = pygame.image.load(os.path.join('C:\Python27', 'player.png'))
        self.center = [100, 200]

    def move(self, x, y):
        self.center[0] += x
        self.center[1] += y

    def draw(self, surf):
        surf.blit(self.image, self.center)

class game(object):
    
    def __init__(self):
        self.screen = pygame.display.set_mode((640, 400))
        self.clock = pygame.time.Clock()
        self.player = Bird()

    def run(self):
        running = 1
        while running:
            self.clock.tick(60)
            event = pygame.event.poll()
            if event.type == pygame.QUIT:
                running = 0
            
            keys = pygame.key.get_pressed()
            move_x = keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]
            move_y = keys[pygame.K_DOWN] - keys[pygame.K_UP]
            self.player.move(move_x * 5, move_y * 5)

            self.screen.fill([255, 255, 255])
            self.player.draw(self.screen)
            pygame.display.update()

g = game()
g.run()

0
投票

正如之前所说,你真的应该做这三件事:

  1. 使用
    pygame.init
  2. 初始化 pygame
  3. 将你的精灵类置于游戏循环之外 - 当该类处于游戏循环中时,你的精灵会无限刷新,因此即使你的键盘代码确实有效,仍然会有太多的精灵调用导致游戏无法正常运行。
  4. 利用适当的精灵类,如下所示:
class.Bird(pygame.sprite.Sprite):
  def__init_(self, x, y): # pos_x and pos_y also work fine here
    super().__init__()
    self.image = pygame.image.load('bird.png') # This must be the file name of the image you are using.
    self.rect = self.image.get_rect()
    self.rect.topleft = (x, y)

birdbody = Turtle(275, 650)

bird_group = pygame.sprite.Group()
bird_group.add(turtlebody)
  
# NOW THE GAME LOOP WILL BE IN HERE

bird_group.draw(screen)

# END OF GAME LOOP
© www.soinside.com 2019 - 2024. All rights reserved.