目录
最好的学习方法是学习别人的代码,加上自己以前比较喜欢雷电这款游戏,所以就从飞机大战入手了,从网上下的源代码和图片素材,先上源代码,代码所有权归原作者。
一、源代码
import pygame
from pygame.locals import *
from sys import exit
import time
import random
#创建子弹类,把子弹的图片转化为图像对象,设定固定的移动速度
class Bullet():
def __init__(self,bulletfilename,bulletpos): #定义初始化,参数是图的文件名和位置
self.bulletimg = pygame.image.load(bulletfilename) #图像
self.bullet_rect = self.bulletimg.get_rect()#获得rect
self.bullet_image = self.bulletimg.subsurface(self.bullet_rect) #生成subsurface对象
self.bullet_rect.midbottom = bulletpos #设置rect位置
self.speed = 2 #设置子弹速度
def move(self):
self.bullet_rect.top -= self.speed #子弹的运动是不断的以速度值大小减小
# 创建玩家飞机类,用面向对象的思想来对待
class play_plane_fly():
def __init__(self,play_image_filename,play_pos):
self.image = pygame.image.load(play_image_filename)
self.plane_rect = self.image.get_rect()
self.play_image = self.image.subsurface(self.plane_rect)
self.plane_rect.midtop = play_pos
self.speed = 2
#子弹是由玩家飞机发射的,所以创建列表,存储子弹对象,使该列表变为该类的属性
self.bullets = [] #子弹空列表
self.is_hitted = False #是否被击中
#生成函数,完成发射子弹动作,同时将每个子弹对象存在列表中
def shoot(self,bullet_filename):
bulletobj = Bullet(bullet_filename,self.plane_rect.midtop) #利用Bullet生产
self.bullets.append(bulletobj) #加入子弹列表
#定义向上移动方法,当飞机移动到边框位置时,无法移动
def moveup(self):
if self.plane_rect.top <= 0:
self.plane_rect.top = 0
else:
self.plane_rect.top -= self.speed
# 定义向下移动方法,当飞机移动到边框位置时,无法移动
def movedown(self):
if self.plane_rect.top >= 700 - self.plane_rect.height:
self.plane_rect.top = 700 - self.plane_rect.height
else:
self.plane_rect.top += self.speed
# 向右移动,当飞机移动到边框位置时,无法移动
def moveleft(self):
if self.plane_rect.left <= -40:
self.plane_rect.left = -40
else:
self.plane_rect.left -= self.speed
# 向左移动,当飞机移动到边框位置时,无法移动
def moveright(self):
if self.plane_rect.left >= 700 - self.plane_rect.width:
self.plane_rect.left = 700 - self.plane_rect.width
else:
self.plane_rect.left += self.speed
# 生成敌机类,设定固定的移动速度
class Enemy():
def __init__(self,enemyfilename,enemypos):
self.img = pygame.image.load(enemyfilename)
self.enemy_rect = self.img.get_rect()
self.enemy_image = self.img.subsurface(self.enemy_rect)
self.enemy_rect.midbottom = enemypos
self.speed = 1
def move(self):
self.enemy_rect.bottom += self.speed #敌机向下运动
clock = pygame.time.Clock()
def main():
# 初始化文字屏幕
pygame.font.init()
# 初始化图像屏幕
pygame.init()
# 设定游戏帧

最低0.47元/天 解锁文章

1056

被折叠的 条评论
为什么被折叠?



