過剰な弾丸の発射を防ぐためのクールダウンメカニズムを実装するにはどうすればよいですか?

Susan Sarandon
リリース: 2024-10-21 06:38:30
オリジナル
948 人が閲覧しました

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

複数の弾丸の同時発射を防ぐ方法

元のコードでは、pygame が原因で複数の弾丸が同時に発射されていました。 .key.get_pressed() 関数は、キーが押されている限り True を返します。この動作は、プレイヤーの動きを制御するのには適していますが、キーを押すたびに 1 つの弾丸だけを発射したい場合の弾丸の発射には適していません。

この問題を解決するには、pygame.KEYDOWN を利用できます。このイベントは、キーが最初に押されたときに 1 回だけ発生します。 pygame.key.get_pressed() の代わりにこのイベントを使用することで、スペースバーが押されたときに弾丸が 1 つだけ発射されるようにすることができます。

さらに、弾丸の連射を防ぐための簡単なクールダウン メカニズムを実装できます。射撃。これは、次の弾丸を発射できる最も早い時間を表す 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 中国語 Web サイトの他の関連記事を参照してください。

ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!