Как мне остановить более чем одну пулю одновременно? - PullRequest
2 голосов
/ 08 февраля 2020
import pygame
pygame.init()

red = 255,0,0
blue = 0,0,255
black = 0,0,0

screenWidth = 800
screenHeight = 600

gameDisplay = pygame.display.set_mode((screenWidth,screenHeight))        ## screen width and height
pygame.display.set_caption('JUST SOME BLOCKS')       ## set my title of the window

clock = pygame.time.Clock()

class player():       ## has all of my attributes for player 1
    def __init__(self,x,y,width,height):
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.vel = 5
        self.left = False
        self.right = False
        self.up = False
        self.down = False

class projectile():     ## projectile attributes
    def __init__(self,x,y,radius,colour,facing):
        self.x = x
        self.y = y
        self.radius = radius
        self.facing = facing
        self.colour = colour
        self.vel = 8 * facing       # speed of bullet * the direction (-1 or 1)

    def draw(self,gameDisplay):
        pygame.draw.circle(gameDisplay, self.colour , (self.x,self.y),self.radius)      ## put a 1 after that to make it so the circle is just an outline

def redrawGameWindow():
    for bullet in bullets:      ## draw bullets
        bullet.draw(gameDisplay)

    pygame.display.update()   

#mainloop

player1 = player(300,410,50,70)     # moves the stuff from the class (when variables are user use player1.var)
bullets = []

run = True
while run == True:
    clock.tick(27)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    for bullet in bullets:
        if bullet.x < screenWidth and bullet.x > 0 and bullet.y < screenHeight and bullet.y > 0: ## makes sure bullet does not go off screen
            bullet.x += bullet.vel
        else:
            bullets.pop(bullets.index(bullet))


    keys = pygame.key.get_pressed()     ## check if a key has been pressed

    ## red player movement   
    if keys[pygame.K_w] and player1.y > player1.vel:    ## check if that key has been pressed down (this will check for w)     and checks for boundry
        player1.y -= player1.vel            ## move the shape in a direction
        player1.up = True
        player1.down = False

    if keys[pygame.K_a] and player1.x > player1.vel:      ### this is for a 
        player1.x -= player1.vel
        player1.left = True
        player1.right = False

    if keys[pygame.K_s] and player1.y < screenHeight - player1.height - player1.vel: ## this is for s
        player1.y += player1.vel
        player1.down = True
        player1.up = False

    if keys[pygame.K_d] and player1.x < screenWidth - player1.width - player1.vel:   ## this is for d                          
        player1.x += player1.vel
        player1.right = True
        player1.left = False

    if keys[pygame.K_SPACE]:     # shooting with the space bar
        if player1.left == True:   ## handles the direction of the bullet
            facing = -1
        else:
            facing = 1  


        if len(bullets) < 5:    ## max amounts of bullets on screen
            bullets.append(projectile(player1.x + player1.width //2 ,player1.y + player1.height//2,6,black,facing))   ##just like calling upon a function




    ## level


    gameDisplay.fill((0,255,0))        ### will stop the shape from spreading around and will have a background
    pygame.draw.rect(gameDisplay,(red),(player1.x,player1.y,player1.width,player1.height))  ## draw player
    pygame.display.update()
    redrawGameWindow()

pygame.quit()

Когда я стреляю более чем в одну пулю, и я хочу, чтобы только одна пуля стреляла за раз (но не только одна пуля на экране), они все стреляют в большой комок и тоже склеиваются, поэтому я хочу их чтобы стрелять в разное время, я пытался использовать задержку clock.tick, но это делает игру крайне медленной

Я относительно новичок в Pygame и не до конца понимаю, что любая помощь будет оценена, спасибо!

1 Ответ

1 голос
/ 08 февраля 2020

Состояния, которые возвращаются pygame.key.get_pressed(), устанавливаются, пока нажата клавиша. Это полезно для движения игрока. Игрок продолжает двигаться, пока нажата клавиша.
Но это противоречит вашим намерениям, когда вы хотите выстрелить. Если вы хотите запустить пулю при нажатии клавиши, то можете использовать событие KEYDOWN. Событие происходит только один раз при нажатии клавиши:

while run == True:
    clock.tick(27)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE: 
                if player1.left == True:   ## handles the direction of the bullet
                    facing = -1
                else:
                    facing = 1  
                if len(bullets) < 5:    ## max amounts of bullets on screen
                    bx, by = player1.x + player1.width //2 ,player1.y + player1.height//2
                    bullets.append(projectile(bx, by, 6, black, facing))

    # [...]

Если вы хотите реализовать какой-то быстрый огонь, то все становится сложнее. Если бы вы использовали состояние pygame.key.get_pressed(), то вы бы порождали одну пулю в каждом кадре. Это слишком быстро. Вы должны реализовать некоторый тайм-аут.
Когда пуля запускается, получить текущее время на pygame.time.get_ticks(). Определите количество миллисекунд для задержки между пулями. Добавьте dela к времени и укажите время в переменной (next_bullet_threshold). Пропускать маркеры, пока время не превышено:

next_bullet_threshold = 0

run = True
while run == True:

    # [...]

    current_time = pygame.time.get_ticks()
    if keys[pygame.K_SPACE] and current_time > next_bullet_threshold:

        bullet_delay = 500 # 500 milliseconds (0.5 seconds)
        next_bullet_threshold = current_time + bullet_delay

        if player1.left == True:   ## handles the direction of the bullet
            facing = -1
        else:
            facing = 1  
        if len(bullets) < 5:
            bx, by = player1.x + player1.width //2 ,player1.y + player1.height//2
            bullets.append(projectile(bx, by, 6, black, facing))

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