一。背景介绍

 90后小伙伴应该对坦克大战这款游戏很熟悉吧!!这款经典游戏,笔者小时候玩过无数次,大多数时候都是和小伙伴们一起开玩,相信对很多人来说,这款游戏还是记忆深处的珍藏品。当然,现在大家更热衷于英雄联盟、王者农药这样的游戏了。今天就和大家一起分享下,用python的pygame库制作的坦克大战游戏。

基于Python的坦克大战小游戏_pygame

二。游戏介绍

    打开游戏后是熟悉的主界面,关卡为两关,场景有石墙、钢墙和树林,其中红色土石墙(子弹可以打通),白色钢板(子弹打不通),树林坦克进去可以隐藏(子弹不隐藏),大本营由土墙包围,内部有老鹰的图腾,敌方坦克有三种,分别为 普通坦克、移速慢血多、移速快血少,打红色坦克会产生食物  不同的食物有不同的效果(子弹加速、大本营加固成钢板、坦克生命+1等)。我方坦克和敌方坦克出生会有简单特效。

基于Python的坦克大战小游戏_主文件_02

当地方坦克全部死亡时  出现 Congratulations  字样,当我放坦克生命数为0或者大本营被击毁时  出现  Game Over  字样。

三。游戏文件

游戏代码部分由bullet.py、food.py、home.py、scene.py、tanks.py、main.py这六个文件组成,分别代表子弹、奖励物品、基地、场景、坦克及主文件。整个游戏主要基于Pygame库进行开发,各模块均用函数进行封装,以增强复用性,主文件的部分代码如下所示:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
import os
import pygame
import scene
import bullet
import food
import tanks
import home
from pygame.locals import *
# 开始界面显示
def show_start_interface(screen, width, height):
    tfont = pygame.font.Font('./font/times.ttf', width//4)
    cfont = pygame.font.Font('./font/times.ttf', width//20)
    title = tfont.render(u'Tank War', True, (255, 0, 0))
    content1 = cfont.render(u'Press 1 for one player', True, (0, 0, 255))
    content2 = cfont.render(u'Press 2 for two players', True, (0, 0, 255))
    trect = title.get_rect()
    trect.midtop = (width/2, height/4)
    crect1 = content1.get_rect()
    crect1.midtop = (width/2, height/1.8)
    crect2 = content2.get_rect()
    crect2.midtop = (width/2, height/1.6)
    screen.blit(title, trect)
    screen.blit(content1, crect1)
    screen.blit(content2, crect2)
    pygame.display.update()
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_1:
                    return 1
                if event.key == pygame.K_2:
                    return 2
# 结束界面显示
def show_end_interface(screen, width, height, is_win):
    bg_img = pygame.image.load("./images/others/background.png")
    screen.blit(bg_img, (0, 0))
    if is_win:
        font = pygame.font.Font('./font/times.ttf', width//10)
        content = font.render(u'Congratulations!', True, (255, 0, 0))
        rect = content.get_rect()
        rect.midtop = (width/2, height/2)
        screen.blit(content, rect)
    else:
        fail_img = pygame.image.load("./images/others/gameover.png")
        rect = fail_img.get_rect()
        rect.midtop = (width/2, height/2)
        screen.blit(fail_img, rect)
    pygame.display.update()
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()

除了代码文件外,游戏文件还包含音乐、字体、图片等文件,最终游戏的效果也非常接近小时候的味道~~