0

我正在开发 pygame 的平台游戏,以学习引擎。

我让它创建了块的多个实例,并且我有一个可以以越来越快的速度下降的播放器对象。我怎样才能使它在玩家击中障碍物时不会掉下来?这是我的代码:

#imports
import pygame, sys
from pygame.locals import *

#init game
pygame.init()
screen = pygame.display.set_mode((640,480))
pygame.key.set_repeat(True) 
clock = pygame.time.Clock()

#classes
class playerClass:
    x = 100
    y = 100
    boundingBox_x = 32
    boundingBox_y = 32
    sprite = pygame.image.load("Image2.png").convert_alpha()

class Block(object):

    sprite = None

    def __init__(self, x, y):
        if not Block.sprite:
            Block.sprite = pygame.image.load("Image1.png").convert_alpha()
        self.rect = Block.sprite.get_rect(top=y, left=x)

#objects
playerObject = playerClass()
blocks = []
blocks.append(Block(0, 14*32))
blocks.append(Block(1*32, 14*32))
blocks.append(Block(2*32, 14*32))
blocks.append(Block(3*32, 14*32))
blocks.append(Block(4*32, 14*32))
blocks.append(Block(5*32, 14*32))
blocks.append(Block(6*32, 14*32))
blocks.append(Block(7*32, 14*32))
blocks.append(Block(8*32, 14*32))
blocks.append(Block(9*32, 14*32))
blocks.append(Block(10*32, 14*32))
blocks.append(Block(11*32, 14*32))
blocks.append(Block(12*32, 14*32))
blocks.append(Block(13*32, 14*32))
blocks.append(Block(14*32, 14*32))
blocks.append(Block(15*32, 14*32))
blocks.append(Block(16*32, 14*32))
blocks.append(Block(17*32, 14*32))
blocks.append(Block(18*32, 14*32))
blocks.append(Block(19*32, 14*32))

blocks.append(Block(0, 13*32))
blocks.append(Block(19*32, 13*32))
blocks.append(Block(0, 13*32))
blocks.append(Block(19*32, 13*32))
blocks.append(Block(0, 12*32))
blocks.append(Block(19*32, 12*32))
blocks.append(Block(0, 11*32))
blocks.append(Block(19*32, 11*32))
#colors
white = 255,255,255

#variables
up = False
down = False
right = False
left = False

xspeed = 0
yspeed = 0
gspeed = 0.2
#functions

#main loop
quitting = False
while quitting == False:
    for event in pygame.event.get():

#event processing
        if event.type == pygame.QUIT:
            quitting = True

#game logic
    yspeed += gspeed
    playerObject.y += yspeed
#drawing
    screen.fill((white))

    screen.blit(playerObject.sprite,(playerObject.x,playerObject.y))
    for block in blocks:
        screen.blit(block.sprite, block.rect)

    pygame.display.flip()

#ending
    clock.tick(60)

另外,我知道我正在使用大量代码来构建关卡。我正在开发一个从 txt 文件中读取级别的系统。感谢

4

1 回答 1

1

做到这一点的简单方法是使用pygame.sprite专门为这类事情设计的模块。

该页面上的示例显示了您想要做的大部分事情;pygame 附带的Shooter示例显示了所有细节。

但简而言之:MakeBlockPlayer的两个子类sprite.Sprite,将所有Blocks 放入一个 sprite 组,而不仅仅是一个列表,然后使用spritecollideany(player, block_group),这就是它的全部内容。


如果你想手动完成,它并没有那么难。您需要以与每个块相同的方式跟踪播放器的边界矩形,然后改为:

spritecollideany(player, block_group)

… 你来做这件事:

player.rect.collidelist([block.rect for block in blocks]) != -1

一般来说,一切都sprite可以,你可以自己做——只需大约两倍的代码。当然,你必须弄清楚你需要做的所有事情——使用sprite精灵和组的简单 API 几乎可以告诉你在大多数游戏中你要用它们做的所有事情。

于 2013-07-12T22:48:32.450 回答