python外星人入侵小游戏代码
时间: 2023-09-04 22:13:12 浏览: 134
外星人入侵python游戏代码
以下是一个简单的 Python 外星人入侵小游戏的代码:
```python
import pygame
import random
# 初始化 pygame
pygame.init()
# 设置游戏窗口
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置游戏标题
pygame.display.set_caption("Alien Invasion")
# 加载游戏背景
background_image = pygame.image.load("background.png")
# 加载玩家飞船
player_image = pygame.image.load("player.png")
player_width = player_image.get_width()
player_height = player_image.get_height()
player_x = (screen_width - player_width) // 2
player_y = screen_height - player_height - 10
# 加载外星人
alien_image = pygame.image.load("alien.png")
alien_width = alien_image.get_width()
alien_height = alien_image.get_height()
alien_x = random.randint(0, screen_width - alien_width)
alien_y = 0
alien_speed = 5
# 设置游戏循环
running = True
while running:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 绘制游戏背景
screen.blit(background_image, (0, 0))
# 移动玩家飞船
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player_x > 0:
player_x -= 5
if keys[pygame.K_RIGHT] and player_x < screen_width - player_width:
player_x += 5
if keys[pygame.K_UP] and player_y > 0:
player_y -= 5
if keys[pygame.K_DOWN] and player_y < screen_height - player_height:
player_y += 5
# 绘制玩家飞船和外星人
screen.blit(player_image, (player_x, player_y))
screen.blit(alien_image, (alien_x, alien_y))
# 移动外星人
alien_y += alien_speed
if alien_y > screen_height:
alien_x = random.randint(0, screen_width - alien_width)
alien_y = 0
# 检测玩家和外星人是否相撞
if player_x < alien_x + alien_width and player_x + player_width > alien_x and player_y < alien_y + alien_height and player_y + player_height > alien_y:
running = False
# 刷新屏幕
pygame.display.flip()
# 结束游戏
pygame.quit()
```
在运行游戏之前,需要先准备好游戏所需的图片,并将其命名为 `background.png`、`player.png` 和 `alien.png`,并与代码文件放在同一个目录下。
阅读全文