python(pygame)开发一个超简易版消灭病毒

python(pygame)开发一个超简易版消灭病毒

  • 消灭病毒游戏
    • 以下是游戏代码:每个类都是一个py文件,需要导包
    • 1、主程序代码
    • 2、飞机类
    • 3、子弹类
    • 4、病毒类

消灭病毒游戏

消灭病毒是一个打飞机类型游戏,游戏开始界面如下,病毒有生命值,一颗子弹伤害为10
病毒生命值为0时则消失,飞机撞到病毒游戏结束,游戏结束时显示分数
python(pygame)开发一个超简易版消灭病毒_第1张图片

以下是游戏代码:每个类都是一个py文件,需要导包

1、主程序代码

import pygame
from airplane import Airplane
from bullet import Bullet
import virusers


def loadgameover(scorenum):  # 绘出GAME OVER
    screen.fill([0, 0, 0])
    my_font = pygame.font.SysFont('arial', 50)
    levelstr = 'GAME OVER'  #游戏结束
    over_screen = my_font.render(levelstr, True, (255, 0, 0))
    screen.blit(over_screen, (200, 240))
    highscorestr = 'YOUR SCORE IS ' + str(scorenum)  #显示得分
    over_screen = my_font.render(highscorestr, True, (255, 0, 0))
    screen.blit(over_screen, (200, 290))
    global count_num   #分数是一个全局变量,在这里重置为0
    count_num = 0
    airplane.rect.centerx = 300  #飞机位置重置
    airplane.rect.top = 800 - 54
    pygame.display.update()  # 刷新
    pygame.time.delay(1000)


if __name__ == '__main__':
    pygame.init()  # 初始化
    pygame.mixer.init()

    virusers.viruse_new()  # 病毒实例化
    #窗口初始化
    screen = pygame.display.set_mode((600,800))
    pygame.display.set_caption('消灭病毒')
    window_image = pygame.image.load('./airplane.jpg')
    pygame.display.set_icon(window_image)
    # 帧率设置
    clock = pygame.time.Clock()
    # 左上角计算分数
    countObj = pygame.font.SysFont('arial', 50)
    textObj = countObj.render('SCORE:0', True, (255, 0, 0))
    textRectObj = textObj.get_rect()
    screen.blit(textObj, textRectObj)
    # 这个是计算分数
    count_num = 0
    # 创建飞机
    airplane = Airplane(screen)
    # 子弹容器
    bullet_sprites = pygame.sprite.RenderUpdates()  # 创建sprite容器  树
    AddEnemy = pygame.USEREVENT + 1  # 添加子弹的时间
    pygame.time.set_timer(AddEnemy, 300)

    pygame.display.flip()
    while True:
        clock.tick(60)
        screen.fill((255, 255, 255))  # 背景色
        screen.blit(airplane.image, airplane.rect)
        ''' 添加新病毒 '''
        if virusers.group.__len__() < 3:
            virusers.viruse_new()  # 病毒实例化

        virusers.group.update()  # 病毒
        virusers.group.draw(screen)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
            elif event.type == AddEnemy:
                bullet_sprites.add(Bullet(screen, airplane))
            elif event.type == pygame.K_BACKSPACE:
                loadgameover(count_num)

        # 获取键盘状态
        pressed_keys = pygame.key.get_pressed()
        # 调用方法更新
        airplane.update(pressed_keys)
        # 场景动画更新
        bullet_sprites.update()
        bullet_updates = bullet_sprites.draw(screen)
        pygame.display.update(bullet_updates)

        # 子弹和病毒组的碰撞
        hit_list = pygame.sprite.groupcollide(bullet_sprites, virusers.group, True, False)
        '''得分'''
        if hit_list.values().__len__():  # hit_list.values() 返回就是病毒精灵
            for obj in hit_list.values():
                if obj[0].score > 10:
                    obj[0].score -= 10
                else:
                    obj[0].kill()
                count_num += 10
        '''结束游戏 '''
        game_over = pygame.sprite.spritecollide(airplane, virusers.group, False)
        if game_over:
            if not game_over[0].Flag:
                loadgameover(count_num)
                # game_over[0].kill()
                game_over[0].Flag = True

        # 得分多少
        textObj = countObj.render('SCORE:%d' % count_num, False, (255, 0, 0))  # 显示得分内容
        textRectObj = textObj.get_rect()
        screen.blit(textObj, textRectObj)  # 这是得分
        pygame.display.flip()
        pygame.display.update()  # 刷新

2、飞机类

import pygame

class Airplane(pygame.sprite.Sprite):
    def __init__(self,screen):
        pygame.sprite.Sprite.__init__(self)
        self.screen = screen
        self.image = pygame.image.load('./airplane.jpg')
        self.rect = self.image.get_rect()
        self.rect.centerx = 300
        self.rect.top = 800 - 54
        self.speed = 4

        # 根据按键事件来移动
    def update(self, pressed_keys):
            # 按键事件
        if pressed_keys[pygame.K_LEFT] or pressed_keys[pygame.K_a]:
            if self.rect.left > 0:
                self.rect.left -= self.speed
        elif pressed_keys[pygame.K_RIGHT] or pressed_keys[pygame.K_d]:
            if self.rect.left < 600 - self.image.get_width():
                self.rect.left += self.speed
        if pressed_keys[pygame.K_UP] or pressed_keys[pygame.K_w]:
            if self.rect.top > 0:
                self.rect.top -= self.speed
        elif pressed_keys[pygame.K_DOWN] or pressed_keys[pygame.K_s]:
            if self.rect.top < 800 - self.image.get_height():
                self.rect.top += self.speed

3、子弹类

import pygame

#这是子弹类
class Bullet(pygame.sprite.Sprite):
    """A class to manage bullets fired from the ship."""

    def __init__(self, screen, ship):
        """Create a bullet object, at the ship's current position."""
        super().__init__()
        self.screen = screen
        self.image = pygame.image.load('./bullet.png')
        self.damage = 2  #子弹每一发的伤害
        # Create bullet rect at (0, 0), then set correct position.
        self.rect = self.image.get_rect()
        self.rect.centerx = ship.rect.centerx
        self.rect.top = ship.rect.top
        self.speed = 5

    def update(self):
        """Move the bullet up the screen."""
        # Update the decimal position of the bullet.
        self.rect.y -= self.speed
        if self.rect.top < -self.rect.height:
            self.kill()

4、病毒类

import pygame
import sys
import random


# 病毒类
class Viruses(pygame.sprite.Sprite):
    Flag = False

    def __init__(self, image, position, x_speed, y_speed):
        '''
        初始化
        :param image: 图片名字
        :param position: 位置
        :param x_speed: 水平的速度
        :param y_speed: 竖直的速度
        :param score:  生命值
        '''
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(image)
        self.rect = self.image.get_rect()
        self.rect.center = position
        self.X_speed = x_speed
        self.Y_speed = y_speed
        if image == '2.png':
            self.score = 20
        elif image == '3.png':
            self.score = 10

    ''' 移动 '''
    def update(self, *args):
        self.rect = self.rect.move(self.X_speed, self.Y_speed)
        if self.rect.left < 0 or self.rect.right > 600:
            self.X_speed = -self.X_speed
        if self.rect.bottom > 800 + self.rect.height:
            self.rect.top = -self.rect.height

        if not self.score:
            self.kill()
        elif self.score == 10:
            self.trun(1)

    ''' 换图 '''
    def trun(self, value):
        if value == 0:
            self.image = pygame.image.load(viruses_images[value])
        elif value == 1:
            self.image = pygame.image.load(viruses_images[value])


group = pygame.sprite.Group()
viruses_images = ['2.png', '3.png']


# 初始化精灵组
def viruse_new():
    position_list = []
    for i in range(10):
        row = random.randint(0, 8)
        col = random.randint(0, 9)
        position = [row * 60 + 33, - col * 60 - 50]
        if position not in position_list:
            position_list.append(position)
            image_name = random.choice(viruses_images)
            obj = Viruses(image_name, position, random.randint(0, 3), random.randint(1, 3))
            group.add(obj)

你可能感兴趣的:(Python)