经过我为期一周的开发与完善,现在我正式宣布Space War1.0已经完成了
现在网上能找到的那些飞机大战都是飞机只能左右移动,子弹只能向上发射的无聊版本。
而这一款Space War1.0则与之截然不同。飞机选择了歼16的图片(因为我喜欢歼16),而且机头能跟随鼠标以固定角速度旋转,飞机能上下左右全屏移动,且有微微的加速减速使移动操作更为丝滑。子弹呈长条形,按鼠标左键从机头射出,且子弹角度与飞机一致,弹夹打空后过三秒会自动填满。敌机对象是红色正方形,可以用子弹摧毁或用飞机撞毁(但会使自己收到敌机剩余血量的伤害),若摧毁所有敌机之后,则显示胜利,自身血量为零则显示失败。在游戏开始前,按P键开始,期间仍可用P键实现暂停。按C键退出游戏,当然也可直接叉掉界面以关闭游戏。在游戏胜利或失败后可以按O键重新开始。
Space War1.0 2024-07-14
话不多说,先给代码和资源文件,自己体验吧。之后我会慢慢更新这篇文章,分模块对代码进行解析。(资源文件在最下面)
# -*- coding: utf-8 -*-
"""
Created on Tue May 7 15:33:31 2024
@author: yq1215
"""
import pygame
import sys
import math
import time
import random
from pygame.locals import *
import winsound
#定义Bullet(子弹)类
class Bullet(pygame.sprite.Sprite):
def __init__(self, screen, x, y, angle, damage):
pygame.sprite.Sprite.__init__(self)
#self.image = self.image1 = pygame.Surface((10, 1)) # 用一个简单的矩形代替子弹图片
#self.image.fill((255, 255, 0)) # 设置为黄色
self.image = self.image1 = pygame.image.load("bullet.png")
self.rect = self.image.get_rect()
self.rect.center = (x, y)
self.screen = screen
self.angle = angle
self.image = pygame.transform.rotate(self.image1,self.angle)
self.rect = self.image.get_rect(center=self.rect.center)
self.vel = 15
self.x = x
self.y = y
self.damage = damage
def display(self): #显示子弹图片的方法
self.screen.blit(self.image, (self.x, self.y)) #将创建的子弹图片按设定的坐标贴到窗口中
def move(self): #子弹移动方法
self.x += self.vel*math.cos(math.radians(self.angle))
self.y -= self.vel*math.sin(math.radians(self.angle))
def judge(self): #判断子弹是否出界
if self.y<0 or self.y>1200 or self.x<0 or self.x>1800:
return True
else:
return False
def judge1(self, enemy_list): #判断子弹是否击中敌机
flag = False
for enemy in enemy_list:
if (self.x>enemy.rect.centerx-10 and
self.x<enemy.rect.centerx+10 and
self.y>enemy.rect.centery-10 and
self.y<enemy.rect.centery+10):
winsound.Beep(500,1)
enemy.health -= self.damage
flag = True
return flag
#定义Plane(飞机)类
class Plane(pygame.sprite.Sprite):
def __init__(self, screen, image, x, y, max_health, max_bullet):
pygame.sprite.Sprite.__init__(self)
self.image = image
self.image1 = self.image #保留原图
self.rect = self.image.get_rect()
self.rect.topleft = (x, y)
self.screen = screen
self.score = 0 #当前得分
self.acceleration = 0.2
self.max_speed = 8
self.vel_x = 0
self.vel_y = 0
self.angular_speed = 2 #角速度
self.current_angle = 0
self.max_health = max_health
self.health = max_health # 初始生命值等于最大生命值
self.health_bar = HealthBar(screen, 300, 80, 200, 20, max_health) # 创建血条对象
self.bullet_list = [] #存储发射出去的