Попытка загнать врага в пигам, когда здоровье достигнет 0 - PullRequest
4 голосов
/ 12 февраля 2020

Вот раздел, который я пытаюсь заставить работать, мое намерение состоит в том, чтобы вытеснить врага из кода, в настоящее время, когда враг достигает 0, он исчезает и больше не повреждает игру, но пули все еще могут поразить врага в месте, где он был уничтожен:

for lizard in enemy:
    if lizard.visible == True:
        enemy.pop(enemy.index(lizard))

Вот ошибка, которую я продолжаю получать:

Ошибка типа: объект 'type' не повторяется

Ниже вы можете увидеть полный код:

import pygame
pygame.init()
win = pygame.display.set_mode((600, 580))

pygame.display.set_caption('new nas')

screenWidth = 500

walkRight = [pygame.image.load('R1.png'), 
pygame.image.load('R2.png'), pygame.image.load('R3.png'), pygame.image.load('R4.png'), pygame.image.load('R5.png'), pygame.image.load('R6.png'), pygame.image.load('R7.png'), pygame.image.load('R8.png'), pygame.image.load('R9.png')]
walkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'), pygame.image.load('L4.png'), pygame.image.load('L5.png'), pygame.image.load('L6.png'), pygame.image.load('L7.png'), pygame.image.load('L8.png'), pygame.image.load('L9.png')]
bg = pygame.image.load('sunset.jpg')
char = pygame.image.load('standing.png')

clock = pygame.time.Clock()

bowSound = pygame.mixer.Sound('Bow_release.wav')
arrowSound = pygame.mixer.Sound('Arrow_hit.wav')

music = pygame.mixer.music.load('upbeat.mp3')
pygame.mixer.music.play(-1)

score = 0


#hero
class player(object):
    def __init__(self,x,y,width,height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = 5
        self.isJump = False
        self.jumpCount = 10
        self.left = False
        self.right = False
        self.walkCount = 0
        self.standing = True
        self.hitbox = (self.x + 17, self.y + 11, 29, 52)
        self.health = 10
        self.visible = True


    def draw(self, win):
        if self.visible:
            self.health > 1
        else:
            self.visible == False

        if self.walkCount + 1 >= 27:
            self.walkCount = 0

        if not (self.standing):
            if self.left:
                win.blit(walkLeft[self.walkCount//3], (self.x,self.y))
                self.walkCount += 1
            elif self.right:
                win.blit(walkRight[self.walkCount//3], (self.x,self.y))
                self.walkCount += 1
        else:
            if self.right:
                win.blit(walkRight[0], (self.x, self.y))
            else:
                win.blit(walkLeft[0], (self.x, self.y))
        self.hitbox = (self.x + 17, self.y + 11, 29, 52)
        pygame.draw.rect(win, (255,0,0), (self.hitbox[0], self.hitbox[1] - 20, 50,10))
        pygame.draw.rect(win, (0,100,0), (self.hitbox[0], self.hitbox[1] - 20, 50 - ((50/10) * (10 - self.health)),10))
        #pygame.draw.rect(win, (255,0,0), self.hitbox,2)

    def hit(self):
        self.jumpCount = False
        self.jumpCount = 10
        self.x = 25
        self.y = 480
        self.walkCount = 0
        font1 = pygame.font.SysFont('forte', 100)
        text = font1.render('-5', 1, (255,0,0))




        pygame.display.update()
        i = 0
        while i < 100:
            pygame.time.delay(10)
            i += 1
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    i = 301
                    pygame.quit()



# weap

class projectile(object):
    def __init__(self,x,y,radius,color,facing):
        self.x = x
        self.y = y
        self.radius = radius
        self.color = color
        self.facing = facing
        self.vel = 8 * facing

    def draw(self,win):
        pygame.draw.circle(win, self.color, (self.x,self.y), self.radius)

# enemy fodder

class enemy(object):
    walkRight = [pygame.image.load('R1E.png'), pygame.image.load('R2E.png'), pygame.image.load('R3E.png'), pygame.image.load('R4E.png'), pygame.image.load('R5E.png'), pygame.image.load('R6E.png'), pygame.image.load('R7E.png'), pygame.image.load('R8E.png'), pygame.image.load('R9E.png'), pygame.image.load('R10E.png'), pygame.image.load('R11E.png')]
    walkLeft = [pygame.image.load('L1E.png'), pygame.image.load('L2E.png'), pygame.image.load('L3E.png'), pygame.image.load('L4E.png'), pygame.image.load('L5E.png'), pygame.image.load('L6E.png'), pygame.image.load('L7E.png'), pygame.image.load('L8E.png'), pygame.image.load('L9E.png'), pygame.image.load('L10E.png'), pygame.image.load('L11E.png')]

    def __init__(self, x, y, width, height, end):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.end = end
        self.path = [self.x, self.end]
        self.walkCount = 0
        self.vel = 3
        self.hitbox = (self.x + 17, self.y + 2, 31, 57)
        self.health = 10
        self.visible = True

    def draw(self,win):
        self.move()
        if self.visible:
            if self.walkCount + 1 >= 33:
                self.walkCount = 0

            if self.vel > 1:
                win.blit(self.walkRight[self.walkCount //3], (self.x, self.y))
                self.walkCount += 1
            else:
                win.blit(self.walkLeft[self.walkCount //3], (self.x, self.y))
                self.walkCount += 1

            pygame.draw.rect(win, (255,0,0), (self.hitbox[0], self.hitbox[1] - 20, 50,10))
            pygame.draw.rect(win, (0,100,0), (self.hitbox[0], self.hitbox[1] - 20, 50 - ((50/10) * (10 - self.health)),10))
            self.hitbox = (self.x + 17, self.y + 2, 31, 57)
            #pygame.draw.rect(win, (255,0,0), self.hitbox,2)

    def move(self):
        if self.vel > 0:
            if self.x < self.path[1] + self.vel:
                self.x += self.vel
            else:
                self.vel = self.vel * -1
                self.walkCount = 0
        else:
            if self.x > self.path[0] - self.vel:
                self.x += self.vel
            else:
                self.vel = self.vel * -1
                self.walkCount = 0

    def hit(self):
        if self.health > 0:
            self.health -= 1
        else:
            self.visible = False
        print('hit')


def redrawGameWindow():
    win.blit(bg, (0,0))
    text = font.render('Score: ' + str(score), 1, (0,0,0))
    win.blit(text, (400, 10))
    nas.draw(win)
    lizard.draw(win)
    for bullet in bullets:
        bullet.draw(win)

    pygame.display.update()

#main loop
font = pygame.font.SysFont('forte', 20, True)
nas = player(50, 480, 64, 64)
lizard = enemy(100, 485, 64, 64, 450)
run = True
shootLoop = 0
bullets = []
while run:
    clock.tick(27)

    if lizard.visible == True:
        if nas.hitbox[1] < lizard.hitbox[1] + lizard.hitbox[3] and nas.hitbox[1] + nas.hitbox[3] > lizard.hitbox[1]:
            if nas.hitbox[0] + nas.hitbox[2] > lizard.hitbox[0] and nas.hitbox[0] < lizard.hitbox[0] + lizard.hitbox[2]:

                nas.hit()
                score -= 5

    for lizard in enemy:
        if lizard.visible == True:
            enemy.pop(enemy.index(lizard))


# projectile cool down
    if shootLoop > 0:
        shootLoop += 1
    if shootLoop > 3:
        shootLoop = 0


    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    for bullet in bullets:
        if bullet.y - bullet.radius < lizard.hitbox[1] + lizard.hitbox[3] and bullet.y + bullet.radius > lizard.hitbox[1]:
            if bullet.x + bullet.radius > lizard.hitbox[0] and bullet.x - bullet.radius < lizard.hitbox[0] + lizard.hitbox[2]:
                arrowSound.play()
                lizard.hit()
                score += 1
                bullets.pop(bullets.index(bullet))

        if bullet.x < 500 and bullet.x > 0:
            bullet.x += bullet.vel
        else:
            bullets.pop(bullets.index(bullet))



    keys = pygame.key.get_pressed()

    if keys[pygame.K_SPACE] and shootLoop == 0:
        bowSound.play()
        if nas.left:
            facing = -1
        else:
            facing = 1

        if len(bullets) < 3:
            bullets.append(projectile(round(nas.x + nas.width//2), round(nas.y + nas.height//2), 6,(250,0,0), facing))

        shootLoop = 1

    if keys [pygame.K_a] and nas.x > nas.vel:
        nas.x -= nas.vel
        nas.left = True
        nas.right = False
        nas.standing = False

    elif keys [pygame.K_d] and nas.x < 500 - nas.width - nas.vel:
        nas.x += nas.vel
        nas.right = True
        nas.left = False
        nas.standing = False

    else:
        nas.standing = True
        nas.walkCount = 0

    if not (nas.isJump):   
            if keys[pygame.K_w]:
                nas.isJump = True
                nas.right = False
                nas.left = False
                nas.walkCount = 0

    else:
        if nas.jumpCount >= -10:
            neg = 1
            if nas.jumpCount < 0:
                neg = -1
            nas.y -= (nas.jumpCount ** 2) * 0.2 * neg
            nas.jumpCount -= 1
        else:
            nas.isJump = False
            nas.jumpCount = 10

    redrawGameWindow()


pygame.quit()

Ответы [ 2 ]

0 голосов
/ 12 февраля 2020

enemy - это класс, а не список, поэтому его нельзя повторять. Кстати, имена классов обычно должны использовать соглашение CapWords. См. Руководство по стилю для Python Код .


В любом случае, добавьте список enemies в приложение. Список можно просмотреть и убить врагов можно:

enemies = []
enemies.append(Enemy(100, 485, 64, 64, 450))

# [...]

while run:
    # [...]

    for lizard in enemies[:]:
        if lizard.visible == True:
            if nas.hitbox[1] < lizard.hitbox[1] + lizard.hitbox[3] and nas.hitbox[1] + nas.hitbox[3] > lizard.hitbox[1]:
                if nas.hitbox[0] + nas.hitbox[2] > lizard.hitbox[0] and nas.hitbox[0] < lizard.hitbox[0] + lizard.hitbox[2]:

                    nas.hit()
                    score -= 5

        if lizard.visible == False:
            enemies.pop(enemies.index(lizard))

Рекомендую прочитать о pygame.Rect. Используйте collidepoint() для упрощения кода проверки столкновения. Например:

while run:
    # [...]

    for lizard in enemies[:]:
        if lizard.visible:

            lizard_rect = pygame.Rect(*lizard.hitbox)
            nas_rect = pygame.Rect(*nas.hitbox)
            if nas_rect.colliderect(lizard_rect):
                nas.hit()
                score -= 5

        if not lizard.visible:
            enemies.pop(enemies.index(lizard))

Кроме того, способ реализации таких приложений в Pygame - использовать pygame.sprite.Sprite и pygame.sprite.Group

0 голосов
/ 12 февраля 2020

Попробуйте убрать врага с экрана. Что-то вроде enemy.move(-100, 100) в псевдокоде.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...