python - 创建一个组以在 Pygame 中添加我的类

标签 python class pygame sprite

我目前正在 Pygame 中制作游戏,并且希望在我的屏幕上随机生成多个平台。但是,我似乎不知道如何创建一个组以便我可以一次绘制多个 Sprite 。我尝试过使用 super.__init__(self) 并将 self 替换为 (*Group) ,但它不起作用。我也刚刚尝试将其添加到组中。我应该如何创建我的组以及如何正确地将我的 Sprite 添加到其中? 这是代码(我要添加的 Sprite 是在此处创建的,但未绘制):

######## basic setup
import pygame, sys, time, random, threading, tkinter, ctypes
from threading import Timer
from pygame.locals import *
from tkinter import *
pygame.init()
WINDOWHEIGHT = 720
WINDOWWIDTH = 1280
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Hitman Grandma | vB1.0 (prealpha)')
white = (255,255,255)
red = (255,0,0)
black = (0,0,0)
green = (0,255,0)
blue = (0,0,255)
cyan = (0,255,255)
lightgrey = (198,198,198)
windowSurface.fill(lightgrey)
pygame.display.update()
mainClock = pygame.time.Clock()
########## variables
level = 0
touching = False
global x_speed
x_speed = 0
y_speed = 0
leftallowed = True
rightallowed = True
hgturnright = True
hgjumpallowed = True
########### the grandma d'awesome murder sorts
hgimage = pygame.image.load('hgfinal.png')
hgimage.convert_alpha()
class HG(object):
    def __init__(self,x,y,image):
        self.image = image
        self.rect = self.image.get_rect()
        self.x = x
        self.y = y       
    def draw(self):
        windowSurface.blit(self.image,(self.x,self.y))
    def move(self):
        self.x += x_speed
        self.y += y_speed
    def topcollide(self,box):
        if not self.rect.colliderect(box.rect):
            global y_speed
            if y_speed < 20:
                y_speed += 1
            elif y_speed == 20:
                y_speed = 20
            print('shhoooo')
        elif self.rect.colliderect(box.rect):
            y_speed = 0
            print('flop')
hg = HG(0,0,hgimage)
########### land and boundary
lands = pygame.image.load('hgland1.png')
floorland = pygame.transform.scale(lands,(1280,50))
sideedge = pygame.Rect(0,0,1,720),pygame.Rect(1279,0,1,720)
topedge = pygame.Rect(0,0,1280,1)
class Floor(object):
    def __init__(self,x,y,image):
        self.image = image
        self.x = x
        self.y = y
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
    def draw(self):
        windowSurface.blit(self.image,(self.x,self.y))
class Ground(object):
    def __init__(self,x,y,image):
        self.image = image
        self.x = x
        self.y = y
        self.rect = self.image.get_rect()
    def draw(self):
        windowSurface.blit(self.image,(self.x,self.y))
class Ground(object):
    def __init__(self,x,y,image):
        super.__init__(self)
        self.image = image
        self.x = x
        self.y = y
        self.rect = self.image.get_rect(topleft = (x,y))
    def draw(self):
        windowSurface.blit(self.image,(self.x,self.y))
floor = Floor(0,670,floorland)
platform1 = Ground((random.randint(0,800)),(random.randint(50,620)),lands)
########### WHILE
while True:
########### background
    windowSurface.fill(lightgrey)
########### hg movement
    for event in pygame.event.get():
        if event.type == KEYDOWN:
                if event.key == K_LEFT and hg.x > 0 and leftallowed:
                    x_speed = -4
                    hgturnright = False
                if event.key == K_RIGHT and (hg.x + 36) < WINDOWWIDTH and rightallowed:
                    x_speed = 4
                    hgturnright = True
                if event.key == K_UP and hgjumpallowed:
                    y_speed = -17
        if event.type == KEYUP:
            if event.key == K_RIGHT:
                x_speed = 0
            if event.key == K_LEFT:
                x_speed = 0
        if event.type == KEYDOWN:
########### ctrl+q
            if event.key == K_q and pygame.key.get_mods() & pygame.KMOD_CTRL:
                pygame.quit()
                sys.exit()
                exit
########### [x]
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
                exit
########### drawing and .move()
    floor.draw()
    hg.draw()
    hg.move()
    hg.topcollide(floor)
########### technicals
    pygame.display.update()
    mainClock.tick(40)

这是我想要使用的类:

class Ground(object):
    def __init__(self,x,y,image):
        super.__init__(self)
        self.image = image
        self.x = x
        self.y = y
        self.rect = self.image.get_rect(topleft = (x,y))
    def draw(self):
        windowSurface.blit(self.image,(self.x,self.y))
platform1 = Ground((random.randint(0,800)),(random.randint(50,620)),lands)

另外,这里有两个要使用的图像:this is the grandmother here is the land

最佳答案

你的类应该继承自 pygame.sprite.Sprite ,以便可以将它们放入 Sprite 组中,例如类平台(pg.sprite.Sprite):。不要忘记调用父类super().__init__()__init__方法。然后创建 Sprite 组 (all_sprites = pg.sprite.Group()) 和 Sprite 实例,并调用组的 add 方法来添加 Sprite 。

然后您只需在主循环中调用 all_sprites.update()all_sprites.draw(screen) 即可。

from random import randrange

import pygame as pg


class Platform(pg.sprite.Sprite):

    def __init__(self, x, y, width, height):
        super().__init__()
        self.image = pg.Surface((width, height))
        self.image.fill(pg.Color('dodgerblue1'))
        self.rect = self.image.get_rect(topleft=(x, y))


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group()  # This group that will contain all sprites.
    # You probably want to add the platforms to a separate
    # group as well, so that you can use it for collision detection.
    platforms = pg.sprite.Group()

    for _ in range(6):  # Create six platforms at random coords.
        platform = Platform(randrange(600), randrange(440), 170, 20)
        platforms.add(platform)
        all_sprites.add(platform)

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        all_sprites.update()

        screen.fill((30, 30, 30))
        all_sprites.draw(screen)

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()

关于python - 创建一个组以在 Pygame 中添加我的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47603286/

相关文章:

c++ - 包含另一个类的对象的类的大小

python - 将 PyGame 黑白显示转换为 7x5 位矩阵

python - pygame.draw.rect() 不绘制另一个矩形

swift - 仍然可以从外部访问私有(private)值

java - 按名称获取类(class)

python - 如何在pygame中获取键盘输入?

python - 计算余弦相似度矩阵,无需 scipy、sklearn.metrics.pairwise

python - 真的可以用 python 发布文件吗?

python - 使用 python 将输入发送到使用子进程打开的程序?

python - 获取列表中的 XML 元素