修改第七章的AlienDirection程序,不允许图像移出窗口的可视区域。忽略引起图像位置越界的键盘事件。
时间: 2024-03-23 20:40:26 浏览: 22
好的,以下是修改后的AlienDirection程序代码:
```python
import sys
import pygame
def check_events(alien, screen):
"""响应按键和鼠标事件"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
alien.rect.centery -= 10
elif event.key == pygame.K_DOWN:
alien.rect.centery += 10
elif event.key == pygame.K_LEFT:
alien.rect.centerx -= 10
elif event.key == pygame.K_RIGHT:
alien.rect.centerx += 10
# 限制图像移动范围
if alien.rect.top < 0:
alien.rect.top = 0
if alien.rect.bottom > screen.get_rect().bottom:
alien.rect.bottom = screen.get_rect().bottom
if alien.rect.left < 0:
alien.rect.left = 0
if alien.rect.right > screen.get_rect().right:
alien.rect.right = screen.get_rect().right
def update_screen(ai_settings, screen, alien):
"""更新屏幕上的图像,并切换到新屏幕"""
# 每次循环时都重新绘制屏幕
screen.fill(ai_settings.bg_color)
alien.blitme()
# 让最近绘制的屏幕可见
pygame.display.flip()
def run_game():
# 初始化游戏并创建一个屏幕对象
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode(
(ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_caption("Alien Direction")
# 创建一个外星人
alien = Alien(ai_settings, screen)
# 开始游戏的主循环
while True:
check_events(alien, screen)
update_screen(ai_settings, screen, alien)
run_game()
```
在原来的基础上,我们加入了限制图像移动范围的代码。具体来说,我们判断了外星人图像的上、下、左、右四个边界,如果超出了屏幕的可视区域,就将其移回到边界。这样就可以防止图像移出窗口的可视区域了。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![ipynb](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)