또 다른 문제는 총알이 화면 상단에 도달했을 때 촬영 루프를 깨뜨릴 수 없다는 것이 었습니다. 원래 코드는 무한히 계속 된 while 루프를 사용했습니다. 이 문제를 해결하려면 총알이 최상위에 도달했는지 확인하는 조건이있는 while 루프를 사용해야합니다.
코드의 수정 된 버전은 다음과 같습니다.
[
키 변경 :
import pygame, os
# Boilerplate setup omitted for brevity
class Player:
def __init__(self, x, y, height, width):
...
def draw(self):
...
def move_left(self):
...
def move_right(self):
...
class Bullet:
def __init__(self, x, y):
...
def update(self):
...
def draw(self):
...
# Lists of bullets
bullets = []
# Initialize player
p = Player(600, 500, 50, 30)
# Main game loop
run = True
while run:
clock.tick(100)
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bullets.append(Bullet(p.x p.width//2, p.y))
# Update objects
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
p.move_left()
if keys[pygame.K_RIGHT]:
p.move_right()
for b in bullets:
b.update()
# Update position and remove bullet if it goes off-screen
if b.y < 0:
bullets.remove(b)
# Update frame
d.fill((98, 98, 98))
for b in bullets:
b.draw()
p.draw()
win.update()
촬영 및 플레이어 움직임 로직은 이제 단일 기본 게임 루프로 결합되었습니다. 총알이 화면 밖으로 나갔는지 확인하고 그에 따라 제거합니다. 부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3