Как исправить пулю в моем проекте Pygame? - PullRequest
0 голосов
/ 09 апреля 2020

Я работал над этим проектом о танках (основанном на игре Tank Trouble), и я нашел 2 ошибки в моей игре.

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

Я хочу исправить их, но не могу найти проблему. Я буду признателен за любую помощь!

Вот мой танк и пуля:

enter image description here enter image description here

Здесь такое код игры:

import sys
import pygame, math, random
from pygame.locals import *

pygame.mixer.pre_init(44100, -16, 2, 512)
pygame.init()

# ======================= Variables =======================

gray = (168, 168, 168)
dark_gray = (75, 75, 75)
white = (255, 255, 255)

font = pygame.font.Font("bin/font/Montserrat.ttf", 20)

bounce = pygame.mixer.Sound("bin/audio/bounce.wav")
bounce.set_volume(2)


# =========================================================

class Game:

    def __init__(self):
        self.run = True
        self.screen_width = 1060
        self.screen_height = 798
        self.image = pygame.image.load("bin/sprites/background/background1.png")
        self.image = pygame.transform.scale(self.image, (self.screen_width, self.screen_height))
        self.screen = pygame.display.set_mode((self.screen_width, self.screen_height))

        # all_sprites is used to update and draw all sprites together.
        self.all_sprites = pygame.sprite.Group()

        # for collision detection with enemies.
        self.bullet_group = pygame.sprite.Group()

        self.tank = Tank()
        self.all_sprites.add(self.tank)

        self.enemy = Enemy()
        self.all_sprites.add(self.enemy)

        bullet = Bullet(self.tank)
        self.bullet_group.add(bullet)
        self.all_sprites.add(bullet)

    def handle_events(self):
        keys = pygame.key.get_pressed()
        self.tank.handle_events()
        self.enemy.handle_events()

        if keys[pygame.K_UP] and self.tank.rect.left - 5 > 0 and self.tank.rect.top - 5 > 0 and self.tank.rect.right + 5 < 1060 and self.tank.rect.bottom + 5 < 798:
            self.tank.move(-3)
        if keys[pygame.K_DOWN]:
            self.tank.move(3)
        if keys[pygame.K_w]:
            self.enemy.move(-3)
        if keys[pygame.K_s]:
            self.enemy.move(3)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.run = False
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    self.run = False
                if event.key == pygame.K_SPACE:
                    bullet = Bullet(self.tank)
                    self.bullet_group.add(bullet)
                    self.all_sprites.add(bullet)

    def update(self):
        # Calls `update` methods of all contained sprites.
        self.all_sprites.update()

    def draw(self):
        self.screen.blit(self.image, (0, 0))
        self.all_sprites.draw(self.screen)  # Draw the contained sprites.
        pygame.display.update()


class Tank(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("bin/sprites/player/player_tank.png")
        self.org_image = self.image.copy()

        # A nicer way to set the start pos with `get_rect`.
        self.rect = self.image.get_rect(center=(70, 600))

        self.vel = 3

        self.angle = 270 # starts looking right
        self.direction = pygame.Vector2(1, 0)
        self.pos = pygame.Vector2(self.rect.center)

        self.hp = 1

    def handle_events(self):
        pressed = pygame.key.get_pressed()
        if pressed[pygame.K_LEFT]:
            self.angle += 3
        if pressed[pygame.K_RIGHT]:
            self.angle -= 3

        self.direction = pygame.Vector2(1, 0).rotate(-self.angle)
        self.image = pygame.transform.rotate(self.org_image, self.angle)
        self.rect = self.image.get_rect(center=self.rect.center)

    def move(self, vel):
        direction = pygame.Vector2(0, vel).rotate(-self.angle)
        self.pos += direction
        self.rect.center = round(self.pos[0]), round(self.pos[1])


class Enemy(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("bin/sprites/enemy/enemy_tank.png")
        self.org_image = self.image.copy()

        self.spawnx = [600, 850, 860] # spawning x coord
        self.spawny = [70, 200, 700] # spawning y coord
        self.i = random.randint(0, len(self.spawnx) - 1)

        # A nicer way to set the start pos with `get_rect`.
        self.rect = self.image.get_rect(center=(self.spawnx[self.i], self.spawny[self.i]))

        self.vel = 3
        self.hp = 1

        if self.i == 0:
            self.angle = 180
        elif self.i == 1:
            self.angle = 90
        elif self.i == 2:
            self.angle = 0

        self.direction = pygame.Vector2(1, 0)
        self.pos = pygame.Vector2(self.rect.center)

    def handle_events(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_a]:
            self.angle += 3
        if keys[pygame.K_d]:
            self.angle -= 3

        self.direction = pygame.Vector2(1, 0).rotate(-self.angle)
        self.image = pygame.transform.rotate(self.org_image, self.angle)
        self.rect = self.image.get_rect(center=self.rect.center)

    def move(self, vel):
        direction = pygame.Vector2(0, vel).rotate(-self.angle)
        self.pos += direction
        self.rect.center = round(self.pos[0]), round(self.pos[1])



class Bullet(pygame.sprite.Sprite):

    def __init__(self, tank):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("bin/sprites/bullet/bullet.png")
        self.image = pygame.transform.scale(self.image, (16, 16))
        self.rect = self.image.get_rect()
        self.rect.centerx = tank.rect.centerx + 3  # How much pixels from tank turret on x axis
        self.rect.centery = tank.rect.centery - 25  # How much pixels from tank turret on y axis
        self.angle = tank.angle
        self.pos = pygame.Vector2(self.rect.center)
        self.direction = pygame.Vector2(0, -10).rotate(-self.angle)
        self.lives = 4  # how many times bounces

    def update(self):
        self.pos += self.direction
        self.rect.center = round(self.pos[0]), round(self.pos[1])

        if self.rect.left < 0:
            self.direction.x *= -1
            self.rect.left = 0
            self.pos.x = self.rect.centerx
            self.lives -= 1
            if self.lives == 0:
                return self.kill()
            bounce.play()

        if self.rect.right > 1060:
            self.direction.x *= -1
            self.rect.right = 1060
            self.pos.x = self.rect.centerx
            self.lives -= 1
            if self.lives == 0:
                return self.kill()
            bounce.play()

        if self.rect.top < 0:
            self.direction.y *= -1
            self.rect.top = 0
            self.pos.y = self.rect.centery
            self.lives -= 1
            if self.lives == 0:
                return self.kill()
            bounce.play()

        if self.rect.bottom > 798:
            self.direction.y *= -1
            self.rect.right = 798
            self.pos.y = self.rect.centery
            self.lives -= 1
            if self.lives == 0:
                return self.kill()
            bounce.play()


font = pygame.font.SysFont("bin/font/Montserrat.ttf", 40)
text = font.render("PLAY", 1, white)
font = pygame.font.SysFont("bin/font/Montserrat.ttf", 50)
title = font.render("TANK TROUBLE", 1, dark_gray)

click = False


def main_menu():
    global click
    clock = pygame.time.Clock()
    game = Game()

    while True:
        pygame.display.set_caption('Tank Trouble')
        game.screen.fill((white))

        mx, my = pygame.mouse.get_pos()

        button_1 = pygame.Rect(377, 370, 300, 50)
        if button_1.collidepoint((mx, my)):
            if click:
                main()
        pygame.draw.rect(game.screen, gray, button_1)
        game.screen.blit(text, (490, 383))
        game.screen.blit(title, (395, 320))

        click = False
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                if event.key == K_RETURN:
                    main()
            if event.type == MOUSEBUTTONDOWN:
                if event.button == 1:
                    click = True

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


def main():
    pygame.display.set_caption('Tank Trouble')
    clock = pygame.time.Clock()
    game = Game()

    while game.run:
        game.handle_events()
        game.update()
        game.draw()
        clock.tick(60)


if __name__ == '__main__':
    main_menu()
    pygame.quit()
    sys.exit()

1 Ответ

1 голос
/ 09 апреля 2020

«Первое, когда я порождаю пулю, которая стреляет сама по себе без какого-либо ключевого ввода».

Ну, вы звоните

bullet = Bullet(self.tank)

в Game.__init__(), так что это обязательно произойдет.

во-вторых, пули стреляют прямо из башни, когда угол танка равен 0 ° или 180 °.

Я не уверен, что вы имеете в виду здесь.

...