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
评论已关闭