python - 我如何停止一次发射超过 1 颗子弹?

标签 python pygame pygame-tick

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()

当我发射超过 1 发子弹并且我只想一次发射 1 发子弹(但屏幕上不仅只有 1 发子弹) 它们都以大块的形式开火并粘在一起,所以我希望它们在不同的时间开火 我曾尝试使用延迟 clock.tick 但这会使游戏非常滞后

我对 pygame 比较陌生,不完全理解它,任何帮助将不胜感激!

最佳答案

发射子弹的一般方法是将子弹的位置存储在列表中 (bullet_list)。发射子弹时,将子弹的起始位置 ([start_x, start_y]) 添加到列表中。起始位置是发射子弹的物体(玩家或敌人)的位置。使用 for 循环遍历列表中的所有项目符号。移动循环中每个项目符号的位置。从列表中删除离开屏幕的项目符号 (bullet_list.remove(bullet_pos))。出于这个原因,必须遍历列表 (bullet_list[:]) 的副本(参见 How to remove items from a list while iterating? )。使用另一个 for 循环来 blit 屏幕上剩余的项目符号:

bullet_list = []

while run == True:
    # [...]

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

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                bullet_list.append([start_x, start_y])

    for bullet_pos in bullet_list[:]:
        bullet_pos[0] += move_bullet_x
        bullet_pos[1] += move_bullet_y
        if not screen.get_rect().colliderect(bullet_image.get_rect(center = bullet_pos))
            bullet_list.remove(bullet_pos)

    # [...]

    for bullet_pos in bullet_list[:]
        screen.blit(bullet_image, bullet_image.get_rect(center = bullet_pos))

    # [...]

另见 Shoot bullet .


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() 获取当前时间.为项目符号之间的延迟定义毫秒数。将延迟添加到时间并在变量中声明时间 (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))

最小示例: repl.it/@Rabbid76/PyGame-ShootBullet

import pygame
pygame.init()

window = pygame.display.set_mode((500, 200))
clock = pygame.time.Clock()

tank_surf = pygame.Surface((60, 40), pygame.SRCALPHA)
pygame.draw.rect(tank_surf, (0, 96, 0), (0, 00, 50, 40))
pygame.draw.rect(tank_surf, (0, 128, 0), (10, 10, 30, 20))
pygame.draw.rect(tank_surf, (32, 32, 96), (20, 16, 40, 8))
tank_rect = tank_surf.get_rect(midleft = (20, window.get_height() // 2))

bullet_surf = pygame.Surface((10, 10), pygame.SRCALPHA)
pygame.draw.circle(bullet_surf, (64, 64, 62), bullet_surf.get_rect().center, bullet_surf.get_width() // 2)
bullet_list = []
max_bullets = 4
next_bullet_time = 0
bullet_delta_time = 200 # milliseconds

run = True
while run:
    clock.tick(60)
    current_time = pygame.time.get_ticks()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

        if event.type == pygame.KEYDOWN:
            if len(bullet_list) < max_bullets and current_time >= next_bullet_time:
                next_bullet_time = current_time + bullet_delta_time
                bullet_list.insert(0, tank_rect.midright)

    for i, bullet_pos in enumerate(bullet_list):
        bullet_list[i] = bullet_pos[0] + 5, bullet_pos[1]
        if bullet_surf.get_rect(center = bullet_pos).left > window.get_width():
            del bullet_list[i:]
            break

    window.fill((224, 192, 160))
    window.blit(tank_surf, tank_rect)
    for bullet_pos in bullet_list:
        window.blit(bullet_surf, bullet_surf.get_rect(center = bullet_pos))
    pygame.display.flip()

pygame.quit()
exit()

关于python - 我如何停止一次发射超过 1 颗子弹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60122492/

相关文章:

python - 如何在 Tkinter 中使用列表框打开文本文件

python - 如何在pygame中更改圆形 Sprite 碰撞框的大小

python - Pygame 类型错误 : missing 1 required positional argument:

python - Pygame 在点击之间重置计时器

python - 帧率影响游戏速度

python - 我可以将函数作为参数发送到具有多处理功能的所有进程吗?

python - 如何在ffmpeg中使用字节而不是文件路径?

python - PyQt 菜单栏 Mac OSX 雪豹

python - 如何让屏幕随着pygame中的角色移动?