signed

QiShunwang

“诚信为本、客户至上”

python实现小游戏代码

2021/6/3 14:17:35   来源:

mport pygame
import random
from sys import exit #向sys模块借用个exit函数来退出程序

定义一个敌机类

class Enemy:

def restar(self):
    #重置敌机位置与速度
    self.x=random.randint(100,600)
    self.y=random.randint(-200,-80)
    self.speed=random.random()+0.4
def __init__(self):
    self.restar()
    self.image=pygame.image.load('enermy.jpg')
def move(self):
    if self.y < 800:
        self.y+=self.speed  #向下移动
    else:
        self.restar()

定义一个bullet类,封装子弹相关的数据和方法

class Bullet:

def __init__(self):
    self.x=0;
    self.y=-1;
    self.image=pygame.image.load('bulet.jpg')
    self.active=False  #默认不激活子弹

def move(self):
    #激活状态下,向上移动
    if self.active:
        self.y-=0.8
    #挡飞出屏幕,设为不激活
    if self.yenemy.x and bullet.x < enemy.x + enemy.image.get_width()) and (
                bullet.y > enemy.ywww.cungun.com and bullet.y < enemy.y + enemy.image.get_height()
    ):
    enemy.restar();
    bullet.active=False
    return True
return False

class Plane:

def restar(self):
    self.x=200
    self.y=600
def __init__(self):
    self.restar()
    self.image=pygame.image.load('plane.jpg')
def move(self):
    x, y = pygame.mouse.get_pos();  # 跟随鼠标移动
    x -= self.image.get_width() / 2;
    y -= self.image.get_height() / 2;
    self.x=x;
    self.y=y

def checkcrash(enemy, plane):

if (plane.x + 0.7*plane.image.get_width() > enemy.x) and (
    plane.x + 0.3*plane.image.get_width() < enemy.x + enemy.image.get_width()) and (
    plane.y + 0.7*plane.image.get_height() > enemy.y) and (
    plane.y + 0.3*plane.image.get_width() < enemy.y + enemy.image.get_height()
):
    return True
return False

pygame.init()
screen=pygame.display.set_mode((1000,700),0,32) #创建一个窗口
pygame.display.set_caption('xwr!')#设置窗口标题
background=pygame.image.load('pygame.jpg') #加载并转换图像
plane=Plane()#加载飞机游戏图像
bullets=[]#创建子弹的list
for i in range(5):

bullets.append(Bullet()) #向list添加5发子弹

count_b=len(bullets)#子弹总数
index_b=0 #即将激活的子弹序号
interval_b=0#发射子弹的间隔
enemies=[]
for e in range(5):

enemies.append(Enemy())

gameover = False

分数

score = 0

用以显示文字的font变量

font = pygame.font.Font(None, 32)
while True: #游戏主循环函数

for event in pygame.event.get():
    if event.type==pygame.QUIT:  #接收到退出事件后退出程序
        pygame.quit()
        exit()
    if gameover and event.type==pygame.MOUSEBUTTONUP:
        plane.restar()
        for e in enemies:
            e.restar()
        for b in bullets:
            b.restar()
        score=0;
        gameover=False
screen.blit(background, (0, 0))  # 将背景图画上去
if not gameover:
    interval_b-=1  #发射间隔递减
    if interval_b<0:   #激活一发子弹

        bullets[index_b].restar()
        interval_b=80  #重置间隔时间
        index_b=(index_b+1)%count_b#子弹序号周期性递增
    for b in bullets:  #处于激活状态的子弹,移动位置并绘制
        if b.active:

            for e in enemies:
                if checkhit(e,b):
                    score+=100