Pygame-窗口和精灵类 - python

时间:2013-11-12 17:51:05

标签: python pygame

我正在尝试构建一个类似于sprite生活的类的窗口类。在窗口类中,我希望有以下内容:

  • set_background()
  • set_size()
  • add_sprite()
  • remove_sprite()

在sprite类中,我想要以下方法:

  • draw_sprite()

现在我将有一个精灵,但我最终想要一个精灵列表。

我已经尝试通过在其实例上调用这些方法来运行我在主类中拥有的东西。

window = Window(200,200)
sprite = Sprite(Window)

window.set_Background()
sprite.draw_sprite()

继承我的代码:

精灵课程:

import pygame

pygame.init()

class Sprite(object):
    def __init__(self, World =None, sprite=[]):
        self.Window = window

    def draw_sprite(self,sprite,x,y):
        sprite=pygame.image.load(sprite)
        self.World.window.blit(sprite,(x,y))
        pygame.display.update()

        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()

窗口类:

import pygame,sys,os from pygame.locals import *

from Window import *

class Panel:
  def __init__(self, width=None,height=None):
      self.width= width
      self.height = height
      self.foreground=pygame.Surface((width, height))
      self.background= pygame.Surface((width, height))
      self.rect= self.foreground.get_rect()

  def clear(self):
      self.foreground.blit(self.background,(0,0))

  def set_background(self, image=None):
      if sky is not None:
          bg = Window.draw_world(self,image)
          self.background.blit(bg,(width,height))

class Window(Panel):
  pygame.init()
  def __init__(self,width,height):
      self.window = pygame.display.set_mode((width,height))
      self.width=width
      self.height=height
      Panel.__init__(self, width, height)
      self._foreground = self.window
      self.set_background()

  def draw_world(self,image):
      image=pygame.image.load(image)
      for x in range(0,(290/image.get_width()+1)):
          for y in range(0,(230/image.get_height()+1)):
              self.background.blit(image,(x*200,y*200))
              pygame.display.update()

      while True:
          for event in pygame.event.get():
              if event.type == pygame.QUIT:
                  pygame.quit()


  def window_setSize(width,height):
      self.width=width
      self.heght =height

主要课程:

from Sprite import * 
from window import *

sprite = Sprite() 

window=Window()
sprite.draw_sprite("sprite.png",100,200)
window.set_background("bg.png")

有没有人知道为什么精灵会显示但我的背景不是?它只显示黑色背景。

我正在使用python 3和pygame 3.3 感谢

1 个答案:

答案 0 :(得分:4)

您在draw_sprite()中有事件循环,因此它一直运行到游戏结束,window.set_background永远不会被执行。

您的代码构造不正确。

我尝试纠正它并稍后发送代码。


顺便说一下:见:pygame.sprite.Sprite


修改

如何组织代码的简单示例。

现在它在一个文件中。 Pygame总是一个Window,所以不需要制作Panel + Widnow。您在run()中有一个事件循环。所有代码都在Window中(创建Sprite,更改背景,绘图等)。

我将精灵添加到(python)列表并从列表中绘制所有精灵 - 玩家异常 - 所以我只能从列表中删除最后一个精灵:/如果你需要更好的东西,请参阅pygame.sprite.Sprite()pygame.sprite.Group()

使用Arrows移动红球,Space暂停游戏,ESC退出。

最后我附上了我的位图。

import pygame

#from pygame.locals import *

#--------------------------------------------------------------------
# class for single sprite
#--------------------------------------------------------------------

class MySprite():

    def __init__(self, image, x, y):

        self.image = pygame.image.load(image)
        image_rect = self.image.get_rect()

        # Rect class to use "Sprite collision detect" - in the future
        # In rect you have sprite position and size 
        # You can use self.rect.x, self.rect.y, self.rect.width, self.rect.height
        # and self.rect.center, self.rect.centerx, self.rect.top, self.rect.bottomright etc.

        self.rect = pygame.rect.Rect(x, y, image_rect.width, image_rect.height)

    def draw(self, screen):
        screen.blit(self.image, self.rect)


#--------------------------------------------------------------------
# class for player
#--------------------------------------------------------------------

class MyPlayer(MySprite):

    def __init__(self, image, x, y):
        # parent constructor always as a first in __init__
        MySprite.__init__(self, image, x, y)

        self.speed_x = self.speed_y = 0

    #-----------------------------

    def set_speed(self, x, y):
        self.speed_x = x
        self.speed_y = y

    #-----------------------------

    def update(self):
        self.rect.x += self.speed_x
        self.rect.y += self.speed_y

        if self.rect.centerx < 0 :
            self.rect.centerx = 800
        elif self.rect.centerx > 800 :
            self.rect.centerx = 0

        if self.rect.centery < 0 :
            self.rect.centery = 600
        elif self.rect.centery > 600 :
            self.rect.centery = 0

#--------------------------------------------------------------------

class Window():

    def __init__(self, width, height):

        #--------------------
        self.rect = pygame.Rect(0, 0, width, height)
        # or
        self.width, self.height = width, height
        #--------------------

        pygame.init()

        # most users and tutorials call it "screen"
        self.screen = pygame.display.set_mode(self.rect.size)

        #############################################################

        self.foreground = None
        self.background = None

        self.set_background("background.jpg")                          
        self.set_foreground("ball3.png")                          

        #################################################

        self.player = MyPlayer("ball1.png", 100, 200)

        self.sprites_list = []

        self.add_sprite(MySprite("ball2.png", 100, 400))
        self.add_sprite(MySprite("ball2.png", 300, 500))
        self.add_sprite(MySprite("ball2.png", 300, 200))

        self.remove_last_sprite()

        #-----------------------------

        # red text "PAUSE"
        font = pygame.font.SysFont("", 72)
        self.text_pause = font.render("PAUSE", True, (255, 0, 0))

        # center text on screen
        screen_center = self.screen.get_rect().center
        self.text_pause_rect = self.text_pause.get_rect(center=screen_center) 

    #--------------------------

    def add_sprite(self, sprite):
        self.sprites_list.append(sprite)

    #--------------------------

    def remove_last_sprite(self):
        if self.sprites_list:
            del self.sprites_list[-1]

    #--------------------------

    def draw_sprites(self, screen):
        for sprite in self.sprites_list:
            sprite.draw(screen)

    #--------------------------

    def draw_background(self, screen):
        screen.fill((0,64,0)) # clear screen to green
        if self.background:
            screen.blit(self.background, (0,0))

    #--------------------------

    def draw_foreground(self, screen):
        if self.foreground:
            screen.blit(self.foreground, (0,0))

    #--------------------------

    def draw_world(self, image):
        temp = pygame.Surface(self.rect.size, pygame.SRCALPHA, 32).convert_alpha()
        image_rect = image.get_rect()

        for x in range(0, self.rect.width, 60):
            for y in range(0,self.rect.width, 60):
                temp.blit(image,(x,y))

        return temp

    #--------------------------

    def set_foreground(self, image=None):
        if image: 
            img = pygame.image.load(image)
            self.foreground = self.draw_world(img)

    #--------------------------

    def set_background(self, image=None):
        if image: 
            self.background = pygame.image.load(image)

    #--------------------------

    def run(self):

        clock = pygame.time.Clock()

        RUNNING = True
        PAUSED = False

        while RUNNING:

            #--- events ---

            for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    RUNNING = False

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        RUNNING = False
                    elif event.key == pygame.K_SPACE:
                        PAUSED = not PAUSED

                    if event.key == pygame.K_UP:
                        self.player.set_speed(0,-10)
                    elif event.key == pygame.K_DOWN:
                        self.player.set_speed(0,10)
                    elif event.key == pygame.K_LEFT:
                        self.player.set_speed(-10,0)
                    elif event.key == pygame.K_RIGHT:
                        self.player.set_speed(10,0)

                if event.type == pygame.KEYUP:
                    if event.key in (pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT):
                        self.player.set_speed(0,0)

            #--- changes ----

            if not PAUSED:
                # change elements position
                self.player.update()

            #--- draws ---

            self.draw_background(self.screen)
            self.draw_foreground(self.screen)
            self.draw_sprites(self.screen) 
            self.player.draw(self.screen)

            if PAUSED:
                # draw pause string
                self.screen.blit(self.text_pause, self.text_pause_rect.topleft)

            pygame.display.update()

            #--- FPS ---

            clock.tick(25) # 25 Frames Per Seconds

        #--- finish ---

        pygame.quit()

#----------------------------------------------------------------------

Window(800,600).run()

ball1.png enter image description here ball2.png enter image description here ball3.png enter image description here

background.jpg enter image description here

截图 enter image description here