"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > 파이게임에서 동시 총알 발사를 방지하는 방법은 무엇입니까?

파이게임에서 동시 총알 발사를 방지하는 방법은 무엇입니까?

2024-11-03에 게시됨
검색:129

How to Prevent Simultaneous Bullet Firing in Pygame?

한 번에 두 개 이상의 총알이 발사되는 것을 어떻게 막을 수 있나요?

Pygame에서 플레이어가 발사할 때 목록에 여러 개의 총알을 추가하려면 Append() 메서드를 사용하세요. 사격은 모든 총알이 동시에 발사되도록 합니다. 이를 방지하려면 총알 발사 간격을 조정하는 타이머를 구현하십시오.

다음은 타이머를 통합한 수정된 코드 버전입니다.

import pygame
pygame.init()

# Game settings
screenWidth = 800
screenHeight = 600
clock = pygame.time.Clock()
# Bullet settings
bullet_delay = 500 # Time in milliseconds between shots
next_bullet = 0 # Time of next bullet

# Player settings
player1 = pygame.sprite.Sprite()
player1.image = pygame.Surface((50, 50))
player1.image.fill((255, 0, 0))
player1.rect = player1.image.get_rect()
player1.rect.center = (screenWidth / 2, screenHeight / 2)

# Group to hold all bullets
bullets = pygame.sprite.Group()

# Game loop
run = True
while run:
    clock.tick(30)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                # Check if enough time has passed since last shot
                current_time = pygame.time.get_ticks()
                if current_time >= next_bullet:
                    # Create a new bullet
                    bullet = pygame.sprite.Sprite()
                    bullet.image = pygame.Surface((10, 10))
                    bullet.image.fill((0, 0, 0))
                    bullet.rect = bullet.image.get_rect()
                    bullet.rect.center = player1.rect.center
                    # Add bullet to group
                    bullets.add(bullet)
                    # Reset next bullet time
                    next_bullet = current_time   bullet_delay

    # Update game objects
    player1.update()
    bullets.update()

    # Handle bullet movement
    for bullet in bullets:
        bullet.rect.y -= 5 # Change to desired bullet speed

        # Remove any bullets that have moved off the screen
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)

    # Draw objects on the screen
    screen.fill((0, 0, 0))
    screen.blit(player1.image, player1.rect)
    bullets.draw(screen)

    # Update the display
    pygame.display.update()

pygame.quit()

이 수정된 코드에서 bullet_delay는 발사 사이의 지연을 결정하고 next_bullet은 다음 허용되는 발사 시간을 추적합니다. 플레이어가 스페이스바를 누르면 마지막 샷 이후 충분한 시간이 지났는지 확인합니다(next_bullet 기준). 그렇다면 글머리 기호가 생성되어 글머리 기호 그룹에 추가됩니다. 이 타이머는 bullet_delay에 지정된 지연을 사용하여 한 번에 하나의 총알만 발사할 수 있도록 보장합니다.

릴리스 선언문 이 글은 1729463900에서 재인쇄되었습니다. 침해 내용이 있는 경우, [email protected]으로 연락하여 삭제하시기 바랍니다.
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3