带你用Python制作超级经典的2048游戏

warning: 这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。



import sys
import pygame
import random
 
# 定义颜色变量
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
DARK_GREY = (100, 100, 100)
LIGHT_GREY = (230, 230, 230)
YELLOW = (255, 255, 0)
 
# 初始化pygame
pygame.init()
 
# 设置窗口大小
size = (400, 400)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("2048 Game")
 
# 定义方向常量
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
 
# 定义格子类
class Grid(object):
    def __init__(self, x, y, width, height, num=0):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.num = num
 
    def draw(self):
        # 绘制格子边框
        pygame.draw.rect(screen, LIGHT_GREY, (self.x, self.y, self.width, self.height))
        pygame.draw.rect(screen, DARK_GREY, (self.x + 4, self.y + 4, self.width - 8, self.height - 8))
 
        # 如果有数字,则显示
        if self.num > 0:
            font = pygame.font.SysFont("Arial", 20)
            text = font.render(str(self.num), True, BLACK)
            textRect = text.get_rect()
            textRect.center = ((self.x + self.width / 2), (self.y + self.height / 2))
            screen.blit(text, textRect)
 
    def get_position(self, x, y):
        return (self.x + 4 <= x <= self.x + self.width - 4 and self.y + 4 <= y <= self.y + self.height - 4)
 
# 初始化格子数组
grids = [
    [Grid(i * 100, j * 100, 100, 100) for i in range(4)]
    for j in range(4)
]
 
# 随机添加2或4
def add_random_number():
    if random.random() > 0.5:
        num = 2
    else:
        num = 4
 
    empty_cells = []
    for i in range(4):
        for j in range(4):
            if grids[i][j].num == 0:
                empty_cells.append((i, j))
 
    if len(empty_cells) > 0:
        i, j = empty_cells[random.randint(0, len(empty_cells) - 1)]
        grids[i][j].num = num
 
# 添加数字
add_random_number()
add_random_number()
 
# 移动处理
def move(direction):
    if direction == UP:
        for j in range(4):
            is_changed = False
            temp = [grid for grid in grids if grid.num != 0]
            temp.sort(key=lambda grid: grid.y)
 
            for i in range(len(temp) - 1):
                if temp[i].num == 0:
                    temp.pop(i)
                elif temp[i].num == temp[i + 1].num:
                    temp[i].num *= 2
                    temp[i + 1].num = 0
                    is_changed = True
 
            for i in range(len(temp)):
                gri
最后修改于:2024年08月16日 10:26

评论已关闭

推荐阅读

DDPG 模型解析,附Pytorch完整代码
2024年11月24日
DQN 模型解析,附Pytorch完整代码
2024年11月24日
AIGC实战——Transformer模型
2024年12月01日
Socket TCP 和 UDP 编程基础(Python)
2024年11月30日
python , tcp , udp
如何使用 ChatGPT 进行学术润色?你需要这些指令
2024年12月01日
AI
最新 Python 调用 OpenAi 详细教程实现问答、图像合成、图像理解、语音合成、语音识别(详细教程)
2024年11月24日
ChatGPT 和 DALL·E 2 配合生成故事绘本
2024年12月01日
omegaconf,一个超强的 Python 库!
2024年11月24日
【视觉AIGC识别】误差特征、人脸伪造检测、其他类型假图检测
2024年12月01日
[超级详细]如何在深度学习训练模型过程中使用 GPU 加速
2024年11月29日
Python 物理引擎pymunk最完整教程
2024年11月27日
MediaPipe 人体姿态与手指关键点检测教程
2024年11月27日
深入了解 Taipy:Python 打造 Web 应用的全面教程
2024年11月26日
基于Transformer的时间序列预测模型
2024年11月25日
Python在金融大数据分析中的AI应用(股价分析、量化交易)实战
2024年11月25日
AIGC Gradio系列学习教程之Components
2024年12月01日
Python3 `asyncio` — 异步 I/O,事件循环和并发工具
2024年11月30日
llama-factory SFT系列教程:大模型在自定义数据集 LoRA 训练与部署
2024年12月01日
Python 多线程和多进程用法
2024年11月24日
Python socket详解,全网最全教程
2024年11月27日