Python写一款游戏小脚本究竟有多简单。给我五分钟教你写飞机大战。

  前言

学习贵在坚持:小编之前在学习中,看到了很多有趣的小游戏,希望大家喜欢!这个飞机大战

的小程序的话刚做的比较粗糙哈,之后会继续优化,目前就分享下给大家!

Python写一款游戏小脚本究竟有多简单。给我五分钟教你写飞机大战。_第1张图片

正文

 Show Time

Nov  1)背景环境

开发工具—Python版本:3.6.4

相关模块:Pygame模块;

环境搭建:安装Python并添加到环境变量,pip安装需要的相关模块即可。

Nov  2)代码演示

游戏界面:

'''游戏界面'''
def GamingInterface(num_player, screen):
    # 初始化
    pygame.mixer.music.load(cfg.SOUNDPATHS['Cool Space Music'])
    pygame.mixer.music.set_volume(0.4)
    pygame.mixer.music.play(-1)
    explosion_sound = pygame.mixer.Sound(cfg.SOUNDPATHS['boom'])
    fire_sound = pygame.mixer.Sound(cfg.SOUNDPATHS['shot'])
    font = pygame.font.Font(cfg.FONTPATH, 20)
    # 游戏背景图
    bg_imgs = [cfg.IMAGEPATHS['bg_big'], cfg.IMAGEPATHS['seamless_space'], cfg.IMAGEPATHS['space3']]
    bg_move_dis = 0
    bg_1 = pygame.image.load(bg_imgs[0]).convert()
    bg_2 = pygame.image.load(bg_imgs[1]).convert()
    bg_3 = pygame.image.load(bg_imgs[2]).convert()
    # 玩家, 子弹和小行星精灵组
    player_group = pygame.sprite.Group()
    bullet_group = pygame.sprite.Group()
    asteroid_group = pygame.sprite.Group()
    # 产生小行星的时间间隔
    asteroid_ticks = 90
    for i in range(num_player):
        player_group.add(Ship(i+1, cfg))
    clock = pygame.time.Clock()
    # 分数
    score_1, score_2 = 0, 0
    # 游戏主循环
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
        # --玩家一: ↑↓←→控制, j射击; 玩家二: wsad控制, 空格射击
        pressed_keys = pygame.key.get_pressed()
        for idx, player in enumerate(player_group):
            direction = None
            if idx == 0:
                if pressed_keys[pygame.K_UP]:
                    direction = 'up'
                elif pressed_keys[pygame.K_DOWN]:
                    direction = 'down'
                elif pressed_keys[pygame.K_LEFT]:
                    direction = 'left'
                elif pressed_keys[pygame.K_RIGHT]:
                    direction = 'right'
                if direction:
                    player.move(direction)
                if pressed_keys[pygame.K_j]:
                    if player.cooling_time == 0:
                        fire_sound.play()
                        bullet_group.add(player.shot())
                        player.cooling_time = 20
            elif idx == 1:
                if pressed_keys[pygame.K_w]:
                    direction = 'up'
                elif pressed_keys[pygame.K_s]:
                    direction = 'down'
                elif pressed_keys[pygame.K_a]:
                    direction = 'left'
                elif pressed_keys[pygame.K_d]:
                    direction = 'right'
                if direction:
                    player.move(direction)
                if pressed_keys[pygame.K_SPACE]:
                    if player.cooling_time == 0:
                        fire_sound.play()
                        bullet_group.add(player.shot())
                        player.cooling_time = 20
            if player.cooling_time > 0:
                player.cooling_time -= 1
        if (score_1 + score_2) < 500:
            background = bg_1
        elif (score_1 + score_2) < 1500:
            background = bg_2
        else:
            background = bg_3
        # --向下移动背景图实现飞船向上移动的效果
        screen.blit(background, (0, -background.get_rect().height + bg_move_dis))
        screen.blit(background, (0, bg_move_dis))
        bg_move_dis = (bg_move_dis + 2) % background.get_rect().height
        # --生成小行星
        if asteroid_ticks == 0:
            asteroid_ticks = 90
            asteroid_group.add(Asteroid(cfg))
        else:
            asteroid_ticks -= 1
        # --画飞船
        for player in player_group:
            if pygame.sprite.spritecollide(player, asteroid_group, True, None):
                player.explode_step = 1
                explosion_sound.play()
            elif player.explode_step > 0:
                if player.explode_step > 3:
                    player_group.remove(player)
                    if len(player_group) == 0:
                        return
                else:
                    player.explode(screen)
            else:
                player.draw(screen)
        # --画子弹
        for bullet in bullet_group:
            bullet.move()
            if pygame.sprite.spritecollide(bullet, asteroid_group, True, None):
                bullet_group.remove(bullet)
                if bullet.player_idx == 1:
                    score_1 += 1
                else:
                    score_2 += 1
            else:
                bullet.draw(screen)
        # --画小行星
        for asteroid in asteroid_group:
            asteroid.move()
            asteroid.rotate()
            asteroid.draw(screen)
        # --显示分数
        score_1_text = '玩家一得分: %s' % score_1
        score_2_text = '玩家二得分: %s' % score_2
        text_1 = font.render(score_1_text, True, (0, 0, 255))
        text_2 = font.render(score_2_text, True, (255, 0, 0))
        screen.blit(text_1, (2, 5))
        screen.blit(text_2, (2, 35))
        # --屏幕刷新
        pygame.display.update()
        clock.tick(60)

配置一些文件如背景图片等:

'''屏幕大小'''
SCREENSIZE = (956, 560)
'''字体路径'''
FONTPATH = os.path.join(os.getcwd(), 'resources/font/simkai.ttf')
'''图片路径'''
IMAGEPATHS = {
    'asteroid': os.path.join(os.getcwd(), 'resources/images/asteroid.png'),
    'bg_big': os.path.join(os.getcwd(), 'resources/images/bg_big.png'),
    'bullet': os.path.join(os.getcwd(), 'resources/images/bullet.png'),
    'seamless_space': os.path.join(os.getcwd(), 'resources/images/seamless_space.png'),
    'ship': os.path.join(os.getcwd(), 'resources/images/ship.png'),
    'ship_exploded': os.path.join(os.getcwd(), 'resources/images/ship_exploded.png'),
    'space3': os.path.join(os.getcwd(), 'resources/images/space3.jpg'),
}
'''声音路径'''
SOUNDPATHS = {
    'boom': os.path.join(os.getcwd(), 'resources/sounds/boom.wav'),
    'Cool Space Music': os.path.join(os.getcwd(), 'resources/sounds/Cool Space Music.mp3'),
    'shot': os.path.join(os.getcwd(), 'resources/sounds/shot.ogg'),
}

定义子弹、飞船等:

'''子弹'''
class Bullet(pygame.sprite.Sprite):
    def __init__(self, idx, position, cfg):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(cfg.IMAGEPATHS['bullet']).convert_alpha()
        self.image = pygame.transform.scale(self.image, (10, 10))
        # 位置
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = position
        self.position = position
        # 速度
        self.speed = 8
        # 玩家编号
        self.player_idx = idx
    '''移动子弹'''
    def move(self):
        self.position = self.position[0], self.position[1] - self.speed
        self.rect.left, self.rect.top = self.position
    '''画子弹'''
    def draw(self, screen):
        screen.blit(self.image, self.rect)


'''小行星'''
class Asteroid(pygame.sprite.Sprite):
    def __init__(self, cfg):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(cfg.IMAGEPATHS['asteroid']).convert_alpha()
        # 位置
        self.rect = self.image.get_rect()
        self.position = (random.randrange(20, cfg.SCREENSIZE[0] - 20), -64)
        self.rect.left, self.rect.top = self.position
        # 速度
        self.speed = random.randrange(3, 9)
        self.angle = 0
        self.angular_velocity = random.randrange(1, 5)
        self.rotate_ticks = 3
    '''移动小行星'''
    def move(self):
        self.position = self.position[0], self.position[1] + self.speed
        self.rect.left, self.rect.top = self.position
    '''转动小行星'''
    def rotate(self):
        self.rotate_ticks -= 1
        if self.rotate_ticks == 0:
            self.angle = (self.angle + self.angular_velocity) % 360
            orig_rect = self.image.get_rect()
            rot_image = pygame.transform.rotate(self.image, self.angle)
            rot_rect = orig_rect.copy()
            rot_rect.center = rot_image.get_rect().center
            rot_image = rot_image.subsurface(rot_rect).copy()
            self.image = rot_image
            self.rotate_ticks = 3
    '''画小行星'''
    def draw(self, screen):
        screen.blit(self.image, self.rect)


'''飞船'''
class Ship(pygame.sprite.Sprite):
    def __init__(self, idx, cfg):
        pygame.sprite.Sprite.__init__(self)
        self.cfg = cfg
        self.image = pygame.image.load(cfg.IMAGEPATHS['ship']).convert_alpha()
        self.explode_image = pygame.image.load(cfg.IMAGEPATHS['ship_exploded']).convert_alpha()
        # 位置
        self.position = {'x': random.randrange(-10, 918), 'y': random.randrange(-10, 520)}
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = self.position['x'], self.position['y']
        # 速度
        self.speed = {'x': 10, 'y': 5}
        # 玩家编号
        self.player_idx = idx
        # 子弹冷却时间
        self.cooling_time = 0
        # 爆炸用
        self.explode_step = 0
    '''飞船爆炸'''
    def explode(self, screen):
        img = self.explode_image.subsurface((48 * (self.explode_step - 1), 0), (48, 48))
        screen.blit(img, (self.position['x'], self.position['y']))
        self.explode_step += 1
    '''移动飞船'''
    def move(self, direction):
        if direction == 'left':
            self.position['x'] = max(-self.speed['x'] + self.position['x'], -10)
        elif direction == 'right':
            self.position['x'] = min(self.speed['x'] + self.position['x'], 918)
        elif direction == 'up':
            self.position['y'] = max(-self.speed['y'] + self.position['y'], -10)
        elif direction == 'down':
            self.position['y'] = min(self.speed['y'] + self.position['y'], 520)
        self.rect.left, self.rect.top = self.position['x'], self.position['y']
    '''画飞船'''
    def draw(self, screen):
        screen.blit(self.image, self.rect)
    '''射击'''
    def shot(self):
        return Bullet(self.player_idx, (self.rect.center[0] - 5, self.position['y'] - 5), self.cfg)

游戏开始、结束界面:

'''开始界面'''
def StartInterface(screen, cfg):
    clock = pygame.time.Clock()
    while True:
        button_1 = Button(screen, (330, 190), '单人模式', cfg)
        button_2 = Button(screen, (330, 305), '双人模式', cfg)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if button_1.collidepoint(pygame.mouse.get_pos()):
                    return 1
                elif button_2.collidepoint(pygame.mouse.get_pos()):
                    return 2
        clock.tick(60)
        pygame.display.update()


'''结束界面'''
def EndInterface(screen, cfg):
    clock = pygame.time.Clock()
    while True:
        button_1 = Button(screen, (330, 190), '重新开始', cfg)
        button_2 = Button(screen, (330, 305), '退出游戏', cfg)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if button_1.collidepoint(pygame.mouse.get_pos()):
                    return
                elif button_2.collidepoint(pygame.mouse.get_pos()):
                    pygame.quit()
                    sys.exit()
        clock.tick(60)
        pygame.display.update()

Nov  4)展示效果

     

手把手教你使用Python开发飞机大战小游戏(含源码)

 小结

简易版本的飞机大战就写到这里结束了,有没有想现在就动手自己玩一下滴

粉丝交流
欢迎关注、收藏、有所收获点赞支持一下!源碼點這裏


目前开通了交流群,方便大家获取源码、技术交流等等,方便找到志同道合的朋友哦!

你可能感兴趣的:(Python,程序员,python,pygame,开发语言)