如何在pygame中制作突破墙?

时间:2016-11-23 23:15:27

标签: python pygame

import pygame

from pygame.locals import *

import os

import sys

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

ancho = 768

largo = 480

direccion = "imagenes"

vidas = 3

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

def cargar_img(nombre, direccion, alpha=False):

    ruta = os.path.join(direccion, nombre)
    try:
        image = pygame.image.load(ruta)
    except:
        print("Error al cargar la Imagen, compruebe la ruta")
        sys.exit(1)

    if alpha is True:
        image = image.convert_alpha()
    else:
        image = image.convert()
    return image  

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

class Pelota(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = cargar_img("bola.png", direccion, alpha=True)
        self.rect = self.image.get_rect()
        self.rect.centerx = ancho/2
        self.rect.centery = largo/2
        self.speed = [6,6]

    def  refrescar(self):
        if self.rect.left < 0 or self.rect.right > ancho:
            self.speed[0] = -self.speed[0]
        if self.rect.top < 0 :
            self.speed[1] = -self.speed[1]
        if self.rect.bottom > largo :
            self.rect.centerx = ancho/2
            self.rect.centery = largo/2
            global vidas
            vidas = vidas -1

        self.rect.move_ip((self.speed[0], self.speed[1]))


    def colision(self, objeto):
        if self.rect.colliderect(objeto.rect):
            self.speed[1] = -self.speed[1]


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

class Barra(pygame.sprite.Sprite):

    def __init__(self, y):
        pygame.sprite.Sprite.__init__(self)
        self.image = cargar_img("paleta.png", direccion, alpha = True)
        self.rect = self.image.get_rect()
        self.rect.centerx = 384
        self.rect.centery = 460

    def control(self):
        if self.rect.right >= ancho:
            self.rect.right = ancho
        elif self.rect.left <= 0:
            self.rect.left = 0
#--------------------------------------------------------------------------------------------------------
class Bloque(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = cargar_img("ladrillo.png", direccion, alpha = True)
        self.rect = self.image.get_rect()




#----------------------------------------------------------------------------------------------------------
def main():

    pygame.init()
    pantalla = pygame.display.set_mode ((ancho, largo))
    pygame.display.set_caption("Breakout")
#----------------------------------------------------------------------------------------------------------
    fondo = cargar_img("fondo.jpg", direccion, alpha = False)
    bola = Pelota()
    barra= Barra(25)
    ladrillo = Bloque()
    reloj = pygame.time.Clock()
    pygame.key.set_repeat(1,20)

#----------------------------------------------------------------------------------------------------------  
    while True:
        reloj.tick(60)
        bola.refrescar()
        bola.colision(barra)
        bola.colision(ladrillo)
        barra.control()

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

        pantalla.blit(fondo,(0,0))
        pantalla.blit(bola.image, bola.rect)
        pantalla.blit(barra.image, barra.rect)
        pantalla.blit(ladrillo.image, ladrillo.rect)
        pygame.display.flip()

#----------------------------------------------------------------------------------------------------------  
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit(0)
            elif event.type == pygame.KEYDOWN:
                if event.key == K_LEFT:
                    barra.rect.centerx -= 20
                elif event.key == K_RIGHT:
                    barra.rect.centerx += 20
                elif event.key == K_ESCAPE:
                    sys.exit(0)
            elif event.type == pygame.KEYUP:
                if event.key == K_RIGHT:
                    barra.rect.centerx += 0
                elif event.key == K_LEFT:
                    barra.rect.centerx += 0
#----------------------------------------------------------------------------------------------------------
if __name__ == "__main__":
    main()

2 个答案:

答案 0 :(得分:0)

您可以使用

bricks = pygame.sprite.Group()
bricks.add( Bloque(0, 0) )
bricks.add( Bloque(100, 0) )
# etc.

保持砖块。

稍后你可以使用

bricks.draw(screen)

bricks.update() 

pygame.sprite.spritecollide(bola, bricks, dokill=True)

完整的工作代码

import pygame
import os
import sys

#--- constants --- (UPPER_CASE names)

ANCHO = 768
LARGO = 480

DIRECCION = "imagenes"

BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)

#--- classes --- (CamelCase names)

class Pelota(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

        self.image = cargar_img("bola.png", DIRECCION, True)
        self.rect = self.image.get_rect()
        self.rect.centerx = ANCHO/2
        self.rect.centery = LARGO/2
        # self.rect.center = pantalla.get_rect().center
        self.speed = [6,6]

    def  refrescar(self):
        global vidas

        if self.rect.left < 0 or self.rect.right > ANCHO: # pantalla.get_rect().right
            self.speed[0] = -self.speed[0]
        if self.rect.top < 0 :
            self.speed[1] = -self.speed[1]
        if self.rect.bottom > LARGO : # pantalla.get_rect().bottom
            self.rect.centerx = ANCHO/2 
            self.rect.centery = LARGO/2

            # self.rect.center = pantalla.get_rect().center

            self.vidas[0] -= 1

        self.rect.move_ip((self.speed[0], self.speed[1]))

    def colision(self, objeto):
        if self.rect.colliderect(objeto.rect):
            self.speed[1] = -self.speed[1]

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

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

class Barra(pygame.sprite.Sprite):

    def __init__(self, y):
        pygame.sprite.Sprite.__init__(self)

        self.image = cargar_img("paleta.png", DIRECCION, True)
        self.rect = self.image.get_rect()
        self.rect.centerx = 384
        self.rect.centery = 460

    def control(self):
        if self.rect.right >= ANCHO:
            self.rect.right = ANCHO
        elif self.rect.left <= 0:
            self.rect.left = 0

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

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

class Bloque(pygame.sprite.Sprite):

    def __init__(self, x, y):
        pygame.sprite.Sprite.__init__(self)

        self.image = cargar_img("ladrillo.png", DIRECCION, True)
        self.rect = self.image.get_rect(x=x, y=y)

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

#--- functions --- (lower_case names)

def cargar_img(nombre, direccion, alpha=False):

    ruta = os.path.join(direccion, nombre)

    try:
        image = pygame.image.load(ruta)
    except:
        print("Error al cargar la Imagen, compruebe la ruta")
        pygame.quit()
        sys.exit(1)

    if alpha:
        image = image.convert_alpha()
    else:
        image = image.convert()

    return image

def main():

    # - init -

    pygame.init()
    pantalla = pygame.display.set_mode ((ANCHO, LARGO))
    pantalla_rect = pantalla.get_rect()

    pygame.display.set_caption("Breakout")

    # - objects -

    fondo = cargar_img("fondo.jpg", DIRECCION)

    bola  = Pelota()
    barra = Barra(25)

    bricks = pygame.sprite.Group()

    for y in range(3):
        for x in range(15):
            bricks.add( Bloque(x*50, y*50) )

    # - other -

    vidas = [3] # as list to send as reference
    bola.vidas = vidas

    font = pygame.font.Font(None, 40)

    paused = False
    pause_text = font.render("PAUSE", True, WHITE)
    pause_text_rect = pause_text.get_rect(center=pantalla_rect.center)

    pygame.key.set_repeat(1, 20)

    # - mainloop -

    reloj = pygame.time.Clock()

    while True:
        reloj.tick(60)

        # - updates -

        if not paused:
            bola.refrescar()
            bola.colision(barra)

            hits = pygame.sprite.spritecollide(bola, bricks, dokill=True)

            if hits:
                bola.speed[1] = -bola.speed[1]

            barra.control()

            score = font.render(str(vidas[0]), True, WHITE)
            score_rect = score.get_rect(x=10, y=10)

        # - draws -

        #pantalla.fill(BLACK) # <-- I don't have image with background

        pantalla.blit(fondo,(0,0))

        bola.draw(pantalla)

        barra.draw(pantalla)

        bricks.draw(pantalla)

        pantalla.blit(score, score_rect)

        if paused:
            pantalla.blit(pause_text, pause_text_rect)

        pygame.display.flip()

        # - events -

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit(0)

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    barra.rect.x -= 20
                elif event.key == pygame.K_RIGHT:
                    barra.rect.x += 20
                elif event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit(0)

                elif event.key == pygame.K_SPACE:
                    paused = not paused

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

if __name__ == "__main__":
    main()

答案 1 :(得分:-1)

你需要建立一个约束,这样只有当X值介于0和??(最大宽度)之间时它才会移动。

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        sys.exit(0)
    elif event.type == pygame.KEYDOWN:
        if event.key == K_LEFT and barra.rect.centerx > 0: # Set your minimum value
            barra.rect.centerx -= 20
        elif event.key == K_RIGHT and barra.rect.centerx < 100: # Set your maximum value
            barra.rect.centerx += 20
        elif event.key == K_ESCAPE:
            sys.exit(0)
    elif event.type == pygame.KEYUP:
        if event.key == K_RIGHT:
            barra.rect.centerx += 0
        elif event.key == K_LEFT:
            barra.rect.centerx += 0

当然,您应该添加或减少条形宽度等内容。试试这些价值观。

在边缘你应该添加像

这样的东西
barra.rect.centerx -= (difference between left edge and bar)

barra.rect.centerx += (difference between right edge and bar)