以下代码个人原创,在需要说明的地方我在后面加了注释,当然我的代码是希望给大家一个思想,还有很多很多不足之处,希望大佬们发现后私信我哦,咱们一起探讨(嘻嘻,说得有点小装逼呀,其实是老师发个模版,让我们去加内容的):
需要注意的一个地方是,如果你用的版本是3.6的,那么下面的用到的所有从外界接收信息所用到的input()用input()就行了,如果是2.7版本,那么如果接收的是字符串要用raw_input()(将接收到的信息自动转化为字符串,即使你输入的是12345那也是字符串12345)
以下是代码,备注还是很详细的(代码中用到的文件可以点https://download.youkuaiyun.com/download/sand8o8time/10635172下载)
# -*- coding:utf-8 -*-
import pygame
import sys
from pygame.locals import *
from pygame.font import *
import time
import random
class Hero(object):
#玩家 英雄类
def __init__(self, screen_temp):
self.x = 210
self.y = 700
self.life = 21
# self.life = 100
self.image = pygame.image.load("./feiji/hero1.png")
self.screen = screen_temp
self.bullet_list = []#用来存储子弹对象的引用
#爆炸效果用的如下属性
self.hit = False #表示是否要爆炸
self.bomb_list = [] #用来存储爆炸时需要的图片
self.__create_images() #调用这个方法向bomb_list中添加图片
self.image_num = 0 #用来记录while True的次数,当次数达到一定值时才显示一张爆炸的图,然后清空,,当这个次数再次达到时,再显示下一个爆炸效果的图片
self.image_index = 0#用来记录当前要显示的爆炸效果的图片的序号
def __create_images(self):
#添加爆炸图片
self.bomb_list.append(pygame.image.load("./feiji/hero_blowup_n1.png"))
self.bomb_list.append(pygame.image.load("./feiji/hero_blowup_n2.png"))
self.bomb_list.append(pygame.image.load("./feiji/hero_blowup_n3.png"))
self.bomb_list.append(pygame.image.load("./feiji/hero_blowup_n4.png"))
def display(self):
#显示玩家的飞机
#如果被击中,就显示爆炸效果,否则显示普通的飞机效果
if self.hit == True:
self.screen.blit(self.bomb_list[self.image_index], (self.x, self.y))#(self.x, self.y)是指当前英雄的位置
#blit方法 (一个对象,左上角位置)
self.image_num += 1
print(self.image_num)
if self.image_num == 7:
self.image_num = 0
self.image_index += 1
print(self.image_index) #这里子弹打住英雄时没有被清除掉,所以打一下,就死了
if self.image_index > 3:
time.sleep(1)
exit()#调用exit让游戏退出
#self.image_index = 0
else:
if self.x< 0: #控制英雄,不让它跑出界面
self.x = 0
elif self.x > 382:
self.x = 382
if self.y < 0:
self.y = 0
elif self.y > 750:
self.y = 750
self.screen.blit(self.image,(self.x, self.y))#z这里是只要没有被打中,就一直是刚开始的样子
#不管玩家飞机是否被击中,都要显示发射出去的子弹
for bullet in self.bullet_list:
bullet.display()
bullet.move()
def move(self, move_x,move_y):
self.x += move_x
self.y += move_y
def fire(self):
#通过创建一个子弹对象,完成发射子弹
bullet = Bullet(self.screen, self.x, self.y)#创建一个子弹对象
self.bullet_list.append(bullet)
def bomb(self):
self.hit = True
def judge(self):
global life
if life == 0:
self.bomb()
class Bullet(object):
#玩家子弹类
def __init__(self, screen_temp, x_temp, y_temp):
self.x = x_temp + 40
self.y = y_temp - 20
self.image = pygame.image.load("./feiji/bullet.png")
self.screen = screen_temp
def display(self):
self.screen.blit(self.image, (self.x, self.y))
def move(self):
self.y -= 10
class Bullet_Enemy(object):
#敌机子弹类
def __init__(self, screen_temp, x_temp, y_temp):
self.x = x_temp + 25
self.y = y_temp + 30
self.image = pygame.image.load("./feiji/bullet1.png")
self.screen = screen_temp
def display(self):
self.screen.blit(self.image,(self.x,self.y))
def