采用GPT生成的Python 的 2048 游戏

devtools/2025/1/12 9:48:06/

采用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/devtools/149840.html

相关文章

/src/utils/request.ts:axios 请求封装,适用于需要统一处理请求和响应的场景

文章目录 数据结构解释1. 核心功能2. 代码结构分析请求拦截器响应拦截器 3. 改进建议4. 总结 console.log(Intercepted Response:, JSON.stringify(response));{"data": {"code": 0,"msg": "成功","data": {"id":…

论文阅读:LDA-AQU:Adaptive Query-guided Upsampling via Local Deformable Attention

论文地址&#xff1a;arxiv 摘要 提出了一种上采样的模块&#xff0c;有着较好的效果。 正文 常见的上采样方法有最近邻插值和双线性插值&#xff0c;通过手动的范式从邻近点聚合特征。之后又提出了可学习的上采样方法&#xff0c;比如反卷积&#xff0c;像素洗牌等。但是这…

如何优化爬虫效率?

以下是一些优化爬虫效率和避免被网站封锁的技巧&#xff1a; 优化爬虫效率 使用并发技术&#xff1a; 多线程&#xff1a;适用于I/O密集型任务&#xff0c;如网络请求&#xff0c;通过Java的Thread或ExecutorService实现并发请求&#xff0c;提高数据抓取速度。多进程&#x…

Git 常用命令指南

Git 常用命令指南 基础命令 git init # 初始化Git仓库 git clone <url> # 克隆远程仓库 git status # 查看仓库状态 git add <file> # 添加文件到暂存区 git add . # 添加所有修改到暂存区 git commit …

Docker Compose etcd 服务

目录 /usr/etcd vim docker-compose.yml version: 3.7services:etcd:image: quay.io/coreos/etcd:v3.5.7container_name: etcdenvironment:- ETCD_DATA_DIR/etcd-data- ETCD_LISTEN_PEER_URLShttp://0.0.0.0:2380- ETCD_LISTEN_CLIENT_URLShttp://0.0.0.0:2379- ETCD_ADVERTI…

一个很实用的语音处理工具ClearerVoice-Studio

阿里巴巴刚刚开源了一个很实用的语音处理工具&#xff1a;ClearerVoice-Studio&#xff0c;它可以语音增强、语音分离和音视频说话人提取&#xff0c;可以用来处理会议录音、电话录音等等 功能&#xff1a; 1、语音降噪&#xff0c;把嘈杂的语音转成高质量、清晰的音频信号 2、…

多模态人工智能在零售业的未来:通过GPT-4 Vision和MongoDB实现智能产品发现

多模态人工智能在零售业的未来&#xff1a;通过GPT-4 Vision和MongoDB实现智能产品发现 引言 想象一下&#xff0c;顾客在购物时只需上传一张他们所期望的服装或产品的照片&#xff0c;几分钟内便能收到来自他们最喜欢的商店的个性化推荐。这就是多模态人工智能在零售领域所带…

Openstack持久存储-Swift,Cinder,Manila三者之间的区别

总结不易&#xff0c;给个三连吧&#xff01;&#xff01;&#xff01; 补充&#xff1a; 文件共享存储服务Manila 在OpenStack生态系统中&#xff0c;Cinder和Manila分别提供了两种不同类型的存储服务&#xff0c;类似于传统的SAN&#xff08;存储区域网络&#xff09;和NAS&…