>  기사  >  백엔드 개발  >  과도한 총알 발사를 방지하기 위해 쿨다운 메커니즘을 구현하는 방법은 무엇입니까?

과도한 총알 발사를 방지하기 위해 쿨다운 메커니즘을 구현하는 방법은 무엇입니까?

Susan Sarandon
Susan Sarandon원래의
2024-10-21 06:38:30950검색

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

다발 총알 동시 발사 방지 방법

원래 코드에서는 파이게임이 여러 발의 총알을 동시에 발사하고 있었습니다. .key.get_pressed() 함수는 키를 누르고 있는 동안 True를 반환합니다. 이 동작은 플레이어의 움직임을 제어하는 ​​데 적합하지만, 키를 누를 때마다 하나의 총알만 발사하려는 총알 발사에는 적합하지 않습니다.

이 문제를 해결하려면 파이게임을 활용할 수 있습니다.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으로 문의하세요.