使用.collide()时Pygame会增加玩家得分

时间:2018-04-07 13:34:10

标签: python pygame

碰撞检测在我的游戏中起作用,但是每次子弹碰撞时我都无法找到任何方法来增加分数计数器。

[相关代码]

[class Bullet]

def collide(self, spriteGroup):
    return pygame.sprite.spritecollide(self, spriteGroup, False)

[对手]

def collide(self, spriteGroup):
    return pygame.sprite.spritecollide(self, spriteGroup, True)

[全局]

all_sprites_list = pygame.sprite.Group()
bullet_list = pygame.sprite.Group()

player = Agent()

all_sprites_list.add(player)
opponent = Opponent()
all_sprites_list.add(opponent)

[游戏循环内部]

bullet = Bullet()
Agent()
Opponent()
bullet_list.add(opponent)
# Call the update() method on all the sprites
all_sprites_list.update()


for b in bullet_list:
    bullet_list.remove(b)#Otherwise it'll detect itself
    b.collide(bullet_list)
    bullet_list.add(b)

[尝试] 我已经尝试将碰撞方法转换为if语句并向player.score添加1,然后返回当前代码中显示的相同内容,但每次开始添加超过1子弹与对手相撞。我也在游戏循环中尝试了相同的方法,在b.collide(bullet_list)上使用if语句,但在打印player.score时也返回了一个数字流。我试着搜索.collide返回的内容,但我只能在pygame.sprite.collide_rect等命令中找到它。我使用了this tutorial中使用的.collide。有没有其他方法可以做到这一点,还是我使用错误命令?

[游戏代码]

import pygame
import time
import random
from pygame.locals import *

pygame.init()

display_width = 1002
display_height = 720

black = (0,0,0)
white = (255,255,255)
blue = (53,155,255)

gameDisplay = pygame.display.set_mode((display_width,display_height)) #creates surface/ display
clock = pygame.time.Clock() #sets a clock
bulletpicture = pygame.image.load("bullet.png")
bullet_width = 12
bullet_height = 5
blob_width = 51
blob_height = 51


class Agent(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load("blob2.png").convert()
        self.image.set_colorkey(white)
        self.rect = self.image.get_rect()
        self.score = 0
        self.previous_time = pygame.time.get_ticks()
        self.speed = 5

    def update(self):
        """ Update the player's position. """
        self.movex = 0
        self.movey = 0

        keystate = pygame.key.get_pressed()

        #set boundaries:
        if self.rect.y < 0:
            self.rect.y = 0
        if self.rect.y > display_height - blob_height:
            self.rect.y = display_height - blob_height
        if self.rect.x < 0:
            self.rect.x = 0
        if self.rect.x > 401 - blob_width:
            self.rect.x = 401 - blob_width

        #player movements
        if keystate[pygame.K_a]:
            self.movex = -self.speed
        elif keystate[pygame.K_d]:
            self.movex = self.speed
        if keystate[pygame.K_w]:
            self.movey = -self.speed
        elif keystate[pygame.K_s]:
            self.movey = self.speed
        if keystate[pygame.K_SPACE]:
            self.shoot()

        self.rect.x += self.movex
        self.rect.y += self.movey

    def shoot(self):
        # to tell the bullet where to spawn
        current_time = pygame.time.get_ticks()
        # ready to fire when 500 ms have passed.
        if current_time - self.previous_time > 500:
            self.previous_time = current_time
            all_sprites_list.add(bullet)
            bullet_list.add(bullet)

class Bullet(pygame.sprite.Sprite):
    """ This class represents the bullet . """

    def __init__(self):
        # Call the parent class (Sprite) constructor
        super().__init__()

        self.image = pygame.image.load("bullet.png").convert()
        self.image.set_colorkey(white)
        self.rect = self.image.get_rect()
        self.rect.x = player.rect.x + 20
        self.rect.y = player.rect.y + 20

    def update(self):
        """ Move the bullet. """
        self.rect.x += 5

    def collide(self, spriteGroup):
        return pygame.sprite.spritecollide(self, spriteGroup, False)


class Opponent(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load("blob2.png").convert()
        self.image.set_colorkey(white)
        self.rect = self.image.get_rect()
        self.velocity = [3, 3]
        self.rect.x = display_width/1.2
        self.rect.y = display_height/1.2
        self.previous_time = pygame.time.get_ticks()
        self.bullet_lst = []
        self.lives = 3

    def update(self):
        self.rect.x += self.velocity[0]
        self.rect.y += self.velocity[1]
        if self.rect.x + blob_width > display_width or self.rect.x < 601:
            self.velocity[0] = -self.velocity[0]

        if self.rect.y + blob_height > display_height or self.rect.y < 0:
            self.velocity[1] = -self.velocity[1]

        for b in range(len(self.bullet_lst)):
            self.bullet_lst[b][0] -= 6

        for bullet in self.bullet_lst:
            if bullet[0] < 0:
                self.bullet_lst.remove(bullet)

        current_time = pygame.time.get_ticks()
        # ready to fire when 500 ms have passed.
        if current_time - self.previous_time > 600:
            self.previous_time = current_time
            self.bullet_lst.append([self.rect.x + 25, self.rect.y + 24])

    def collide(self, spriteGroup):
        return pygame.sprite.spritecollide(self, spriteGroup, True)


all_sprites_list = pygame.sprite.Group()
bullet_list = pygame.sprite.Group()

player = Agent()

all_sprites_list.add(player)
opponent = Opponent()
all_sprites_list.add(opponent)


done = False
while not done:
    x = (display_width * 0.08)
    y = (display_height * 0.2)
    # --- Event Processing
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    # --- Game logic
    bullet = Bullet()
    Agent()
    Opponent()
    bullet_list.add(opponent)
    # Call the update() method on all the sprites
    all_sprites_list.update()

    for b in bullet_list:
        bullet_list.remove(b)#Otherwise it'll detect itself
        b.collide(bullet_list)
        bullet_list.add(b)

    # Calculate mechanics for each bullet
    for bullet in bullet_list:
        # Remove the bullet if it flies up off the screen
        if bullet.rect.x > 1010:
            bullet_list.remove(bullet)
            all_sprites_list.remove(bullet)

    # --- Draw a frame

    # Clear the screen
    gameDisplay.fill(blue)

    # Draw all the spites
    all_sprites_list.draw(gameDisplay)


    for bullet in opponent.bullet_lst:
        gameDisplay.blit(bulletpicture, pygame.Rect(bullet[0], bullet[1], 0, 0))
        if bullet[0] + bullet_width < player.rect.x + blob_width and bullet[0] > player.rect.x:
            if bullet[1] > player.rect.y and bullet[1] < player.rect.y + blob_height or bullet[1] + bullet_height > player.rect.y and bullet[1] + bullet_height < player.rect.y + blob_height:
                opponent.bullet_lst.remove(bullet)
                opponent.lives -= 1


    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # --- Limit to 20 frames per second
    clock.tick(60)

1 个答案:

答案 0 :(得分:2)

使用pygame.sprite.spritecollide查看哪些子弹与对手发生了碰撞:collided_bullets = pygame.sprite.spritecollide(opponent, bullet_list, True)。它返回一个碰撞子弹的列表,您可以使用for循环进行迭代以增加分数并减少生命(每个碰撞的子弹一次)。

编辑:如果对手应该被移除并且如果同时应该有很多对手,那么最好使用pygame.sprite.groupcollide并将对手组和子弹组作为参数传递。 groupcollide返回一个字典,其中碰撞的对手作为键,列表中的子弹作为值。一旦对手的lives用完,就会调用kill方法,将其从all_spritesopponent组中移除。

这是一个简单,完整的例子:

import pygame


pygame.init()

display_width = 1002
display_height = 720
blue = (53,155,255)

gameDisplay = pygame.display.set_mode((display_width,display_height))
clock = pygame.time.Clock()
bulletpicture = pygame.Surface((12, 5))
bulletpicture.fill((20, 30, 20))


class Bullet(pygame.sprite.Sprite):
    """This class represents the bullet."""

    def __init__(self, pos):
        super().__init__()
        self.image = bulletpicture
        self.rect = self.image.get_rect(center=pos)

    def update(self):
        """Move the bullet."""
        self.rect.x += 5
        # Remove the bullet if it flies up off the screen
        if self.rect.x > display_width+12:
            self.kill()  # Remove the sprite from all sprite groups.


class Opponent(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((30, 50))
        self.image.fill((250, 130, 20))
        self.rect = self.image.get_rect()
        self.rect.x = display_width/1.2
        self.rect.y = display_height/1.2
        self.lives = 3

    def update(self):
        if self.lives <= 0:
            self.kill()  # Remove the sprite from all sprite groups.


all_sprites_list = pygame.sprite.Group()
bullet_list = pygame.sprite.Group()
opponents = pygame.sprite.Group()
opponent = Opponent()
all_sprites_list.add(opponent)
opponents.add(opponent)

score = 0

done = False
while not done:
    # --- Event Processing
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # Click a mouse button to instantiate a bullet.
            bullet = Bullet(event.pos)
            bullet_list.add(bullet)
            all_sprites_list.add(bullet)

    # --- Game logic
    # Call the update() method on all the sprites.
    all_sprites_list.update()

    # Check which bullets have collided with the opponents.
    collided_opponents = pygame.sprite.groupcollide(opponents, bullet_list, False, True)
    for opponent, bullets in collided_opponents.items():
        for bullet in bullets:
            score += 1  # Increment the score.
            opponent.lives -= 1  # Decrement the lives.
            pygame.display.set_caption(str(score))

    # --- Draw a frame
    gameDisplay.fill(blue)
    all_sprites_list.draw(gameDisplay)

    pygame.display.flip()
    clock.tick(60)