采用GPT生成的Python 的 2048 游戏

ops/2025/1/15 17:35:13/

采用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/ops/150348.html

相关文章

C++ 鼠标轨迹算法 - 防止游戏检测

一.简介 鼠标轨迹算法是一种模拟人类鼠标操作的程序&#xff0c;它能够模拟出自然而真实的鼠标移动路径。 鼠标轨迹算法的底层实现采用C/C语言&#xff0c;原因在于C/C提供了高性能的执行能力和直接访问操作系统底层资源的能力。 鼠标轨迹算法具有以下优势&#xff1a; 模拟…

Android string.xml中特殊字符转义

项目中要在string.xml 中显示特殊符号 空格&#xff1a; &#xff08;普通的英文半角空格但不换行&#xff09; 窄空格&#xff1a;  &#xff08;中文全角空格 &#xff08;一个中文宽度&#xff09;&#xff09; &#xff08;半个中文宽度&#xff0c;但两个空格比一个中文…

Mac 启动docke报错 com.docker.vmnetd【解决方案】

今天不知道 docker抽了啥疯&#xff0c;突然提示更新&#xff0c;更新完就报错 而且还无限的提示&#xff0c;下载最新的版本&#xff0c;更新还是不行--- 于是google查了一下&#xff0c;噢噢噢噢&#xff0c;果然有问题 issiue如下 Malware detection prevents Docker De…

linux 文件权限设置详解

在 Linux 中&#xff0c;文件和目录的权限控制非常重要。权限控制决定了用户对文件的操作能力&#xff0c;主要包括对文件的读取、写入和执行权限。Linux 使用 rwx 方式来表示权限&#xff0c;r 代表读取 (Read)&#xff0c;w 代表写入 (Write)&#xff0c;x 代表执行 (Execute…

计算机网络 | 什么是公网、私网、NAT?

关注&#xff1a;CodingTechWork 引言 计算机网络是现代信息社会的基石&#xff0c;而网络通信的顺畅性和安全性依赖于有效的IP地址管理和网络转换机制。在网络中&#xff0c;IP地址起到了标识设备和进行数据传输的核心作用。本文将详细讨论公网IP、私网IP以及NAT转换等网络技…

HTML拖拽功能(纯html5+JS实现)

1、HTML拖拽--单元行拖动 <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>Document</title><…

《自动驾驶与机器人中的SLAM技术》ch2:基础数学知识

目录 2.1 几何学 向量的内积和外积 旋转矩阵 旋转向量 四元数 李群和李代数 SO(3)上的 BCH 线性近似式 2.2 运动学 李群视角下的运动学 SO(3) t 上的运动学 线速度和加速度 扰动模型和雅可比矩阵 典型算例&#xff1a;对向量进行旋转 典型算例&#xff1a;旋转的复合 2.3 …

Web前端------HTML块级和行内标签之行内标签

一.行内标签介绍 行内标签----span 作用&#xff1a; 1.作为文本字体的容器&#xff0c;用来结合CSS修饰文本样式 2.根据行内标签的特性&#xff08;不换行/部分块级样式不生效eg&#xff1a;宽高等等&#xff09;&#xff0c; 做微小布局 二.代码展示 <!DOCTYPE html>…