如何将 Python代码打包成 exe程序

这篇文章主要介绍了如何把python 代码打包成可执行软件,具有一定借鉴价值,需要的朋友可以参考下。 

1.首先python代码需要能运行。 

import pygame
import random
import sys

# 初始化 Pygame
pygame.init()

# 游戏常量
WIDTH, HEIGHT = 800, 600
GRID_SIZE = 20
GRID_WIDTH = WIDTH // GRID_SIZE
GRID_HEIGHT = HEIGHT // GRID_SIZE

# 颜色定义
BLACK = (18, 18, 18)          # 背景色
SNAKE_COLOR = (46, 204, 113)  # 蛇身颜色
SNAKE_HEAD_COLOR = (34, 197, 94)  # 蛇头颜色
FOOD_COLOR = (239, 68, 68)    # 食物颜色
TEXT_COLOR = (243, 244, 246)  # 文字颜色
BORDER_COLOR = (75, 85, 99)   # 边框颜色
HIGHLIGHT_COLOR = (255, 255, 255, 40)  # 蛇头高光
PAUSE_OVERLAY = (0, 0, 0, 128)  # 暂停遮罩

# 全局变量初始化
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)
pygame.display.set_caption("贪吃蛇游戏")
clock = pygame.time.Clock()
FPS = 10

# 游戏状态变量
snake = []
food = ()
direction = (1, 0)
next_direction = (1, 0)
score = 0
high_score = 0
game_started = False
game_paused = False
game_over = False


def init_snake():
    """初始化蛇的位置"""
    global snake
    snake = [
        (GRID_WIDTH // 2, GRID_HEIGHT // 2),
        (GRID_WIDTH // 2 - 1, GRID_HEIGHT // 2),
        (GRID_WIDTH // 2 - 2, GRID_HEIGHT // 2)
    ]


def generate_food():
    """生成食物,确保不在蛇身上"""
    global food
    while True:
        food = (
            random.randint(1, GRID_WIDTH - 2),
            random.randint(1, GRID_HEIGHT - 2)
        )
        if food not in snake:
            break


def get_suitable_font(size):
    """选择系统中可用的字体,优先支持中文"""
    preferred_fonts = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC", "Arial", "sans-serif"]
    for font in preferred_fonts:
        if font in pygame.font.get_fonts() or pygame.font.match_font(font):
            return pygame.font.SysFont(font, size)
    return pygame.font.Font(None, size)


def draw_snake():
    """绘制蛇,头部使用不同颜色"""
    global screen
    for i, (x, y) in enumerate(snake):
        rect = pygame.Rect(
            x * GRID_SIZE,
            y * GRID_SIZE,
            GRID_SIZE - 1,
            GRID_SIZE - 1
        )
        color = SNAKE_HEAD_COLOR if i == 0 else SNAKE_COLOR
        pygame.draw.rect(screen, color, rect, border_radius=5)

        # 头部高光效果
        if i == 0:
            highlight = pygame.Surface((GRID_SIZE - 1, GRID_SIZE - 1), pygame.SRCALPHA)
            highlight.fill(HIGHLIGHT_COLOR)
            screen.blit(highlight, (x * GRID_SIZE, y * GRID_SIZE))


def draw_food():
    """绘制带脉动效果的食物"""
    global screen
    x, y = food
    pulse = (pygame.time.get_ticks() % 1000) / 1000
    radius = GRID_SIZE // 2 - 2 + int(pulse * 2)
    pygame.draw.circle(
        screen,
        FOOD_COLOR,
        (x * GRID_SIZE + GRID_SIZE // 2, y * GRID_SIZE + GRID_SIZE // 2),
        radius
    )


def draw_score():
    """绘制得分和最高分"""
    global screen, score, high_score
    font = get_suitable_font(28)

    score_text = font.render(f"得分: {score}", True, TEXT_COLOR)
    score_rect = score_text.get_rect(topleft=(15, 15))

    high_score_text = font.render(f"最高分: {high_score}", True, TEXT_COLOR)
    high_score_rect = high_score_text.get_rect(topleft=(15, 50))

    bg_rect = pygame.Rect(10, 10, 200, 80)
    pygame.draw.rect(screen, BORDER_COLOR, bg_rect, 2, border_radius=5)

    screen.blit(score_text, score_rect)
    screen.blit(high_score_text, high_score_rect)


def draw_message(text, y_offset=0, size=48):
    """绘制提示信息"""
    global screen
    font = get_suitable_font(size)
    text_surface = font.render(text, True, TEXT_COLOR)
    text_rect = text_surface.get_rect(center=(WIDTH // 2, HEIGHT // 2 + y_offset))

    bg_rect = text_rect.inflate(30, 20)
    pygame.draw.rect(screen, BORDER_COLOR, bg_rect, 2, border_radius=10)
    screen.blit(text_surface, text_rect)


def draw_border():
    """绘制游戏边框"""
    global screen
    border_rect = pygame.Rect(2, 2, WIDTH - 4, HEIGHT - 4)
    pygame.draw.rect(screen, BORDER_COLOR, border_rect, 4, border_radius=10)


def draw_pause_overlay():
    """绘制暂停遮罩"""
    global screen
    overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
    overlay.fill(PAUSE_OVERLAY)
    screen.blit(overlay, (0, 0))


def reset_game():
    """重置所有游戏状态,确保R键重开功能可靠"""
    global direction, next_direction, score, game_started, game_paused, game_over, high_score
    if score > high_score:
        high_score = score
    init_snake()
    generate_food()
    direction = (1, 0)
    next_direction = (1, 0)
    score = 0
    game_started = False
    game_paused = False
    game_over = False


def main():
    """主游戏循环,整合所有功能并修复所有已知问题"""
    global direction, next_direction, score, game_started, game_paused, game_over, FPS
    global WIDTH, HEIGHT, screen

    # 初始化屏幕
    screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)
    pygame.display.set_caption("贪吃蛇游戏")

    reset_game()  # 初始化游戏状态

    running = True
    while running:
        # 事件处理
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            # 窗口大小调整事件
            elif event.type == pygame.VIDEORESIZE:
                WIDTH, HEIGHT = event.w, event.h
                screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)

            # 键盘事件
            elif event.type == pygame.KEYDOWN:
                # 空格键控制开始/暂停
                if event.key == pygame.K_SPACE:
                    if not game_started:
                        game_started = True
                    elif not game_over:
                        game_paused = not game_paused

                # R键重新开始游戏(任何状态下均可)
                elif event.key == pygame.K_r:
                    reset_game()

                # 方向键控制
                if game_started and not game_paused and not game_over:
                    if event.key == pygame.K_UP and direction != (0, 1):
                        next_direction = (0, -1)
                    elif event.key == pygame.K_DOWN and direction != (0, -1):
                        next_direction = (0, 1)
                    elif event.key == pygame.K_LEFT and direction != (1, 0):
                        next_direction = (-1, 0)
                    elif event.key == pygame.K_RIGHT and direction != (-1, 0):
                        next_direction = (1, 0)

        # 游戏逻辑更新
        if game_started and not game_paused and not game_over:
            direction = next_direction
            head_x, head_y = snake[0]
            new_head = (head_x + direction[0], head_y + direction[1])

            # 碰撞检测
            if (new_head[0] < 0 or new_head[0] >= GRID_WIDTH or
                    new_head[1] < 0 or new_head[1] >= GRID_HEIGHT or
                    new_head in snake[1:]):
                game_over = True

            # 更新蛇身体
            if not game_over:
                snake.insert(0, new_head)
                if new_head == food:
                    score += 1
                    generate_food()
                    # 每得5分加速
                    if score % 5 == 0 and FPS < 20:
                        FPS += 1

                else:
                    snake.pop()

        # 绘制所有元素
        screen.fill(BLACK)
        draw_border()
        draw_snake()
        draw_food()
        draw_score()

        # 暂停遮罩
        if game_paused:
            draw_pause_overlay()

        # 状态提示
        if not game_started:
            draw_message("按空格键开始游戏", -50, 36)
            draw_message("方向键控制移动", 50, 28)
        elif game_paused:
            draw_message("游戏暂停", -50, 36)
            draw_message("按空格键继续", 50, 28)
        elif game_over:
            draw_message(f"游戏结束!得分: {score}", -50, 36)
            draw_message("按 R 键重新开始", 50, 28)

        pygame.display.update()
        clock.tick(FPS)

    pygame.quit()
    sys.exit()


if __name__ == "__main__":
    main()

 这是关于贪吃蛇小游戏代码。

 如何将 Python代码打包成 exe程序_第1张图片

注意:需要安装pip install pygame 

 1.找到文件路径

2.安装pip install pyinstaller(pyinstaller:是一个常用的第三方 Python 库,它的主要功能是将 Python 脚本及其所有依赖项(包括各种库、资源文件等 )打包成可执行文件(比如在 Windows 系统下生成 .exe 文件 )。这样一来,即使在没有安装 Python 环境的计算机上,也能直接运行打包后的程序。) 

如何将 Python代码打包成 exe程序_第2张图片

 如果安装过慢:pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyinstaller

 如何将 Python代码打包成 exe程序_第3张图片

 3.pyinstaller -F python.py

 如何将 Python代码打包成 exe程序_第4张图片 

执行这个命令后,PyInstaller 会在当前目录下创建 dist 和 build 文件夹,最终生成的单个可执行文件会放在 dist 文件夹中,文件名通常为 python.exe(Windows 系统)。打开资源管理器

 如何将 Python代码打包成 exe程序_第5张图片 

如何将 Python代码打包成 exe程序_第6张图片 

点击运行或复制转发。 

本次讲解就到这了请大佬们,点点赞

 

你可能感兴趣的:(基础,python,pygame,开发语言)