基于 Python 的坦克大战小程序,使用 Pygame 库开发

坦克大战程序代码

首先,确保您已安装 Pygame 库,如果没有安装,可以使用以下命令安装:

bash 复制代码
pip install pygame

以下是完整的程序代码:

python 复制代码
import pygame
import random
import sys
import math

# 初始化pygame
pygame.init()

# 确保中文正常显示
pygame.font.init()
chinese_fonts = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC", "simsun"]
font_name = None
for font in chinese_fonts:
    if font in pygame.font.get_fonts():
        font_name = font
        break
if not font_name:
    font_name = pygame.font.get_default_font()  #  fallback to default font

# 游戏常量
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
GRID_SIZE = 40
FPS = 60
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
GRAY = (150, 150, 150)
YELLOW = (255, 255, 0)
BROWN = (139, 69, 19)

# 创建游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("坦克大战")
clock = pygame.time.Clock()

class Tank:
    def __init__(self, x, y, color, is_player=False, speed=2, health=1):
        self.x = x
        self.y = y
        self.width = 30
        self.height = 30
        self.color = color
        self.direction = "up"  # 初始方向
        self.speed = speed
        self.is_player = is_player
        self.shoot_cooldown = 30  # 射击冷却时间(帧)
        self.last_shot = 0
        self.health = health
        self.invincible = False
        self.invincible_timer = 0
        self.invincible_duration = 180  # 无敌状态持续时间(帧)

    def move(self, direction, obstacles, tanks):
        self.direction = direction
        old_x, old_y = self.x, self.y

        if direction == "up":
            self.y -= self.speed
        elif direction == "down":
            self.y += self.speed
        elif direction == "left":
            self.x -= self.speed
        elif direction == "right":
            self.x += self.speed

        # 边界检测
        if self.x < 0:
            self.x = 0
        if self.x > SCREEN_WIDTH - self.width:
            self.x = SCREEN_WIDTH - self.width
        if self.y < 0:
            self.y = 0
        if self.y > SCREEN_HEIGHT - self.height:
            self.y = SCREEN_HEIGHT - self.height

        # 与障碍物碰撞检测
        tank_rect = pygame.Rect(self.x, self.y, self.width, self.height)
        collision = False
        
        for obstacle in obstacles:
            if tank_rect.colliderect(obstacle.rect):
                collision = True
                break
                
        # 与其他坦克碰撞检测
        for tank in tanks:
            if tank != self and tank_rect.colliderect(pygame.Rect(tank.x, tank.y, tank.width, tank.height)):
                collision = True
                break
                
        if collision:
            self.x, self.y = old_x, old_y

    def shoot(self, bullets):
        current_time = pygame.time.get_ticks()
        if current_time - self.last_shot > self.shoot_cooldown * 10:  # 转换为毫秒
            self.last_shot = current_time
            if self.direction == "up":
                bullet = Bullet(self.x + self.width // 2 - 2, self.y, "up", self.color, self.is_player)
            elif self.direction == "down":
                bullet = Bullet(self.x + self.width // 2 - 2, self.y + self.height, "down", self.color, self.is_player)
            elif self.direction == "left":
                bullet = Bullet(self.x, self.y + self.height // 2 - 2, "left", self.color, self.is_player)
            elif self.direction == "right":
                bullet = Bullet(self.x + self.width, self.y + self.height // 2 - 2, "right", self.color, self.is_player)
            bullets.append(bullet)
            return True
        return False

    def draw(self, surface):
        # 处理无敌状态闪烁效果
        if self.invincible:
            self.invincible_timer += 1
            if self.invincible_timer > self.invincible_duration:
                self.invincible = False
                self.invincible_timer = 0
            elif self.invincible_timer % 10 < 5:  # 每10帧闪烁一次
                return

        # 绘制坦克主体
        pygame.draw.rect(surface, self.color, (self.x, self.y, self.width, self.height))
        
        # 绘制坦克炮管
        if self.direction == "up":
            pygame.draw.rect(surface, BLACK, (self.x + self.width // 2 - 2, self.y - 10, 4, 10))
        elif self.direction == "down":
            pygame.draw.rect(surface, BLACK, (self.x + self.width // 2 - 2, self.y + self.height, 4, 10))
        elif self.direction == "left":
            pygame.draw.rect(surface, BLACK, (self.x - 10, self.y + self.height // 2 - 2, 10, 4))
        elif self.direction == "right":
            pygame.draw.rect(surface, BLACK, (self.x + self.width, self.y + self.height // 2 - 2, 10, 4))
            
        # 绘制生命值(仅玩家)
        if self.is_player:
            for i in range(self.health):
                color = GREEN if i < self.health else GRAY
                pygame.draw.rect(surface, color, 
                                (self.x + i * 10, self.y - 15, 8, 8))

    def get_rect(self):
        return pygame.Rect(self.x, self.y, self.width, self.height)

class Bullet:
    def __init__(self, x, y, direction, color, is_player_owned):
        self.x = x
        self.y = y
        self.width = 4
        self.height = 4
        self.direction = direction
        self.speed = 6
        self.color = color
        self.is_player_owned = is_player_owned
        self.damage = 1

    def move(self):
        if self.direction == "up":
            self.y -= self.speed
        elif self.direction == "down":
            self.y += self.speed
        elif self.direction == "left":
            self.x -= self.speed
        elif self.direction == "right":
            self.x += self.speed

    def is_out_of_bounds(self):
        return (self.x < 0 or self.x > SCREEN_WIDTH or 
                self.y < 0 or self.y > SCREEN_HEIGHT)

    def draw(self, surface):
        pygame.draw.rect(surface, self.color, (self.x, self.y, self.width, self.height))

    def get_rect(self):
        return pygame.Rect(self.x, self.y, self.width, self.height)

class Obstacle:
    def __init__(self, x, y, width=GRID_SIZE, height=GRID_SIZE, 
                 is_destructible=True, is_brick=True):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.is_destructible = is_destructible
        self.is_brick = is_brick  # 区分砖块和钢铁
        self.rect = pygame.Rect(x, y, width, height)
        if is_brick:
            self.color = BROWN if not is_destructible else GRAY
        else:
            self.color = BLACK if not is_destructible else (80, 80, 80)

    def draw(self, surface):
        pygame.draw.rect(surface, self.color, self.rect)
        # 钢铁障碍物添加纹理
        if not self.is_brick:
            for i in range(0, self.width, 10):
                pygame.draw.line(surface, (120, 120, 120), 
                                (self.x + i, self.y), 
                                (self.x + i, self.y + self.height), 1)

class Explosion:
    def __init__(self, x, y, size=20):
        self.x = x
        self.y = y
        self.radius = 5
        self.max_radius = size
        self.growth_rate = 1.5
        self.active = True

    def update(self):
        self.radius += self.growth_rate
        if self.radius > self.max_radius:
            self.active = False

    def draw(self, surface):
        alpha = 255 - int(255 * (self.radius / self.max_radius))
        explosion_surf = pygame.Surface((self.max_radius * 2, self.max_radius * 2), pygame.SRCALPHA)
        pygame.draw.circle(explosion_surf, (255, 255, 0, alpha), (self.max_radius, self.max_radius), self.radius)
        pygame.draw.circle(explosion_surf, (255, 165, 0, alpha), (self.max_radius, self.max_radius), self.radius * 0.7)
        pygame.draw.circle(explosion_surf, (255, 0, 0, alpha), (self.max_radius, self.max_radius), self.radius * 0.4)
        surface.blit(explosion_surf, (self.x - self.max_radius, self.y - self.max_radius))

class PowerUp:
    def __init__(self, x, y, power_type):
        self.x = x
        self.y = y
        self.width = 20
        self.height = 20
        self.power_type = power_type  # "speed", "power", "health", "shield"
        self.colors = {
            "speed": BLUE,
            "power": YELLOW,
            "health": GREEN,
            "shield": (100, 100, 255)
        }
        self.active = True
        self.lifetime = 180  # 存在时间(帧)
        self.timer = 0

    def update(self):
        self.timer += 1
        if self.timer > self.lifetime:
            self.active = False

    def draw(self, surface):
        # 闪烁效果(即将消失时)
        if self.lifetime - self.timer < 30 and self.timer % 5 < 2:
            return
        pygame.draw.rect(surface, self.colors[self.power_type], 
                         (self.x, self.y, self.width, self.height))
        # 绘制图标
        if self.power_type == "speed":
            pygame.draw.polygon(surface, WHITE, [(self.x+10, self.y+5), 
                                                (self.x+15, self.y+15), 
                                                (self.x+5, self.y+15)])
        elif self.power_type == "power":
            pygame.draw.circle(surface, WHITE, (self.x+10, self.y+10), 5)

    def get_rect(self):
        return pygame.Rect(self.x, self.y, self.width, self.height)

def create_level(level):
    obstacles = []
    wall_thickness = 10
    
    # 边界墙(不可摧毁)
    obstacles.append(Obstacle(0, 0, SCREEN_WIDTH, wall_thickness, False, False))
    obstacles.append(Obstacle(0, 0, wall_thickness, SCREEN_HEIGHT, False, False))
    obstacles.append(Obstacle(0, SCREEN_HEIGHT - wall_thickness, SCREEN_WIDTH, wall_thickness, False, False))
    obstacles.append(Obstacle(SCREEN_WIDTH - wall_thickness, 0, wall_thickness, SCREEN_HEIGHT, False, False))
    
    # 玩家出生保护区
    protected_area = (SCREEN_WIDTH//2 - 100, SCREEN_HEIGHT - 150, 200, 100)
    for x in range(protected_area[0], protected_area[0]+protected_area[2], GRID_SIZE):
        for y in range(protected_area[1], protected_area[1]+protected_area[3], GRID_SIZE):
            obstacles.append(Obstacle(x, y, GRID_SIZE, GRID_SIZE, False, False))
    
    # 随机障碍物
    obstacle_count = 25 + level * 5
    steel_ratio = 0.2 + min(0.5, level * 0.05)  # 随着关卡提升,钢铁障碍物比例增加
    
    for _ in range(obstacle_count):
        x = random.randint(GRID_SIZE, SCREEN_WIDTH - 2*GRID_SIZE)
        y = random.randint(GRID_SIZE, SCREEN_HEIGHT - 2*GRID_SIZE)
        # 对齐到网格
        x = (x // GRID_SIZE) * GRID_SIZE
        y = (y // GRID_SIZE) * GRID_SIZE
        
        # 避免出现在玩家保护区
        if not (protected_area[0] < x < protected_area[0]+protected_area[2] and 
                protected_area[1] < y < protected_area[1]+protected_area[3]):
            is_steel = random.random() < steel_ratio
            obstacles.append(Obstacle(x, y, GRID_SIZE, GRID_SIZE, not is_steel, not is_steel))
    
    return obstacles

def spawn_enemies(level, current_enemies):
    enemies = []
    max_enemies = 3 + min(5, level)  # 随关卡增加最多8个敌人
    
    if len(current_enemies) < max_enemies:
        # 敌人类型和属性随关卡提升
        enemy_types = [
            {"color": RED, "speed": 1, "health": 1, "cooldown": 40, "prob": 0.7 - min(0.5, level*0.1)},
            {"color": (255, 100, 100), "speed": 1.5, "health": 1, "cooldown": 30, "prob": 0.2},
            {"color": (180, 0, 0), "speed": 0.8, "health": 2, "cooldown": 50, "prob": 0.1 + min(0.3, level*0.05)}
        ]
        
        spawn_positions = [
            (GRID_SIZE*2, GRID_SIZE*2),
            (SCREEN_WIDTH - GRID_SIZE*3, GRID_SIZE*2),
            (GRID_SIZE*2, SCREEN_HEIGHT//2),
            (SCREEN_WIDTH - GRID_SIZE*3, SCREEN_HEIGHT//2)
        ]
        
        # 选择敌人类型
        rand = random.random()
        enemy_type = enemy_types[0]
        cumulative_prob = 0
        for et in enemy_types:
            cumulative_prob += et["prob"]
            if rand < cumulative_prob:
                enemy_type = et
                break
        
        x, y = random.choice(spawn_positions)
        enemy = Tank(x, y, enemy_type["color"])
        enemy.speed = enemy_type["speed"]
        enemy.health = enemy_type["health"]
        enemy.shoot_cooldown = enemy_type["cooldown"]
        enemies.append(enemy)
    
    return enemies

def enemy_ai(enemy_tanks, player_tank, obstacles, bullets, level):
    for tank in enemy_tanks:
        # 随机改变方向
        if random.random() < 0.02 + min(0.03, level*0.005):
            directions = ["up", "down", "left", "right"]
            tank.direction = random.choice(directions)
            
        # 追踪玩家(高级AI)
        if player_tank and random.random() < 0.01 + min(0.04, level*0.005):
            dx = player_tank.x - tank.x
            dy = player_tank.y - tank.y
            
            if abs(dx) > abs(dy):
                tank.direction = "right" if dx > 0 else "left"
            else:
                tank.direction = "down" if dy > 0 else "up"
                
        # 移动
        tank.move(tank.direction, obstacles, enemy_tanks + [player_tank] if player_tank else enemy_tanks)
        
        # 射击
        shoot_prob = 0.005 + min(0.02, level*0.002)
        if player_tank and is_player_visible(tank, player_tank, obstacles):
            shoot_prob += 0.05 + min(0.1, level*0.01)  # 玩家可见时提高射击概率
            
        if random.random() < shoot_prob:
            tank.shoot(bullets)

def is_player_visible(enemy, player, obstacles):
    # 检查玩家是否在敌人视线范围内
    if enemy.direction == "up" and enemy.x < player.x + player.width and enemy.x + enemy.width > player.x and enemy.y > player.y:
        # 检查中间是否有障碍物
        for obstacle in obstacles:
            if (obstacle.rect.right > enemy.x and obstacle.rect.left < enemy.x + enemy.width and
                obstacle.rect.bottom > player.y and obstacle.rect.top < enemy.y):
                return False
        return True
    elif enemy.direction == "down" and enemy.x < player.x + player.width and enemy.x + enemy.width > player.x and enemy.y < player.y:
        for obstacle in obstacles:
            if (obstacle.rect.right > enemy.x and obstacle.rect.left < enemy.x + enemy.width and
                obstacle.rect.top < player.y and obstacle.rect.bottom > enemy.y):
                return False
        return True
    elif enemy.direction == "left" and enemy.y < player.y + player.height and enemy.y + enemy.height > player.y and enemy.x > player.x:
        for obstacle in obstacles:
            if (obstacle.rect.bottom > enemy.y and obstacle.rect.top < enemy.y + enemy.height and
                obstacle.rect.right > player.x and obstacle.rect.left < enemy.x):
                return False
        return True
    elif enemy.direction == "right" and enemy.y < player.y + player.height and enemy.y + enemy.height > player.y and enemy.x < player.x:
        for obstacle in obstacles:
            if (obstacle.rect.bottom > enemy.y and obstacle.rect.top < enemy.y + enemy.height and
                obstacle.rect.left < player.x and obstacle.rect.right > enemy.x):
                return False
        return True
    return False

def draw_text(surface, text, size, x, y, color=WHITE, align="center"):
    font = pygame.font.SysFont(font_name, size)
    text_surface = font.render(text, True, color)
    text_rect = text_surface.get_rect()
    
    if align == "center":
        text_rect.center = (x, y)
    elif align == "topleft":
        text_rect.topleft = (x, y)
        
    surface.blit(text_surface, text_rect)

def game_loop():
    # 初始化游戏状态
    level = 1
    score = 0
    lives = 3
    player = Tank(SCREEN_WIDTH // 2 - 15, SCREEN_HEIGHT - 100, GREEN, True, speed=2, health=1)
    player.invincible = True  # 初始无敌状态
    obstacles = create_level(level)
    enemy_tanks = []
    bullets = []
    explosions = []
    power_ups = []
    game_over = False
    win = False
    enemy_spawn_timer = 0
    enemy_spawn_interval = 3000  # 3秒
    level_clear_timer = 0
    level_clear_delay = 2000  # 2秒
    level_cleared = False

    running = True
    while running:
        current_time = pygame.time.get_ticks()
        
        # 事件处理
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and not game_over and not level_cleared:
                    player.shoot(bullets)
                if event.key == pygame.K_r and game_over:
                    return game_loop()  # 重新开始
                if event.key == pygame.K_q and game_over:
                    running = False

        if not game_over and not level_cleared:
            # 玩家移动控制
            keys = pygame.key.get_pressed()
            if keys[pygame.K_w] or keys[pygame.K_UP]:
                player.move("up", obstacles, enemy_tanks)
            if keys[pygame.K_s] or keys[pygame.K_DOWN]:
                player.move("down", obstacles, enemy_tanks)
            if keys[pygame.K_a] or keys[pygame.K_LEFT]:
                player.move("left", obstacles, enemy_tanks)
            if keys[pygame.K_d] or keys[pygame.K_RIGHT]:
                player.move("right", obstacles, enemy_tanks)

            # 生成敌人
            if current_time - enemy_spawn_timer > enemy_spawn_interval:
                new_enemies = spawn_enemies(level, enemy_tanks)
                enemy_tanks.extend(new_enemies)
                enemy_spawn_timer = current_time

            # 敌人AI
            enemy_ai(enemy_tanks, player, obstacles, bullets, level)

            # 子弹更新和碰撞检测
            for bullet in bullets[:]:
                bullet.move()
                
                # 子弹出界检测
                if bullet.is_out_of_bounds():
                    bullets.remove(bullet)
                    continue
                
                # 子弹与障碍物碰撞
                bullet_rect = bullet.get_rect()
                for obstacle in obstacles[:]:
                    if bullet_rect.colliderect(obstacle.rect):
                        # 钢铁障碍物只有增强子弹才能摧毁
                        if obstacle.is_destructible or (hasattr(bullet, 'power') and bullet.power > 1):
                            if obstacle.is_destructible or bullet.power > 1:
                                obstacles.remove(obstacle)
                                explosions.append(Explosion(bullet.x, bullet.y, 15))
                                # 有概率掉落道具
                                if random.random() < 0.1:
                                    power_types = ["speed", "power", "health", "shield"]
                                    power_up = PowerUp(obstacle.x + 10, obstacle.y + 10, random.choice(power_types))
                                    power_ups.append(power_up)
                        bullets.remove(bullet)
                        explosions.append(Explosion(bullet.x, bullet.y, 10))
                        break

                # 子弹与坦克碰撞
                if bullet.is_player_owned:
                    # 玩家子弹击中敌人
                    for tank in enemy_tanks[:]:
                        if bullet_rect.colliderect(tank.get_rect()):
                            tank.health -= bullet.damage
                            bullets.remove(bullet)
                            explosions.append(Explosion(tank.x + tank.width//2, tank.y + tank.height//2))
                            
                            if tank.health <= 0:
                                enemy_tanks.remove(tank)
                                score += 100 + level * 10
                                # 有概率掉落道具
                                if random.random() < 0.2:
                                    power_types = ["speed", "power", "health", "shield"]
                                    power_up = PowerUp(tank.x + 5, tank.y + 5, random.choice(power_types))
                                    power_ups.append(power_up)
                            break
                else:
                    # 敌人子弹击中玩家
                    if (not player.invincible and 
                        bullet_rect.colliderect(player.get_rect())):
                        player.health -= bullet.damage
                        bullets.remove(bullet)
                        explosions.append(Explosion(player.x + player.width//2, player.y + player.height//2))
                        
                        if player.health <= 0:
                            lives -= 1
                            explosions.append(Explosion(player.x + player.width//2, player.y + player.height//2, 40))
                            if lives <= 0:
                                game_over = True
                            else:
                                # 重生玩家
                                player = Tank(SCREEN_WIDTH // 2 - 15, SCREEN_HEIGHT - 100, GREEN, True, speed=player.speed)
                                player.invincible = True
                                player.health = 1

            # 更新道具
            for power_up in power_ups[:]:
                power_up.update()
                if not power_up.active:
                    power_ups.remove(power_up)
                    continue
                
                # 玩家拾取道具
                if player.get_rect().colliderect(power_up.get_rect()):
                    if power_up.power_type == "speed":
                        player.speed = min(4, player.speed + 0.5)
                    elif power_up.power_type == "power":
                        # 增强子弹威力
                        setattr(Bullet, 'power', 2)
                    elif power_up.power_type == "health":
                        player.health = min(3, player.health + 1)
                    elif power_up.power_type == "shield":
                        player.invincible = True
                        player.invincible_timer = 0
                    
                    explosions.append(Explosion(power_up.x + 10, power_up.y + 10, 20))
                    power_ups.remove(power_up)

            # 检查关卡是否完成
            if len(enemy_tanks) == 0 and current_time - enemy_spawn_timer > 2000:
                level_cleared = True
                level_clear_timer = current_time

        # 处理关卡切换
        if level_cleared:
            if current_time - level_clear_timer > level_clear_delay:
                level += 1
                level_cleared = False
                player = Tank(SCREEN_WIDTH // 2 - 15, SCREEN_HEIGHT - 100, GREEN, True, speed=player.speed)
                player.invincible = True
                obstacles = create_level(level)
                enemy_tanks = []
                bullets = []
                enemy_spawn_timer = current_time
                # 每3关增加一条命
                if level % 3 == 0:
                    lives += 1

        # 更新爆炸效果
        for explosion in explosions[:]:
            explosion.update()
            if not explosion.active:
                explosions.remove(explosion)

        # 绘制游戏元素
        screen.fill(BLACK)
        
        # 绘制障碍物
        for obstacle in obstacles:
            obstacle.draw(screen)
        
        # 绘制道具
        for power_up in power_ups:
            power_up.draw(screen)
        
        # 绘制坦克
        if not game_over:
            player.draw(screen)
        for tank in enemy_tanks:
            tank.draw(screen)
        
        # 绘制子弹
        for bullet in bullets:
            bullet.draw(screen)
        
        # 绘制爆炸
        for explosion in explosions:
            explosion.draw(screen)
        
        # 绘制游戏状态信息
        draw_text(screen, f"分数: {score}", 24, 70, 20, WHITE, "center")
        draw_text(screen, f"关卡: {level}", 24, SCREEN_WIDTH - 70, 20, WHITE, "center")
        draw_text(screen, f"生命: {lives}", 24, SCREEN_WIDTH // 2, 20, WHITE, "center")
        
        # 绘制关卡完成信息
        if level_cleared:
            s = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
            s.fill((0, 0, 0, 128))
            screen.blit(s, (0, 0))
            draw_text(screen, f"关卡 {level} 完成!", 48, SCREEN_WIDTH//2, SCREEN_HEIGHT//2 - 50)
            draw_text(screen, "即将进入下一关...", 24, SCREEN_WIDTH//2, SCREEN_HEIGHT//2 + 30)
        
        # 绘制游戏结束画面
        if game_over:
            s = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
            s.fill((0, 0, 0, 192))
            screen.blit(s, (0, 0))
            
            draw_text(screen, "游戏结束", 64, SCREEN_WIDTH//2, SCREEN_HEIGHT//2 - 100)
            draw_text(screen, f"最终分数: {score}", 36, SCREEN_WIDTH//2, SCREEN_HEIGHT//2 - 20)
            draw_text(screen, f"达到关卡: {level}", 36, SCREEN_WIDTH//2, SCREEN_HEIGHT//2 + 30)
            draw_text(screen, "按 R 重新开始", 24, SCREEN_WIDTH//2, SCREEN_HEIGHT//2 + 100)
            draw_text(screen, "按 Q 退出游戏", 24, SCREEN_WIDTH//2, SCREEN_HEIGHT//2 + 140)

        pygame.display.flip()
        clock.tick(FPS)
    
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    game_loop()

坦克大战运行文档

一. 运行环境

  • 操作系统:Windows/macOS/Linux
  • Python 版本:Python 3.6 及以上
  • 依赖库:Pygame 2.0 及以上

二、安装步骤

1.安装 Python:

2.安装 Pygame 库:

  • 打开命令提示符(Windows)或终端(macOS/Linux)
  • 执行以下命令:
bash 复制代码
pip install pygame

三、运行游戏

  1. 将上述代码保存为tank_game.py文件
  2. 打开命令提示符 / 终端,导航到代码文件所在目录
  3. 执行以下命令启动游戏:

四、游戏操作说明

bash 复制代码
操作	   按键	              功能描述
移动上	   ↑ 或 W	          控制坦克向上移动
移动下	   ↓ 或 S	          控制坦克向下移动
移动左	   ← 或 A	          控制坦克向左移动
移动右      → 或 D	          控制坦克向右移动
射击       空格	              发射子弹
重新开始	   R	              游戏结束后重新开始
退出游戏	   Q	              游戏结束后退出

五、游戏规则说明

  1. 基本目标:
  • 控制绿色坦克消灭所有敌方红色坦克
  • 每消灭一个敌方坦克获得分数(基础 100 分 + 关卡加成)
  • 完成当前关卡所有敌人后自动进入下一关
  1. 生命值与生命数:
  • 玩家坦克初始有 1 点生命值和 3 条生命
  • 被敌人子弹击中会减少生命值
  • 生命值耗尽时失去一条生命并重生
  • 生命数为 0 时游戏结束
  1. 障碍物系统:
  • 灰色砖块:可以被子弹摧毁
  • 深色钢铁:普通子弹无法摧毁,需要增强型子弹
  • 边界墙:不可摧毁,用于限制游戏区域
  • 玩家出生点:初始有保护,不会生成障碍物
  1. 敌方坦克:
  • 随关卡提升会出现不同类型的敌方坦克
  • 普通坦克:红色,速度中等,1 点生命值
  • 快速坦克:浅红色,速度快,1 点生命值
  • 重型坦克:深红色,速度慢,2 点生命值
  • 敌方坦克会自动移动和射击,等级越高 AI 越智能
  1. 道具系统:
  • 摧毁障碍物或敌方坦克时有概率掉落道具
  • 蓝色:提升移动速度
  • 黄色:增强子弹威力(可摧毁钢铁)
  • 绿色:增加生命值
  • 浅蓝色:获得短暂无敌状态
  1. 关卡系统:
  • 每关敌人数量和难度随关卡提升
  • 关卡越高,敌方坦克 AI 越智能
  • 每 3 关奖励一条额外生命
  • 障碍物布局每关随机生成

六、常见问题解决

  1. 中文显示异常:
  • 程序会自动检测并使用系统中的中文字体
  • 若仍显示异常,确保系统中安装了 SimHei、WenQuanYi Micro Hei 等中文字体
  1. 游戏运行卡顿:
  • 尝试关闭其他占用系统资源的程序
  • 降低游戏窗口大小(需修改代码中 SCREEN_WIDTH 和 SCREEN_HEIGHT 参数)
  1. 无法启动游戏:
  • 检查 Python 是否正确安装并添加到环境变量
  • 确认 Pygame 库已正确安装
  • 尝试更新 Pygame:pip install --upgrade pygame
  1. 控制无响应:
  • 检查键盘是否正常工作
  • 确保游戏窗口处于激活状态

七、游戏进阶技巧

  1. 利用障碍物作为掩护,减少被敌方击中的概率
  2. 优先摧毁威胁大的快速坦克和重型坦克
  3. 留意道具掉落,尤其是增强子弹和无敌状态
  4. 保持移动可以降低被敌方瞄准的概率
  5. 关卡后期可利用地形优势与敌人周旋
相关推荐
PieroPc13 小时前
一个基于Python Streamlit sqlite3 的销售单管理系统,提供商品管理、客户管理、销售单管理及打印,和应收对账单等功能
python·oracle·sqlite·streamlit
月下倩影时13 小时前
视觉进阶篇—— PyTorch 安装
人工智能·pytorch·python
Valueyou2414 小时前
论文阅读——CenterNet
论文阅读·python·opencv·目标检测·计算机视觉
孤狼warrior14 小时前
目前最新同花顺金融股市数据爬取 JS逆向+node.js补浏览器环境
javascript·爬虫·python·金融·node.js
蒋星熠14 小时前
全栈开发实战指南:从架构设计到部署运维
运维·c++·python·系统架构·node.js·devops·c5全栈
小小王app小程序开发14 小时前
淘宝扭蛋机小程序:电商娱乐化赛道的机遇挖掘与风险防控
小程序·娱乐
说私域14 小时前
基于开源AI智能名片链动2+1模式与S2B2C商城小程序的商家活动策略研究
人工智能·小程序
低代码布道师14 小时前
医疗小程序07设置默认卡
低代码·小程序
程序员爱钓鱼15 小时前
Python 编程实战 · 实用工具与库 — Flask 基础入门
后端·python·面试
程序员爱钓鱼15 小时前
Python编程实战 - Python实用工具与库 - 文件批量处理脚本
后端·python·面试