Космические захватчики: загрузка изображений - PullRequest
2 голосов
/ 05 августа 2020

Я пытаюсь создать Space Invaders как проект, я смотрел видео Tech With Tim о его создании и до сих пор это делал.

Я внес много изменений в программа и много экспериментировал с ней, но всегда есть одна вещь, которая идет не так, что все портит.

Это мой первый пост здесь, я не совсем уверен, как это сделать .. . Посмотрим. Это мой код прямо сейчас:

import random
import pygame
import mixer

pygame.font.init()
pygame.init()

WIDTH, HEIGHT = 800, 600
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("The Space Walker")

# Load images
RSHIP = pygame.image.load("RShip.png")
GSHIP = pygame.image.load("GShip.png")
BSHIP = pygame.image.load("BShip.png")
BOSS = pygame.image.load("Boss.png")

# Player player
BLSHIP = pygame.image.load("BLShip.png")

# Lasers
RLASER = pygame.image.load("RLaser.png")
GLASER = pygame.image.load("GLaser.png")
BLASER = pygame.image.load("Blaser.png")
BLLASER = pygame.image.load("BLlaser.png")
BOLASER = pygame.image.load("BOLaser.png")

# Background
BG = pygame.transform.scale(pygame.image.load("background.png"), (WIDTH, HEIGHT))

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


def pause():
    paused = True

    while paused:
        pause_font = pygame.font.SysFont("freesansbold.ttf", 80)
        con_font = pygame.font.SysFont("freesansbold.ttf", 80)
        for event in pygame.event.get():

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_c:
                    paused = False

        pause_label = pause_font.render("Paused", 1, (255, 255, 255))
        WIN.blit(pause_label, (WIDTH / 2 - pause_label.get_width() / 2, 250))
        con_label = con_font.render("C to Continue", 1, (255, 255, 255))
        WIN.blit(con_label, (WIDTH / 2 - con_label.get_width() / 2, 300))
        pygame.display.update()
        pygame.time.Clock()


class Boss:
    COOLDOWN = 50

    def __init__(self, x, y, health=200):
        self.x = x
        self.y = y
        self.health = health
        self.ship_img = None
        self.laser_img = None
        self.lasers = []
        self.cool_down_counter = 0

    def draw(self, window):
        window.blit(self.ship_img, (self.x, self.y))
        for laser in self.lasers:
            laser.draw(window)

    def move_lasers(self, vel, obj):
        self.cooldown()
        for laser in self.lasers:
            laser.move(vel)
            if laser.off_screen(HEIGHT):
                self.lasers.remove(laser)
            elif laser.collision(obj):
                obj.health -= 20
                self.lasers.remove(laser)

    def cooldown(self):
        if self.cool_down_counter >= self.COOLDOWN:
            self.cool_down_counter = 0
        elif self.cool_down_counter > 0:
            self.cool_down_counter += 1

    def shoot(self):
        if self.cool_down_counter == 0:
            laser = Laser(self.x - 20, self.y, self.laser_img)
            self.lasers.append(laser)
            self.cool_down_counter = 1

    def get_width(self):
        return self.ship_img.get_width()

    def get_height(self):
        return self.ship_img.get_height()

    def move(self, boss_vel):
        pass


class Laser:
    def __init__(self, x, y, img):
        self.x = x
        self.y = y
        self.img = img
        self.mask = pygame.mask.from_surface(self.img)

    def draw(self, window):
        window.blit(self.img, (self.x, self.y))

    def move(self, vel):
        self.y += vel

    def off_screen(self, height):
        return not (self.y <= height and self.y >= 0)

    def collision(self, obj):
        return collide(self, obj)


class Ship:
    COOLDOWN = 30

    def __init__(self, x, y, health=100):
        self.x = x
        self.y = y
        self.health = health
        self.ship_img = None
        self.laser_img = None
        self.lasers = []
        self.cool_down_counter = 0

    def draw(self, window):
        window.blit(self.ship_img, (self.x, self.y))
        for laser in self.lasers:
            laser.draw(window)

    def move_lasers(self, vel, obj):
        self.cooldown()
        for laser in self.lasers:
            laser.move(vel)
            if laser.off_screen(HEIGHT):
                self.lasers.remove(laser)
            elif laser.collision(obj):
                obj.health -= 10
                self.lasers.remove(laser)

    def cooldown(self):
        if self.cool_down_counter >= self.COOLDOWN:
            self.cool_down_counter = 0
        elif self.cool_down_counter > 0:
            self.cool_down_counter += 1

    def shoot(self):
        if self.cool_down_counter == 0:
            laser = Laser(self.x - 17, self.y, self.laser_img)
            self.lasers.append(laser)
            self.cool_down_counter = 1

    def get_width(self):
        return self.ship_img.get_width()

    def get_height(self):
        return self.ship_img.get_height()


class Player(Ship):
    def __init__(self, x, y, health=100):
        super().__init__(x, y, health)
        self.ship_img = BLSHIP
        self.laser_img = BLLASER
        self.mask = pygame.mask.from_surface(self.ship_img)
        self.max_health = health

    def move_lasers(self, vel, objs):
        self.cooldown()
        for laser in self.lasers:
            laser.move(vel)
            if laser.off_screen(HEIGHT):
                self.lasers.remove(laser)
            else:
                for obj in objs:
                    if laser.collision(obj):
                        objs.remove(obj)
                        if laser in self.lasers:
                            self.lasers.remove(laser)

    def draw(self, window):
        super().draw(window)
        self.healthbar(window)

    def healthbar(self, window):
        pygame.draw.rect(window, (255, 0, 0),
                         (self.x, self.y + self.ship_img.get_height() + 10, self.ship_img.get_width(), 10))
        pygame.draw.rect(window, (0, 255, 0), (
            self.x, self.y + self.ship_img.get_height() + 10,
            self.ship_img.get_width() * (self.health / self.max_health),
            10))


class Enemy(Ship):
    COLOR_MAP = {
        "red": (RSHIP, RLASER),
        "green": (GSHIP, GLASER),
        "blue": (BSHIP, BLASER),
    }

    def __init__(self, x, y, color, health=100):
        super().__init__(x, y, health)
        self.ship_img, self.laser_img = self.COLOR_MAP[color]
        self.mask = pygame.mask.from_surface(self.ship_img)

    def move(self, vel):
        self.y += vel

    def shoot(self):
        if self.cool_down_counter == 0:
            laser = Laser(self.x - 20, self.y, self.laser_img)
            self.lasers.append(laser)
            self.cool_down_counter = 1


class BBoss(Ship):
    def __init__(self, x, y, health=200):
        super().__init__(x, y, health)
        self.ship_img = BOSS
        self.laser_img = BOLASER
        self.mask = pygame.mask.from_surface(self.ship_img)

    def draw(self, window):
        super().draw(window)

    def move(self, boss_vel):
        self.y += boss_vel

    def shoot(self):
        if self.cool_down_counter == 0:
            laser = Laser(self.x - 50, self.y, self.laser_img)
            self.lasers.append(laser)
            self.cool_down_counter = 2


def collide(obj1, obj2):
    offset_x = obj2.x - obj1.x
    offset_y = obj2.y - obj1.y
    return obj1.mask.overlap(obj2.mask, (offset_x, offset_y)) != None


def main():
    run = True
    FPS = 60
    level = 4
    lives = 3
    score = 0

    main_font = pygame.font.SysFont("freesansbold.ttf", 50)
    winc_font = pygame.font.SysFont("freesansbold.ttf", 70)
    lost_font = pygame.font.SysFont("freesansbold.ttf", 70)

    enemies = []
    bosses = []
    wave_length = 5
    enemy_vel = 1

    boss_vel = 1
    player_vel = 5
    laser_vel = 3

    player = Player(350, 500)

    clock = pygame.time.Clock()

    lost = False
    lost_count = 0

    winc = False
    winc_count = 0

    def redraw_window():
        WIN.blit(BG, (0, 0))
        # draw text
        lives_label = main_font.render(f"Lives: {lives}", 1, (255, 255, 255))
        level_label = main_font.render(f"Level: {level}", 1, (255, 255, 255))
        score_label = main_font.render(f"Score: {score}", 1, (255, 255, 255))

        WIN.blit(lives_label, (10, 10))
        WIN.blit(level_label, (WIDTH - level_label.get_width() - 10, 10))
        WIN.blit(score_label, (20, 550))

        for enemy in enemies:
            enemy.draw(WIN)

        player.draw(WIN)

        if lost:
            lost_label = lost_font.render("GAME OVER", 1, (255, 255, 255))
            WIN.blit(lost_label, (WIDTH / 2 - lost_label.get_width() / 2, 250))

        if winc:
            winc_label = winc_font.render("You Win!", 1, (255, 255, 255))
            WIN.blit(winc_label, (WIDTH / 2 - winc_label.get_width() / 2, 250))

        pygame.display.update()

    while run:
        clock.tick(FPS)
        redraw_window()

        if lives <= 0 or player.health <= 0:
            lost = True
            lost_count += 1

        if lost:
            if lost_count > FPS * 3:
                run = False
            else:
                continue

        if level < 5:
            if len(enemies) == 0:
                level += 1
                wave_length += 3
                for i in range(wave_length):
                    if level == 1:
                        enemy = Enemy(random.randrange(25, WIDTH - 50), random.randrange(-1200, -100),
                                      random.choice(["blue"]))
                        enemies.append(enemy)
                    if level == 2:
                        enemy = Enemy(random.randrange(25, WIDTH - 50), random.randrange(-1200, -100),
                                      random.choice(["red"]))
                        enemies.append(enemy)
                    if level == 3:
                        enemy = Enemy(random.randrange(25, WIDTH - 25), random.randrange(-1200, -100),
                                      random.choice(["green"]))
                        enemies.append(enemy)
                    if level == 4:
                        enemy = Enemy(random.randrange(12, WIDTH - 25), random.randrange(-1200, -100),
                                      random.choice(["red", "green", "blue"]))
                        enemies.append(enemy)
        if level == 5:
            player.health = 100
            boss = Boss(random.randrange(340, 360), random.randrange(-700, -100))
            bosses.append(boss)

        if level > 5:
            winc = True
            winc_count += 1

        if winc:
            if winc_count > FPS * 3:
                run = False
            else:
                continue

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

        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] and player.x - player_vel > 0:  # left
            player.x -= player_vel
        if keys[pygame.K_RIGHT] and player.x + player_vel + player.get_width() < WIDTH:  # right
            player.x += player_vel
        if keys[pygame.K_SPACE]:
            player.shoot()
        if keys[pygame.K_p]:
            pause()

        for boss in bosses[:]:
            boss.move(boss_vel)
            boss.move_lasers(laser_vel, player)

            if random.randrange(0, 2 * 60) == 1:
                boss.shoot()

        for enemy in enemies[:]:
            enemy.move(enemy_vel)
            enemy.move_lasers(laser_vel, player)

            if random.randrange(0, 2 * 60) == 1:
                enemy.shoot()

            if collide(enemy, player):
                player.health -= 10
                enemies.remove(enemy)
                score += 1

            elif enemy.y + enemy.get_height() > HEIGHT:
                lives -= 1
                enemies.remove(enemy)

        player.move_lasers(-laser_vel, enemies)


def main_menu():
    title_font = pygame.font.SysFont("freesansbold.ttf", 80)
    run = True
    while run:
        WIN.blit(BG, (0, 0))
        title_label = title_font.render("Click to start", 1, (255, 255, 255))
        WIN.blit(title_label, (WIDTH / 2 - title_label.get_width() / 2, 250))
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                main()

    pygame.quit()


main_menu()

Я постоянно сталкиваюсь с этой ошибкой, и она не меняется:

C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py:198: DeprecationWarning: an integer is required (got type float).  Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python.
  pygame.draw.rect(window, (0, 255, 0), (
Traceback (most recent call last):
  File "C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py", line 415, in <module>
    main_menu()
  File "C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py", line 410, in main_menu
    main()
  File "C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py", line 377, in main
    boss.shoot()
  File "C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py", line 90, in shoot
    laser = Laser(self.x - 20, self.y, self.laser_img)
  File "C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py", line 109, in __init__
    self.mask = pygame.mask.from_surface(self.img)
TypeError: argument 1 must be pygame.Surface, not None

Может ли кто-нибудь помочь мне исправить это? Я не уверен, что здесь делать.

1 Ответ

3 голосов
/ 05 августа 2020

Посмотрите на эту строку здесь

            boss = Boss(random.randrange(340, 360), random.randrange(-700, -100))

Вот как вы создаете экземпляр своего босса

Теперь посмотрите, как вы определили init своего класса Boss

 def __init__(self, x, y, health=200):
        self.x = x
        self.y = y
        self.health = health
        self.ship_img = None
        self.laser_img = None
        self.lasers = []
        self.cool_down_counter = 0

Обратите внимание, что self.laser_img = None.

Теперь обратите внимание на имеющуюся ошибку:

    laser = Laser(self.x - 20, self.y, self.laser_img)

Ваш третий аргумент - None. Теперь посмотрите на следующую часть вашей ошибки:

        self.mask = pygame.mask.from_surface(self.img)

self.img на самом деле None, поэтому вы получаете сообщение об ошибке.

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