您好,欢迎访问代理记账网站
  • 价格透明
  • 信息保密
  • 进度掌控
  • 售后无忧

python小游戏—摧毁基地

python小游戏—摧毁基地

前言

python新手。最近用python写了一款小游戏,只能算是对大佬的拙劣模仿。代码冗杂,后面有时间会进行优化。如需引用请附上本文地址,有时间会进行不定期更改。请大佬轻喷。

import pygame
import random
import time
import math

SCREEN_WIDTH = 800  # 窗口宽度
SCREEN_HEIGHT = 600  # 窗口高度
BG_COLOR = pygame.Color(0, 0, 0)  # 窗口背景颜色
FG_COLOR = pygame.Color(255, 255, 255)  # 前景颜色
'''摧毁基地'''


class MainGame:
    window = None
    Attacker1 = None
    count = 0
    randNum = 0
    baseList = []
    protectorList = []
    myBulletList = []
    baseBulletList = []  # 基地子弹列表

    def start(self):
        """游戏开始"""
        pygame.display.init()
        MainGame.window = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
        self.createBase()
        self.createProtector()
        self.createAttacker()
        pygame.display.set_caption("摧毁基地")
        while True:
            time.sleep(0.02)
            MainGame.window.fill(BG_COLOR)
            self.getEvent()
            for base in MainGame.baseList:
                if MainGame.Attacker1:
                    MainGame.window.blit(self.showText("boss剩余生命值{0}                                              "
                                                       "攻击者剩余生命值{1}".format(base.hp, MainGame.Attacker1.hp)), (5, 5))
            self.blitBase()
            self.blitProtector()
            self.blitAttacker()
            self.blitBullet()
            if MainGame.count > 50:
                self.createBaseBullet()
                MainGame.count = 0
            MainGame.count += 1
            MainGame.randNum += 1
            self.blitBaseBullet()
            if MainGame.Attacker1:
                if not MainGame.Attacker1.stop:
                    MainGame.Attacker1.move()
            pygame.display.update()

    def createBase(self):
        """基地创建"""
        base = Base(SCREEN_WIDTH / 2 - 100, 25)
        MainGame.baseList.append(base)

    def blitBase(self):
        """显示基地"""
        for base in MainGame.baseList:
            if base.live:
                base.displayBase()
                base.randMove()
            else:
                MainGame.baseList.remove(base)

    def createProtector(self):
        """创建保护者"""
        for i in range(10):
            left = random.randint(0, 300)
            top = 30 * random.randint(5, 12)
            protector = Protector(left, top)
            MainGame.protectorList.append(protector)

    def blitProtector(self):
        """显示保护者"""
        for protector in MainGame.protectorList:
            protector.displayProtector()
            protector.randMove()

    def createAttacker(self):
        """创建攻击者"""
        top = 480
        left = random.randint(0, 700)
        MainGame.Attacker1 = Attacker(left, top)

    def blitAttacker(self):
        """显示攻击者"""
        if MainGame.Attacker1:
            if MainGame.Attacker1.live:
                MainGame.Attacker1.displayAttacker()
            else:
                del MainGame.Attacker1
                MainGame.Attacker1 = None

    def blitBullet(self):
        """显示子弹"""
        for myBullet in MainGame.myBulletList:
            if myBullet.live:
                myBullet.displayBullet()
                myBullet.move()
                myBullet.hitProtector()
                myBullet.hitBase()
            else:
                MainGame.myBulletList.remove(myBullet)

    def createBaseBullet(self):
        """创建基地子弹"""
        for i in range(3):
            speed = 5
            for base in MainGame.baseList:
                baseBullet = BaseBullet(speed, base)
                MainGame.baseBulletList.append(baseBullet)

    def blitBaseBullet(self):
        """显示基地子弹"""
        num = 0
        for baseBullet in MainGame.baseBulletList:
            num += 1
            if baseBullet:
                if baseBullet.live:
                    baseBullet.displayBaseBullet()
                    for base in MainGame.baseList:
                        baseBullet.move(num, base)
                    baseBullet.hitAttacker()
                else:
                    pass

    def showText(self, text):
        """显示基地生命值"""
        pygame.font.init()
        font = pygame.font.SysFont("kaiti", 20)
        textSurface = font.render(text, True, FG_COLOR)
        return textSurface

    def getEvent(self):
        """获取点击事件"""
        eventList = pygame.event.get()
        for event in eventList:
            if event.type == pygame.QUIT:  # 判断事件是否为退出键(即窗口右上角的叉)
                self.endGame()
            if event.type == pygame.KEYDOWN:  # 判断事件是否为按下按键操作
                if not MainGame.Attacker1:
                    if event.key == pygame.K_ESCAPE:  # 判断按键是否为Esc键
                        self.createAttacker()
                elif MainGame.Attacker1.live:
                    if event.key == pygame.K_LEFT:  # 判断按键是否为左键
                        print("左")
                        MainGame.Attacker1.direction = 'L'
                        MainGame.Attacker1.stop = False
                    elif event.key == pygame.K_RIGHT:  # 判断按键是否为右键
                        print("右")
                        MainGame.Attacker1.direction = 'R'
                        MainGame.Attacker1.stop = False
                    elif event.key == pygame.K_SPACE:  # 判断按键是否为空格键
                        print("发射子弹")
                        if len(MainGame.myBulletList) < 8:
                            myBullet = Bullet(MainGame.Attacker1)
                            MainGame.myBulletList.append(myBullet)
            elif event.type == pygame.KEYUP:  # 判断事件是否为释放按键操作
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    if MainGame.Attacker1:
                        MainGame.Attacker1.stop = True

    def endGame(self):
        """结束游戏"""
        exit()


class Base:
    def __init__(self, left, top):
        self.image = pygame.image.load('./img/boss1.gif')  # 加载图片
        self.rect = self.image.get_rect()
        self.rect.left = left
        self.rect.top = top
        self.direction = 'L'
        self.step = 60
        self.speed = 5
        self.live = True
        self.hp = 20  # 设置基地生命

    def randShot(self):
        """随机射击"""
        return Bullet(self)

    def displayBase(self):
        """显示基地"""
        MainGame.window.blit(self.image, self.rect)

    def randDirection(self):
        """产生基地的随机移动方向"""
        a = random.randint(1, 2)
        if a == 1:
            return 'L'
        elif a == 2:
            return 'R'

    def randMove(self):
        if self.step <= 0:
            self.direction = self.randDirection()
            self.step = 60
        else:
            self.move()
            self.step -= 1

    def move(self):
        if self.direction == 'L':
            if self.rect.left > 0:
                self.rect.left -= self.speed
        elif self.direction == 'R':
            if self.rect.left < SCREEN_WIDTH - self.rect.width:
                self.rect.left += self.speed


class Protector:
    def __init__(self, left, top):
        self.image = pygame.image.load('./img/protector.gif')
        self.rect = self.image.get_rect()
        self.step = 60
        self.speed = 5
        self.direction = 'L'
        self.rect.left = left
        self.rect.top = top
        self.oldLeft = self.rect.left
        self.oldTop = self.rect.top

    def randDirection(self):
        a = random.randint(1, 2)
        if a == 1:
            return 'L'
        elif a == 2:
            return 'R'

    def randMove(self):
        self.oldLeft = self.rect.left
        self.oldTop = self.rect.top
        if self.step <= 0:
            self.direction = self.randDirection()
            self.step = 60
        else:
            self.move()
            self.step -= 1

    def move(self):
        if self.direction == 'L':
            if self.rect.left > 0:
                self.rect.left -= self.speed
        elif self.direction == 'R':
            if self.rect.left < SCREEN_WIDTH - self.rect.width:
                self.rect.left += self.speed

    def displayProtector(self):
        MainGame.window.blit(self.image, self.rect)


class Attacker:
    def __init__(self, left, top):
        self.image = pygame.image.load('./img/attacker2.gif')
        self.rect = self.image.get_rect()
        self.direction = 'L'
        self.rect.left = left
        self.rect.top = top
        self.speed = 7
        self.stop = True
        self.hp = 5
        self.live = True

    def shot(self):
        return Bullet(self)

    def move(self):
        if self.direction == 'L':
            if self.rect.left > 0:
                self.rect.left -= self.speed
        elif self.direction == 'R':
            if self.rect.left < SCREEN_WIDTH - self.rect.width:
                self.rect.left += self.speed

    def displayAttacker(self):
        MainGame.window.blit(self.image, self.rect)


class Bullet:
    def __init__(self, attacker):
        self.image = pygame.image.load('./img/enemymissile.gif')
        self.rect = self.image.get_rect()
        self.speed = 10
        self.rect.left = attacker.rect.left + 0.5 * attacker.rect.width - 0.5 * self.rect.width
        self.rect.top = attacker.rect.top + self.rect.height
        self.live = True

    def move(self):
        if self.rect.top > 0:
            self.rect.top -= self.speed
        else:
            self.live = False

    def displayBullet(self):
        MainGame.window.blit(self.image, self.rect)

    def hitProtector(self):
        for protector in MainGame.protectorList:
            if pygame.sprite.collide_rect(self, protector):  # 检测self与protecter是否发生碰撞
                self.live = False

    def hitBase(self):
        for base in MainGame.baseList:
            if pygame.sprite.collide_rect(self, base):
                self.live = False
                base.hp -= 1
                if base.hp <= 0:
                    base.live = False


class BaseBullet:
    def __init__(self, speed, base):
        self.image = pygame.image.load('./img/enemymissile.gif')
        self.rect = self.image.get_rect()
        self.speed = speed
        self.rect.left = base.rect.left + 0.5 * base.rect.width - 0.5 * self.rect.width
        self.rect.top = base.rect.top + base.rect.height
        self.live = True
        self.mark = True

    def move(self, num, base):
        if self.rect.top < SCREEN_HEIGHT:
            if self.rect.left > 0:
                if self.rect.left < SCREEN_WIDTH:
                    if num % 3 == 1:
                        self.rect.top += self.speed
                    elif num % 3 == 2:
                        if self.mark:
                            self.rect.left = base.rect.left + 0.5 * base.rect.width - 0.5 * self.rect.width - 50
                            self.mark = False
                        self.rect.top += self.speed
                    elif num % 3 == 0:
                        if self.mark:
                            self.rect.left = base.rect.left + 0.5 * base.rect.width - 0.5 * self.rect.width + 50
                            self.mark = False
                        self.rect.top += self.speed
                else:
                    self.live = False
            else:
                self.live = False
        else:
            self.live = False

    def hitAttacker(self):
        if MainGame.Attacker1:
            if pygame.sprite.collide_rect(self, MainGame.Attacker1):
                self.live = False
                MainGame.Attacker1.hp -= 1
                if MainGame.Attacker1.hp <= 0:
                    MainGame.Attacker1.live = False

    def displayBaseBullet(self):
        MainGame.window.blit(self.image, self.rect)


if __name__ == '__main__':
    MainGame().start()

分享:

低价透明

统一报价,无隐形消费

金牌服务

一对一专属顾问7*24小时金牌服务

信息保密

个人信息安全有保障

售后无忧

服务出问题客服经理全程跟进