如何使用Pythons PyGame的键盘来移动精灵?

2024-04-24 14:39:02 发布

您现在位置:Python中文网/ 问答频道 /正文

为了学习pygame和livewires,我正在重新制作一个电子游戏。我使用livewires是因为它似乎是一个很好的方式来加载一个精灵的背景图形。在

我试图让一个预加载的精灵水平移动,同时保持在正确的位置移动(在这个例子中它是50像素以上)。在

我可以使用pygame来移动精灵,或者我可以让精灵在正确的位置加载背景,或者我可以让精灵移动,但两者似乎不会同时发生。在

为了增加额外的奖励,我还需要屏幕滚动时,字符移动到不同的位置。在

这是我的代码:

import pygame, sys
from livewires import games
from pygame.locals import *

games.init(screen_width = 640, screen_height = 480, fps = 50) #setup up the window siz

class Mario(games.Sprite):

    def update(self, pressed_keys):
        move = 50 #Setup the origianl position of the character
        if pressed_keys[K_RIGHT]: move += 1 #press right key to move forward
        if pressed_keys[K_LEFT]: move -= 1 #press left key to move back     

    def main():
        pygame.init()
        screen_image = games.load_image("World 1-1.bmp", transparent = False) #setup the background image
        games.screen.background = screen_image
        mario_image = games.load_image("Mario3.bmp")
        mario = games.Sprite(image = mario_image, x = move, y=370) #setup the position of the character
        sprites.add(mario)
        pygame.display.update()

        while True:
            for event in pygame.event.get():
                if event.type == QUIT: return pygame.quit() #if the player quits

            keys_pressed = pygame.key.get_pressed()

    games.screen.mainloop()

    main()

Tags: thekeyimageimportmoveifsetupkeys
1条回答
网友
1楼 · 发布于 2024-04-24 14:39:02

对我来说,如果你只使用Pygame或Livewires,这看起来要简单得多。不要试图强迫两个模块一起工作,如果他们不是故意的。此外,Livewires的介绍页面说,该模块是Python课程的一个附加组件,而不是一个独立的游戏模块。我建议您只使用Pygame,因为它是一个独立的游戏模块。在

另外,上面的代码看起来有点草率(请不要把它当作是个人的),下面我将向您展示如何制作一个入门Pygame文件。在

Pygame文件的主要部分是游戏循环。 典型的Pygame游戏循环(或任何真正的游戏循环)有三个基本部分:

  1. 事件检查器,用于检查任何事件
  2. 事件执行器,当相应的事件发生时执行某些操作。在
  3. 渲染图形的地方。在

为了给Pygame游戏提供一个好的启动文件的一般概念,下面是一个示例:

import pygame #import the pygame moudle into the namespace <module>

WIDTH = 640 # define a constant width for our window
HEIGHT = 480 # define a constant height for our window

display = pygame.display.set_mode((WIDTH, HEIGHT)) #create a pygame window, and
#initialize it with our WIDTH and HEIGHT constants

running = True # our variable for controlling our game loop

while running:
    for e in pygame.event.get(): # iterate ofver all the events pygame is tracking
        if e.type == pygame.QUIT: # is the user trying to close the window?
            running = False # if so break the loop
            pygame.quit() # quit the pygame module
            quit() # quit is for IDLE friendliness

    display.fill((255, 255, 255)) # fill the pygame screen with white
    pygame.display.flip() # update the screen

以上是制作Pygame游戏的一个很好的起点。在

但回到手头的问题上:

假设你只使用Pygame,有几种方法可以让精灵/形状在Pygame中移动。在

方法1:使用sprite类

为了让你的马里奥精灵移动,你可以使用一个类似下面的精灵类。在

^{pr2}$

因为您的类继承自Pygame的sprite类,所以您必须命名您的图像自我形象你必须为图像命名矩形自校正. 您还可以看到,该类有两个主要方法。一个用于创建精灵(init),另一个用于更新精灵(update)

若要使用类,请创建一个Pygame精灵组来保存所有精灵,然后将玩家对象添加到该组中:

sprites = pygame.sprite.Group()
player = Player()
sprtites.add(player)

以及实际渲染你的精灵到屏幕调用精灵.update()和精灵.绘制()在游戏循环中,更新屏幕:

sprites.update()
window_name.fill((200, 200, 200))
sprites.draw(window_name)
pygame.display.flip()

我强烈推荐使用sprite类的原因是,它会使代码看起来更干净,并且更易于维护。你甚至可以将每个sprite类移动到它们各自独立的文件中。在

但是,在深入研究上面的方法之前,您应该先阅读一下pygame.Rect对象和{a2}对象,因为您将要使用它们。在

方法2:使用函数

如果你不想进入精灵类,你可以使用类似下面的函数来创建你的游戏实体。在

def create_car(surface, x, y, w, h, color):
    rect = pygame.Rect(x, y, w, h)
    pygame.draw.rect(surface, color, rect)
    return rect

如果您仍然想使用精灵,但不想创建类,只需稍微修改上面的函数:

def create_car(surface, x, y, color, path_to_img):
    img = pygame.image.load(path_to_img)
    rect = img.get_rect()
    surface.blit(img, (x, y))

下面是一个如何使用上述函数制作可移动矩形/精灵的示例:

import pygame

WIDTH = 640
HEIGHT = 480
display = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Moving Player Test")
clock = pygame.time.Clock()
FPS = 60

def create_car(surface, x, y, w, h, color):
    rect = pygame.Rect(x, y, w, h)
    pygame.draw.rect(surface, color, rect)
    return rect

running = True
vx = 0
vy = 0
player_x = WIDTH / 2 # middle of screen width
player_y = HEIGHT / 2 # middle of screen height
player_speed = 5
while running:
    clock.tick(FPS)
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            running = False
            pygame.quit()
            quit()
        if e.type == pygame.KEYDOWN:
            if e.key == pygame.K_LEFT:
                vx = -player_speed
            elif e.key == pygame.K_RIGHT:
                vx = player_speed
            if e.key == pygame.K_UP:
                vy = -player_speed
            elif e.key == pygame.K_DOWN:
                vy = player_speed
        if e.type == pygame.KEYUP:
            if e.key == pygame.K_LEFT or e.key == pygame.K_RIGHT or\
               e.key == pygame.K_UP or e.key == pygame.K_DOWN:
                vx = 0
                vy = 0

    player_x += vx
    player_y += vy
    display.fill((200, 200, 200))
    ####make the player#####
    player = create_car(display, player_x, player_y, 10, 10, (255, 0, 0))
    pygame.display.flip()

我应该注意到,我对上面列出的每种方法都做了一些假设。在

你可以使用一个圆形,正方形,或者一些pygame形状的对象。 或者你用的是雪碧。 如果您目前没有使用上述任何方法,我建议您使用。一旦开始构建更大、更复杂的游戏,这样做将使代码更易于维护。在

相关问题 更多 >