python设计飞机大战小游戏 gui
时间: 2023-09-14 09:14:05 浏览: 99
好的,下面是一个简单的飞机大战小游戏的GUI设计:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 创建游戏窗口
screen = pygame.display.set_mode((480, 700))
# 加载背景图片
bg = pygame.image.load("images/background.png")
# 加载游戏结束图片
gameover = pygame.image.load("images/gameover.png")
# 加载玩家飞机图片
player_img = pygame.image.load("images/me1.png")
player_rect = player_img.get_rect()
player_rect.centerx = 240
player_rect.bottom = 680
# 加载敌机图片
enemy_img1 = pygame.image.load("images/e1.png")
enemy_img2 = pygame.image.load("images/e2.png")
enemy_img3 = pygame.image.load("images/e3.png")
enemy_imgs = [enemy_img1, enemy_img2, enemy_img3]
# 定义敌机列表
enemies = []
# 定义敌机出现时间间隔
enemy_interval = 120
# 定义计分
score = 0
font = pygame.font.Font(None, 36)
# 游戏主循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 绘制背景
screen.blit(bg, (0, 0))
# 移动玩家飞机
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player_rect.left > 0:
player_rect.move_ip(-5, 0)
if keys[pygame.K_RIGHT] and player_rect.right < 480:
player_rect.move_ip(5, 0)
if keys[pygame.K_UP] and player_rect.top > 0:
player_rect.move_ip(0, -5)
if keys[pygame.K_DOWN] and player_rect.bottom < 680:
player_rect.move_ip(0, 5)
# 绘制玩家飞机
screen.blit(player_img, player_rect)
# 生成敌机
if enemy_interval == 0:
enemy_img = random.choice(enemy_imgs)
enemy_rect = enemy_img.get_rect()
enemy_rect.left = random.randint(0, 480 - enemy_rect.width)
enemy_rect.top = -enemy_rect.height
enemies.append(enemy_rect)
enemy_interval = 120 - score // 10 * 10
if enemy_interval < 60:
enemy_interval = 60
else:
enemy_interval -= 1
# 移动敌机
for enemy_rect in enemies:
enemy_rect.move_ip(0, 5)
if enemy_rect.top > 700:
enemies.remove(enemy_rect)
# 绘制敌机
for enemy_rect in enemies:
screen.blit(enemy_img, enemy_rect)
# 碰撞检测
for enemy_rect in enemies:
if player_rect.colliderect(enemy_rect):
running = False
# 统计得分
for enemy_rect in enemies:
if enemy_rect.bottom >= 700:
score += 1
enemies.remove(enemy_rect)
# 绘制得分
score_text = font.render("Score: " + str(score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
# 更新屏幕
pygame.display.update()
# 游戏结束
screen.blit(gameover, (0, 0))
pygame.display.update()
pygame.time.delay(2000)
# 退出pygame
pygame.quit()
```
上述代码实现了一个简单的飞机大战小游戏,其中使用pygame库实现GUI界面设计,实现了玩家飞机的移动、敌机的生成和移动、碰撞检测、得分统计等功能。
阅读全文