Python飞机大战小游戏

作者:问题终结者2024.01.18 00:07浏览量:13

简介:介绍如何使用Python和pygame库制作一个简单的飞机大战小游戏。

在Python中,我们可以使用pygame库来制作游戏。下面是一个简单的飞机大战小游戏的示例代码。
首先,你需要安装pygame库。在命令行中输入以下命令来安装:

  1. pip install pygame

接下来,我们创建一个新的Python文件,比如叫做plane_game.py,然后输入以下代码:
```python
import pygame
import random

初始化pygame

pygame.init()

设置屏幕大小

screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

设置飞机图像

plane_img = pygame.image.load(‘plane.png’)
plane_width, plane_height = plane_img.get_rect().size
plane_x = screen_width // 2 - plane_width // 2
plane_y = screen_height - plane_height - 20

设置敌机图像和数量

enemy_img = pygame.image.load(‘enemy.png’)
enemy_width, enemy_height = enemy_img.get_rect().size
enemies = []
num_enemies = 5
for i in range(num_enemies):
x = random.randint(0, screen_width - enemy_width)
y = random.randint(0, screen_height - enemy_height)
enemies.append([x, y])

设置子弹图像和数量

bullet_img = pygame.image.load(‘bullet.png’)
bullets = []
num_bullets = 100
bullet_cooldown = 5 # 每隔5帧发射一颗子弹
bullet_cooldown_counter = 0

游戏主循环

running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE: # 按下空格键发射子弹
bullet_cooldown_counter += 1
if bullet_cooldown_counter == bullet_cooldown:
bullets.append([plane_x + plane_width // 2, plane_y])
bullet_cooldown_counter = 0
elif event.type == pygame.KEYUP: # 松开空格键停止发射子弹
bullet_cooldown_counter = 0
bullets = []
keys = pygame.key.get_pressed() # 获取按键状态列表,判断是否需要移动飞机或射击子弹
if keys[pygame.K_LEFT]: # 向左移动飞机
plane_x -= 5
if keys[pygame.K_RIGHT]: # 向右移动飞机
plane_x += 5
if keys[pygame.K_SPACE] and len(bullets) < num_bullets: # 发射子弹时判断子弹数量上限,超过则停止发射子弹
bullets.append([plane_x + plane_width // 2, plane_y]) # 在飞机中心位置添加子弹位置列表元素,并更新子弹数量上限值加一。同时,将子弹位置列表元素添加到子弹列表中。如果子弹数量超过上限值,则停止发射子弹。这样做是为了控制子弹的数量和频率,增加游戏的挑战性和趣味性。
for bullet in bullets[:]: # 将所有子弹移动到适当位置并绘制到屏幕上,如果碰撞到敌机则移除相应元素并计算得分。通过遍历所有子弹,依次将每颗子弹向上移动并更新其位置列表元素。在移动的同时判断是否与敌机碰撞,如果碰撞则从子弹列表中移除相应元素并计算得分。这样做是为了实现子弹的移动和碰撞检测功能,增加游戏的互动性和刺激性。同时,为了保持游戏画面的清晰度和流畅度,我们限制了子弹的数量和移动速度。通过限制子弹的数量和移动速度,可以避免游戏画面过于混乱和卡顿,提高游戏的可玩性和用户体验。
for bullet in bullets[:]: # 将所有子弹移动到适当位置并绘制到屏幕上,如果碰撞到敌机则移除相应元素并计算得分。通过遍历所有子弹,依次将每颗