采用GPT生成的Python 的 2048 游戏

server/2025/1/16 20:30:43/

采用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 gridgrid = [[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 gridmoved = Falseif direction == "left":for i in range(GRID_SIZE):row = grid[i]new_row = merge(row)if row != new_row:grid[i] = new_rowmoved = Trueelif 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 = Trueelif 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 = Trueelif 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 = Trueif moved:add_random_tile()# 合并行或列
def merge(line):new_line = [0] * GRID_SIZEindex = 0for value in line:if value != 0:if new_line[index] == 0:new_line[index] = valueelif new_line[index] == value:new_line[index] *= 2index += 1else:index += 1new_line[index] = valuereturn new_line# 检查游戏是否结束
def is_game_over():for i in range(GRID_SIZE):for j in range(GRID_SIZE):if grid[i][j] == 0:return Falseif i < GRID_SIZE - 1 and grid[i][j] == grid[i + 1][j]:return Falseif j < GRID_SIZE - 1 and grid[i][j] == grid[i][j + 1]:return Falsereturn True# 游戏主循环
def game_loop():initialize_game()running = Truewhile running:screen.fill(BACKGROUND_COLOR)  # 设置背景颜色draw_grid()for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseelif 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 = Falsepygame.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_scoretry: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, scoregrid = [[0] * GRID_SIZE for _ in range(GRID_SIZE)]score = 0add_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_scoremoved = Falseif direction == "left":for i in range(GRID_SIZE):row = grid[i]new_row, row_score = merge(row)if row != new_row:grid[i] = new_rowmoved = Truescore += row_scoreelif 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 = Truescore += row_scoreelif 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 = Truescore += col_scoreelif 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 = Truescore += col_scoreif moved:add_random_tile()if score > high_score:high_score = scoresave_high_score()# 合并行或列
def merge(line):new_line = [0] * GRID_SIZEindex = 0score = 0for value in line:if value != 0:if new_line[index] == 0:new_line[index] = valueelif new_line[index] == value:new_line[index] *= 2score += new_line[index]index += 1else:index += 1new_line[index] = valuereturn 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 Falseif i < GRID_SIZE - 1 and grid[i][j] == grid[i + 1][j]:return Falseif j < GRID_SIZE - 1 and grid[i][j] == grid[i][j + 1]:return Falsereturn 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) - 1if 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, scoregrid = 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 = Truewhile 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 = Falseelif 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 = Falsepygame.display.update()pygame.quit()# 启动游戏
game_loop()

效果展示

2048 小游戏 - 1.0 版本
在这里插入图片描述

2048 小游戏 - 2.0 版本
在这里插入图片描述

源码下载

Python 的 2048 游戏


http://www.ppmy.cn/server/158908.html

相关文章

Redis快速入门店铺营业状态设置

Redis简介 Redis是一种基于内存的键值对&#xff08;K-V&#xff09;数据库。 这意味着它与MySQL数据库类似&#xff0c;都能够用于存储数据&#xff0c;但两者又有着本质的区别。首先两者存储数据的结构不一样&#xff0c;Redis通过键&#xff08;key&#xff09;和值…

在 Alpine Linux 下通过 Docker 部署 PostgreSQL 服务器

简要介绍 Docker 是一个开源的容器化平台&#xff0c;它使得开发者能够轻松创建、部署和运行应用程序。通过使用 Docker&#xff0c;程序员可以把应用及其所有依赖打包在一个轻量级的容器中&#xff0c;这样可以确保在不同环境中的一致性。PostgreSQL&#xff08;简称 psql&am…

北邮团队在Nature Medicine发表MedFound——辅助疾病诊断的通用医学语言模型|顶刊速递·25-01-15

小罗碎碎念 这篇文章介绍了一个名为MedFound的通用医学语言模型&#xff0c;该模型拥有1760亿参数&#xff0c;通过大规模医学文本和真实世界临床记录的预训练&#xff0c;以及基于自引导策略的推理方法微调&#xff0c;能够辅助疾病诊断。 在多个专业领域内&#xff0c;无论是…

怎么分析网页游戏中的数据 官方API 数据挖掘 第三方工具Overwolf、LoLalytics

要分析里面“”这个游戏的数据&#xff0c;你可以采用以下几种方法&#xff1a; ### 1. 使用官方API - **注册和认证**&#xff1a;首先&#xff0c;在游戏的官方网站或API平台上注册一个开发者账号&#xff0c;并完成认证&#xff0c;以获取API密钥。 - **阅读API文档**&…

MySQL_JDBC编程

Java中操作数据库&#xff0c;最基础的方式就是JDBC 1.准备工作&#xff1a;需要引入MySQL的JDBC驱动包 &#x1f352;这种驱动包&#xff0c;属于“第三方库” 不是JDK里原生就有的&#xff0c;就需要通过其他途径下载下来并引入到项目中 2.把jar引入到项目中 import com.m…

【Vue3 入门到实战】2. OptionsAPI与CompositionAPI及setup

目录 1. 介绍 1.1 OptionsAPI 1.2 CompositionAPI 2. setup 2.1 setup 概述 2.2 setup 特点 2.3 setup 与OptionsAPI 的关系 2.4 setup语法糖 3. 总结 1. 介绍 1.1 OptionsAPI 选项式 API 是 Vue 2 中的传统模式&#xff0c;并且在 Vue 3 中仍然得到支持。它通过在组…

【搭建JavaEE】(2)Tomcat安装配置和第一个JavaEE程序

Tomcat–容器(Container) 下载 Apache Tomcat - Welcome! 下载完成 请求/响应 结构 测试 查看Jdk版本 改端口号localhost8080–>8099 学学人家以后牛逼了可以用自己名字当文件夹名 配置端口8099 找到server文件 用记事本打开 再打开另一个logging文件 ”乱码解决“步骤&…

GitHub打不开的解决方案

在国内github官网经常面临打不开或访问极慢的问题&#xff0c;那有什么好办法解决GitHub官网访问不了的问题&#xff1f;今天来教你几招轻松访问github官网。 首先我们说下github官网打不开的原因到底是什么。我们会发现&#xff0c;github偶尔可以打开&#xff0c;偶尔打不开&…