1. 程式人生 > 實用技巧 >Python外星人入侵專案-重構程式碼,使得空格鍵按下後可以連續發射子彈

Python外星人入侵專案-重構程式碼,使得空格鍵按下後可以連續發射子彈

1,首先在ship

class Ship():

def __init__(self, ai_settings, screen):
"""初始化飛船並設定其初始位置"""
--snip--

# 空格和發射標誌
self.space = False
self.bullets_fire = True

2,首先重構程式碼,判斷空格鍵按下和放開狀態

def check_events(ship):
"""響應按鍵和滑鼠事件"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()

elif event.type == pygame.KEYDOWN:
check_keydown_events(event, ship)

elif event.type == pygame.KEYUP:
check_keyup_events(event, ship)

def check_keydown_events(event, ship):
"""響應按鍵"""
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
elif event.key == pygame.K_SPACE:
ship.space = True # 增加判斷空格鍵響應


def check_keyup_events(event, ship):
"""響應鬆開"""
if event.key == pygame.K_RIGHT:
ship.moving_right = False
elif event.key == pygame.K_LEFT:
ship.moving_left = False
elif event.key == pygame.K_SPACE:
ship.space = False # 增加判斷空格鍵響應

3,重構fire_bullet增加開關判斷,增加子彈位置判斷(由於沒找到其他好的方法,只能通過子彈畫素位置判斷)
def fire_bullet(ai_settings, screen, ship, bullets):
if len(bullets) < ai_settings.bullets_allowed and ship.space and ship.bullets_fire: # 這裡加了開火開關
new_bullet = Bullet(ai_settings, screen, ship)
bullets.add(new_bullet)
def update_bullets(ai_settings, screen, ship, bullets, fire_speed):
bullets.update()
fire = 0 # 設定標誌
fire_bullet(ai_settings, screen, ship, bullets)
for bullet in bullets.copy():
if bullet.rect.bottom >= fire_speed:
fire += 1 # 這裡的fire_speed值是700,如果有子彈y值大於700,則修改fire值+1
if fire > 0: # 判斷fire值,相當於開關
ship.bullets_fire = False
else:
ship.bullets_fire = True # True則開火
for bullet in bullets.copy():
if bullet.rect.bottom <= 0:
bullets.remove(bullet)

4,如果update_bullets不傳形參fire_speed的話,直接在if中輸入數值
# 開始遊戲的主迴圈
while True:
# 開始遊戲主迴圈
gf.check_events(ship)
ship.update()
gf.update_bullets(ai_settings, screen, ship, bullets, ai_settings.bullet_fire_speed)
gf.update_screen(ai_settings, screen, ship, bullets)

這是比較笨的方法,新手勿噴。
另外求教 bullets.copy怎麼能獲取到最近發射的bullet 屬性?這個不是列表,嘗試了會有報錯。