采用GPT生成的Python 的 2048 游戏

采用GPT生成的Python 的 2048 游戏

文章说明

采用GPT生成的一个小工具,作为一个python开发小游戏的demo,打发时间的小代码,后续可以考虑继续利用GPT生成更多有趣的小游戏

核心代码

2048小游戏-1.0版本

python 复制代码
import pygame
import random

# 初始化 Pygame
pygame.init()

# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BACKGROUND_COLOR = (187, 173, 160)  # 背景颜色
CELL_COLORS = {
    0: (205, 193, 180),  # 空白单元格颜色
    2: (238, 228, 218),
    4: (237, 224, 200),
    8: (242, 177, 121),
    16: (245, 149, 99),
    32: (246, 124, 95),
    64: (246, 94, 59),
    128: (237, 207, 114),
    256: (237, 204, 97),
    512: (237, 200, 80),
    1024: (237, 197, 63),
    2048: (237, 194, 46),
}
TEXT_COLOR = (119, 110, 101)  # 文字颜色

# 定义屏幕尺寸和格子大小
GRID_SIZE = 4
CELL_SIZE = 100
GAP = 10  # 单元格之间的间隙
WIDTH = GRID_SIZE * (CELL_SIZE + GAP) + GAP  # 计算窗口宽度
HEIGHT = WIDTH  # 窗口高度与宽度一致,去除下方多余区域

# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("2048 游戏")

# 定义字体
font = pygame.font.SysFont("Arial", 36, bold=True)
small_font = pygame.font.SysFont("Arial", 24, bold=True)

# 初始化游戏网格
grid = [[0] * GRID_SIZE for _ in range(GRID_SIZE)]

# 随机生成一个 2 或 4
def add_random_tile():
    empty_cells = [(i, j) for i in range(GRID_SIZE) for j in range(GRID_SIZE) if grid[i][j] == 0]
    if empty_cells:
        i, j = random.choice(empty_cells)
        grid[i][j] = random.choice([2, 4])

# 初始化游戏
def initialize_game():
    global grid
    grid = [[0] * GRID_SIZE for _ in range(GRID_SIZE)]
    add_random_tile()
    add_random_tile()

# 绘制网格
def draw_grid():
    for i in range(GRID_SIZE):
        for j in range(GRID_SIZE):
            value = grid[i][j]
            color = CELL_COLORS.get(value, WHITE)
            # 绘制单元格背景
            pygame.draw.rect(
                screen,
                color,
                (
                    j * (CELL_SIZE + GAP) + GAP,
                    i * (CELL_SIZE + GAP) + GAP,
                    CELL_SIZE,
                    CELL_SIZE,
                ),
                border_radius=5,
            )
            # 绘制精美的边框
            pygame.draw.rect(
                screen,
                (187, 173, 160),  # 边框颜色
                (
                    j * (CELL_SIZE + GAP) + GAP,
                    i * (CELL_SIZE + GAP) + GAP,
                    CELL_SIZE,
                    CELL_SIZE,
                ),
                2,
                border_radius=5,
            )
            if value != 0:
                text = font.render(str(value), True, TEXT_COLOR)
                text_rect = text.get_rect(
                    center=(
                        j * (CELL_SIZE + GAP) + GAP + CELL_SIZE // 2,
                        i * (CELL_SIZE + GAP) + GAP + CELL_SIZE // 2,
                    )
                )
                screen.blit(text, text_rect)

# 移动方块
def move(direction):
    global grid
    moved = False

    if direction == "left":
        for i in range(GRID_SIZE):
            row = grid[i]
            new_row = merge(row)
            if row != new_row:
                grid[i] = new_row
                moved = True

    elif direction == "right":
        for i in range(GRID_SIZE):
            row = grid[i][::-1]
            new_row = merge(row)
            if row != new_row:
                grid[i] = new_row[::-1]
                moved = True

    elif direction == "up":
        for j in range(GRID_SIZE):
            column = [grid[i][j] for i in range(GRID_SIZE)]
            new_column = merge(column)
            if column != new_column:
                for i in range(GRID_SIZE):
                    grid[i][j] = new_column[i]
                moved = True

    elif direction == "down":
        for j in range(GRID_SIZE):
            column = [grid[i][j] for i in range(GRID_SIZE)][::-1]
            new_column = merge(column)
            if column != new_column:
                new_column = new_column[::-1]
                for i in range(GRID_SIZE):
                    grid[i][j] = new_column[i]
                moved = True

    if moved:
        add_random_tile()

# 合并行或列
def merge(line):
    new_line = [0] * GRID_SIZE
    index = 0
    for value in line:
        if value != 0:
            if new_line[index] == 0:
                new_line[index] = value
            elif new_line[index] == value:
                new_line[index] *= 2
                index += 1
            else:
                index += 1
                new_line[index] = value
    return new_line

# 检查游戏是否结束
def is_game_over():
    for i in range(GRID_SIZE):
        for j in range(GRID_SIZE):
            if grid[i][j] == 0:
                return False
            if i < GRID_SIZE - 1 and grid[i][j] == grid[i + 1][j]:
                return False
            if j < GRID_SIZE - 1 and grid[i][j] == grid[i][j + 1]:
                return False
    return True

# 游戏主循环
def game_loop():
    initialize_game()
    running = True

    while running:
        screen.fill(BACKGROUND_COLOR)  # 设置背景颜色
        draw_grid()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    move("left")
                elif event.key == pygame.K_RIGHT:
                    move("right")
                elif event.key == pygame.K_UP:
                    move("up")
                elif event.key == pygame.K_DOWN:
                    move("down")

        if is_game_over():
            screen.fill(BACKGROUND_COLOR)
            text = font.render("游戏结束!", True, TEXT_COLOR)
            text_rect = text.get_rect(center=(WIDTH // 2, HEIGHT // 2))
            screen.blit(text, text_rect)
            pygame.display.update()
            pygame.time.wait(2000)
            running = False

        pygame.display.update()

    pygame.quit()

# 启动游戏
game_loop()

2048小游戏-2.0版本.py

python 复制代码
import pygame
import random
import json
import os

# 初始化 Pygame
pygame.init()

# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BACKGROUND_COLOR = (187, 173, 160)  # 背景颜色
CELL_COLORS = {
    0: (205, 193, 180),  # 空白单元格颜色
    2: (238, 228, 218),
    4: (237, 224, 200),
    8: (242, 177, 121),
    16: (245, 149, 99),
    32: (246, 124, 95),
    64: (246, 94, 59),
    128: (237, 207, 114),
    256: (237, 204, 97),
    512: (237, 200, 80),
    1024: (237, 197, 63),
    2048: (237, 194, 46),
}
TEXT_COLOR = (119, 110, 101)  # 文字颜色

# 定义屏幕尺寸和格子大小
GRID_SIZE = 4
CELL_SIZE = 100
GAP = 10  # 单元格之间的间隙
WIDTH = GRID_SIZE * (CELL_SIZE + GAP) + GAP  # 计算窗口宽度
HEIGHT = WIDTH + 120  # 增加底部区域用于显示得分和按钮

# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("2048 游戏")

# 定义字体(使用支持中文的字体)
try:
    # 加载支持中文的字体文件(确保字体文件在项目目录中)
    font_path = "SimHei.ttf"  # 黑体字体文件
    font = pygame.font.Font(font_path, 36)  # 主字体
    small_font = pygame.font.Font(font_path, 24)  # 小字体
except FileNotFoundError:
    print("未找到字体文件,使用默认字体(可能不支持中文)。")
    font = pygame.font.SysFont("Arial", 36, bold=True)
    small_font = pygame.font.SysFont("Arial", 24, bold=True)

# 初始化游戏网格
grid = [[0] * GRID_SIZE for _ in range(GRID_SIZE)]
score = 0
high_score = 0

# 存档文件路径
SAVE_FOLDER = "saves"
if not os.path.exists(SAVE_FOLDER):
    os.makedirs(SAVE_FOLDER)

# 加载排行榜
def load_high_score():
    global high_score
    try:
        with open(os.path.join(SAVE_FOLDER, "high_score.json"), "r") as f:
            high_score = json.load(f).get("high_score", 0)
    except FileNotFoundError:
        high_score = 0

# 保存排行榜
def save_high_score():
    with open(os.path.join(SAVE_FOLDER, "high_score.json"), "w") as f:
        json.dump({"high_score": high_score}, f)

# 随机生成一个 2 或 4
def add_random_tile():
    empty_cells = [(i, j) for i in range(GRID_SIZE) for j in range(GRID_SIZE) if grid[i][j] == 0]
    if empty_cells:
        i, j = random.choice(empty_cells)
        grid[i][j] = random.choice([2, 4])

# 初始化游戏
def initialize_game():
    global grid, score
    grid = [[0] * GRID_SIZE for _ in range(GRID_SIZE)]
    score = 0
    add_random_tile()
    add_random_tile()

# 绘制网格
def draw_grid():
    for i in range(GRID_SIZE):
        for j in range(GRID_SIZE):
            value = grid[i][j]
            color = CELL_COLORS.get(value, WHITE)
            # 绘制单元格背景
            pygame.draw.rect(
                screen,
                color,
                (
                    j * (CELL_SIZE + GAP) + GAP,
                    i * (CELL_SIZE + GAP) + GAP,
                    CELL_SIZE,
                    CELL_SIZE,
                ),
                border_radius=5,
            )
            # 绘制精美的边框
            pygame.draw.rect(
                screen,
                (187, 173, 160),  # 边框颜色
                (
                    j * (CELL_SIZE + GAP) + GAP,
                    i * (CELL_SIZE + GAP) + GAP,
                    CELL_SIZE,
                    CELL_SIZE,
                ),
                2,
                border_radius=5,
            )
            if value != 0:
                text = font.render(str(value), True, TEXT_COLOR)
                text_rect = text.get_rect(
                    center=(
                        j * (CELL_SIZE + GAP) + GAP + CELL_SIZE // 2,
                        i * (CELL_SIZE + GAP) + GAP + CELL_SIZE // 2,
                    )
                )
                screen.blit(text, text_rect)

# 绘制得分和按钮
def draw_ui():
    # 绘制当前得分
    score_text = small_font.render(f"得分: {score}", True, TEXT_COLOR)
    screen.blit(score_text, (GAP, HEIGHT - 110))

    # 绘制最高得分
    high_score_text = small_font.render(f"最高得分: {high_score}", True, TEXT_COLOR)
    screen.blit(high_score_text, (GAP, HEIGHT - 80))

    # 绘制保存按钮
    save_button = pygame.Rect(WIDTH - 150, HEIGHT - 110, 140, 40)
    pygame.draw.rect(screen, (143, 122, 102), save_button, border_radius=5)
    save_text = small_font.render("保存游戏", True, WHITE)
    screen.blit(save_text, (WIDTH - 140, HEIGHT - 100))

    # 绘制加载按钮
    load_button = pygame.Rect(WIDTH - 150, HEIGHT - 60, 140, 40)
    pygame.draw.rect(screen, (143, 122, 102), load_button, border_radius=5)
    load_text = small_font.render("加载游戏", True, WHITE)
    screen.blit(load_text, (WIDTH - 140, HEIGHT - 50))

    return save_button, load_button

# 移动方块
def move(direction):
    global grid, score, high_score
    moved = False

    if direction == "left":
        for i in range(GRID_SIZE):
            row = grid[i]
            new_row, row_score = merge(row)
            if row != new_row:
                grid[i] = new_row
                moved = True
                score += row_score

    elif direction == "right":
        for i in range(GRID_SIZE):
            row = grid[i][::-1]
            new_row, row_score = merge(row)
            if row != new_row:
                grid[i] = new_row[::-1]
                moved = True
                score += row_score

    elif direction == "up":
        for j in range(GRID_SIZE):
            column = [grid[i][j] for i in range(GRID_SIZE)]
            new_column, col_score = merge(column)
            if column != new_column:
                for i in range(GRID_SIZE):
                    grid[i][j] = new_column[i]
                moved = True
                score += col_score

    elif direction == "down":
        for j in range(GRID_SIZE):
            column = [grid[i][j] for i in range(GRID_SIZE)][::-1]
            new_column, col_score = merge(column)
            if column != new_column:
                new_column = new_column[::-1]
                for i in range(GRID_SIZE):
                    grid[i][j] = new_column[i]
                moved = True
                score += col_score

    if moved:
        add_random_tile()
        if score > high_score:
            high_score = score
            save_high_score()

# 合并行或列
def merge(line):
    new_line = [0] * GRID_SIZE
    index = 0
    score = 0
    for value in line:
        if value != 0:
            if new_line[index] == 0:
                new_line[index] = value
            elif new_line[index] == value:
                new_line[index] *= 2
                score += new_line[index]
                index += 1
            else:
                index += 1
                new_line[index] = value
    return new_line, score

# 检查游戏是否结束
def is_game_over():
    for i in range(GRID_SIZE):
        for j in range(GRID_SIZE):
            if grid[i][j] == 0:
                return False
            if i < GRID_SIZE - 1 and grid[i][j] == grid[i + 1][j]:
                return False
            if j < GRID_SIZE - 1 and grid[i][j] == grid[i][j + 1]:
                return False
    return True

# 获取所有存档
def get_save_files():
    return [f for f in os.listdir(SAVE_FOLDER) if f.endswith(".json") and f != "high_score.json"]

# 保存游戏
def save_game():
    save_files = get_save_files()
    if not save_files:
        save_name = "存档1"
    else:
        save_name = f"存档{len(save_files) + 1}"
    save_data = {
        "grid": grid,
        "score": score,
    }
    with open(os.path.join(SAVE_FOLDER, f"{save_name}.json"), "w") as f:
        json.dump(save_data, f)
    print(f"游戏已保存为: {save_name}")

# 加载游戏
def load_game():
    save_files = get_save_files()
    if not save_files:
        print("无存档可供加载!")
        return

    # 显示存档列表
    print("请选择要加载的存档:")
    for i, save_file in enumerate(save_files):
        print(f"{i + 1}. {save_file}")

    # 选择存档
    choice = input("请输入存档编号: ")
    try:
        choice = int(choice) - 1
        if 0 <= choice < len(save_files):
            save_name = save_files[choice]
            with open(os.path.join(SAVE_FOLDER, save_name), "r") as f:
                save_data = json.load(f)
                global grid, score
                grid = save_data["grid"]
                score = save_data["score"]
            print(f"已加载存档: {save_name}")
        else:
            print("无效的选择!")
    except ValueError:
        print("请输入有效的编号!")

# 游戏主循环
def game_loop():
    initialize_game()
    load_high_score()
    running = True

    while running:
        screen.fill(BACKGROUND_COLOR)  # 设置背景颜色
        draw_grid()
        save_button, load_button = draw_ui()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    move("left")
                elif event.key == pygame.K_RIGHT:
                    move("right")
                elif event.key == pygame.K_UP:
                    move("up")
                elif event.key == pygame.K_DOWN:
                    move("down")
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if save_button.collidepoint(event.pos):
                    save_game()
                elif load_button.collidepoint(event.pos):
                    load_game()

        if is_game_over():
            screen.fill(BACKGROUND_COLOR)
            text = font.render("游戏结束!", True, TEXT_COLOR)
            text_rect = text.get_rect(center=(WIDTH // 2, HEIGHT // 2))
            screen.blit(text, text_rect)
            pygame.display.update()
            pygame.time.wait(2000)
            running = False

        pygame.display.update()

    pygame.quit()

# 启动游戏
game_loop()

效果展示

2048 小游戏 - 1.0 版本

2048 小游戏 - 2.0 版本

源码下载

Python 的 2048 游戏

相关推荐
黑客Jack18 分钟前
[Python/网络安全] Git漏洞之Githack工具基本安装及使用详析
git·python·web安全
十二测试录18 分钟前
Android SDK下载安装(图文详解)
android·经验分享·python·程序人生·adb·自动化
墨绿色的摆渡人33 分钟前
pytorch小记(七):pytorch中的保存/加载模型操作
人工智能·pytorch·python
墨绿色的摆渡人36 分钟前
pytorch小记(三):pytorch中的最大值操作:x.max()
人工智能·pytorch·python
风槐啊1 小时前
PyCharm 的安装与使用(Window)
ide·python·pycharm
Serendipity_Carl1 小时前
爬虫基础之爬取歌曲宝歌曲批量下载
爬虫·python·pycharm
坐吃山猪1 小时前
卷积神经04-TensorFlow环境安装
人工智能·python·tensorflow
IT古董1 小时前
【漫话机器学习系列】045.特征向量(Eigenvector)
人工智能·python·机器学习
墨鱼丸家2 小时前
dbscan 聚类并可视化简单案例
python
呆头呆脑~2 小时前
逆向 易九批 最新版 爬虫逆向 x-sign ......
javascript·爬虫·python·算法·网络爬虫