帮我生成一个python的飞机大战游戏
时间: 2023-07-25 13:52:35 浏览: 75
用Python写一个飞机大战小游戏
3星 · 编辑精心推荐
好的,这里提供一个简单的飞机大战游戏的Python代码,你可以在此基础上进行修改和完善:
```python
import pygame
import random
# 初始化
pygame.init()
# 设置游戏窗口大小
screen = pygame.display.set_mode((480, 800))
# 设置游戏标题
pygame.display.set_caption("飞机大战")
# 加载图片
bg = pygame.image.load("images/background.png")
hero = pygame.image.load("images/hero.png")
enemy1 = pygame.image.load("images/enemy1.png")
enemy2 = pygame.image.load("images/enemy2.png")
enemy3 = pygame.image.load("images/enemy3.png")
bullet = pygame.image.load("images/bullet.png")
# 设置字体
font = pygame.font.Font(None, 36)
# 设置游戏变量
score = 0
hero_x = 200
hero_y = 600
hero_speed = 5
enemy_list = []
bullet_list = []
# 设置敌机类
class Enemy():
def __init__(self, img, speed):
self.img = img
self.speed = speed
self.width = self.img.get_rect().width
self.height = self.img.get_rect().height
self.x = random.randint(0, 480 - self.width)
self.y = -self.height
def move(self):
self.y += self.speed
def draw(self):
screen.blit(self.img, (self.x, self.y))
# 设置子弹类
class Bullet():
def __init__(self, img, speed):
self.img = img
self.speed = speed
self.width = self.img.get_rect().width
self.height = self.img.get_rect().height
self.x = hero_x + hero.get_rect().width / 2 - self.width / 2
self.y = hero_y - self.height
def move(self):
self.y -= self.speed
def draw(self):
screen.blit(self.img, (self.x, self.y))
# 设置主循环
while True:
# 绘制背景
screen.blit(bg, (0, 0))
# 绘制分数
text = font.render("Score: %d" % score, True, (255, 255, 255))
screen.blit(text, (0, 0))
# 绘制英雄
screen.blit(hero, (hero_x, hero_y))
# 绘制敌机
for enemy in enemy_list:
enemy.move()
enemy.draw()
if enemy.y > 800:
enemy_list.remove(enemy)
score += 1
# 绘制子弹
for bullet in bullet_list:
bullet.move()
bullet.draw()
if bullet.y < 0:
bullet_list.remove(bullet)
# 控制英雄移动
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and hero_x > 0:
hero_x -= hero_speed
if keys[pygame.K_RIGHT] and hero_x < 480 - hero.get_rect().width:
hero_x += hero_speed
# 控制子弹发射
if keys[pygame.K_SPACE]:
bullet_list.append(Bullet(bullet, 10))
# 控制敌机生成
if random.randint(0, 100) < 3:
enemy_type = random.randint(1, 3)
if enemy_type == 1:
enemy_list.append(Enemy(enemy1, random.randint(1, 3)))
elif enemy_type == 2:
enemy_list.append(Enemy(enemy2, random.randint(1, 3)))
elif enemy_type == 3:
enemy_list.append(Enemy(enemy3, random.randint(1, 3)))
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# 刷新屏幕
pygame.display.update()
```
你可以将这段代码保存为一个Python文件,然后将所需的图片放在`images`文件夹下运行。注意:本代码并不包含游戏结束和游戏暂停等功能,需要自己添加。
阅读全文