鼠标移动控制飞机,点击发射子弹
# -*- coding: utf-8 -*-
import pygame
import random
pygame.init()
screen = pygame.display.set_mode((480, 700))
pygame.display.set_caption("飞机大战")
# 加载图片(需要准备)
player = pygame.image.load('player.png')
enemy = pygame.image.load('enemy.png')
bullet = pygame.image.load('bullet.png')
# 玩家飞机
player_rect = pygame.Rect(200, 500, 50, 50)
# 敌机组
enemies = []
bullets = []
score = 0
clock = pygame.time.Clock()
running = True
while running:
clock.tick(60)
screen.fill((0, 0, 0))
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
# 发射子弹
bullet_rect = pygame.Rect(player_rect.centerx - 5, player_rect.top, 10, 20)
bullets.append(bullet_rect)
# 玩家移动(鼠标)
player_rect.centerx = pygame.mouse.get_pos()[0]
# 生成敌机
if random.randint(0, 50) == 0:
enemy_rect = pygame.Rect(random.randint(0, 400), -50, 50, 50)
enemies.append(enemy_rect)
# 移动子弹
for bullet in bullets[:]:
bullet.y -= 10
if bullet.y < 0: bullets.remove(bullet)
# 移动敌机
for enemy in enemies[:]:
enemy.y += 5
if enemy.y > 700: enemies.remove(enemy)
# 碰撞检测
# ... (简化版)
screen.blit(player, player_rect)
pygame.display.update()
pygame.quit()
pip install pygamepython plane.py