赞
踩
#于是考虑能否在这个基础上进行一些小小的改进
我发现在射击的部分还存在一定的缺憾,想要快速地射击外星人,依靠每次按下发射一颗子弹有些费手,于是考虑实现长按空格键进行射击,网上搜索了一下没有这么实现的代码,而利用pygame.key.set_repeat() 也无法准确实现,反而影响正常射击。
于是考虑与移动相似的方法设定一个flag来判断目前的射击状态
首先在ship.py中添加了一个flag:self.shooting, 用以判断射击状态。
- # Movement flags.
- self.moving_right = False
- self.moving_left = False
- self.shooting = False
接着对game_function.py进行修改。
- ##原代码##
- def check_keydown_events(event, ai_settings, screen, ship, bullets):
- """Respond to keypresses."""
- 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:
- fire_bullet(ai_settings, screen, ship, bullets)
- elif event.key == pygame.K_q:
- sys.exit()
-
- def check_keyup_events(event, ship):
- """Respond to key releases."""
- if event.key == pygame.K_RIGHT:
- ship.moving_right = False
- elif event.key == pygame.K_LEFT:
- ship.moving_left = False
将flag加入其中:
- def check_keydown_events(event, ai_settings, screen, ship, bullets):
- """Respond to keypresses."""
- 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.shooting = True
- # fire_bullet(ai_settings, screen, ship, bullets)
- elif event.key == pygame.K_q:
- sys.exit()
-
- def check_keyup_events(event, ship):
- """Respond to key releases."""
- 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.shooting = False
if ship.shooting: gf.fire_bullet(ai_settings, screen, ship, bullets)定义后就可以在主函数中进行调用了,即 可以实现连续射击
- while True:
-
- clock.tick(250)
- gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
- aliens, bullets)
-
- if stats.game_active:
- if ship.shooting:
- gf.fire_bullet(ai_settings, screen, ship, bullets)
- ship.update()
- gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
- bullets)
- gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
- bullets)
-
- --snip--
-
但是这样在主代码中显得有些臃肿,于是再进行修改。将if shooting放入fire_bullet()中。
def fire_bullet(ai_settings, screen, ship, bullets): """Fire a bullet, if limit not reached yet.""" # Create a new bullet, add to bullets group. if len(bullets) < ai_settings.bullets_allowed and ship.shooting: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet)
这样主代码变为:
- --snip--
-
- if stats.game_active:
- gf.fire_bullet(ai_settings, screen, ship, bullets)
- ship.update()
-
- --snip--
目前基本实现了预期目的,感觉还可以再精进一下.......
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。