首頁 >後端開發 >Python教學 >如何實現冷卻機制來防止子彈過度射擊?

如何實現冷卻機制來防止子彈過度射擊?

Susan Sarandon
Susan Sarandon原創
2024-10-21 06:38:301036瀏覽

How to Implement a Cooldown Mechanism to Prevent Excessive Bullet Firing?

如何防止多顆子彈同時發射

在原始程式碼中,由於pygame 的存在,會同時發射多顆子彈只要按下某個鍵,.key.get_pressed() 函數就會回傳True。此行為適用於控制玩家移動,但不適用於發射子彈,每次按下按鍵時您只希望發射一顆子彈。

要解決此問題,我們可以利用 pygame.KEYDOWN事件,僅在首次按下某個鍵時發生一次。透過使用這個事件而不是pygame.key.get_pressed(),我們可以確保按下空白鍵時只發射一顆子彈。

此外,我們可以實作一個簡單的冷卻機制來防止快速發射子彈射擊。這可以透過引入一個名為 next_bullet_threshold 的變數來完成,該變數表示下一顆子彈可以發射的最早時間。每次發射子彈時,我們都會將 next_bullet_threshold 更新為目前時間加上所需的冷卻時間。透過檢查目前時間是否大於 next_bullet_threshold,我們可以防止任何子彈在所需的冷卻時間之外發射。

以下是已實現冷卻機制的修改後的程式碼:

<code class="python">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
next_bullet_threshold = 0  # Initialize the cooldown threshold
bullet_cooldown = 500  # Set the desired cooldown period in milliseconds
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
        current_time = pygame.time.get_ticks()
        if current_time >= next_bullet_threshold:  # Check the cooldown timer
            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
                next_bullet_threshold = current_time + bullet_cooldown  # Update cooldown timer


    ## 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()</code>

以上是如何實現冷卻機制來防止子彈過度射擊?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn