from machine import Pin
from neopixel import NeoPixel
import random
from button import Button

# 初始化LED矩阵
NUM_LEDS = 16               # 4x4矩阵共有16个LED
LINES = 4
LED_PIN = 2                 # 使用GPIO2作为数据引脚
leds = NeoPixel(Pin(LED_PIN), NUM_LEDS)

# 2028游戏的初始状态
game_grid = [0] * NUM_LEDS

score = 0 # 得分


# 颜色映射
color_map = {
    0: (0, 0, 0),           # 黑色表示0
    2: (255, 0, 0),         # 红色
    4: (0, 255, 0),         # 绿色
    8: (0, 0, 255),         # 蓝色
    16:(255,255,0),         # 黄色
    32:(139,0,255),         # 紫色
    # 可以继续添加更多的颜色映射
}

# 按键设置
button_pins = [19, 16, 17, 18]          # 四个按键分别连接到GPIO19, GPIO16, GPIO17, GPIO18


#按键回调函数,处理按键逻辑
def button_click_cb(pin):
    #print("button clicked {}".format(pin))
    if pin==19:                 #up
        print("up")
        move_up()
    if pin==16:                 #down
        print("down")
        pass
    if pin==17:                 #left
        print("left")
        pass
    if pin==18:                 #right
        print("right")
        pass

    # add_new_number()
    display_grid()

#注册按键
button = Button(
    pin=button_pins,
    click_cb=button_click_cb,
    timeout=3000,
    behavior=Button.BEHAVIOR_HOLD
)




def move_up():
    global score

    merged = False

    for y in range(LINES):
        for x in range(LINES):
            for x1 in range(1, LINES):
                if game_grid[x1*LINES+y] > 0:
                    if game_grid[x*LINES+y] <= 0:
                        game_grid[x*LINES+y] = game_grid[x1*LINES+y]
                        game_grid[x1*LINES+y] = 0

                        x -= 1
                        merged = True
                    elif game_grid[x*LINES+y] == game_grid[x1*LINES+y]:
                        game_grid[x*LINES+y] *= 2
                        game_grid[x1*LINES+y] = 0
                        score += game_grid[x*LINES+y]
                        print(f'update score: {score}')

                        merged = True

                    break

    if merged:
        add_new_number()




# 显示游戏网格
def display_grid():
    for i, value in enumerate(game_grid):
        leds[i] = color_map.get(value, (0, 0, 0))
    leds.write()

# 随机生成新数字
def add_new_number():
    empty_cells = [i for i, value in enumerate(game_grid) if value == 0]
    if empty_cells:
        game_grid[random.choice(empty_cells)] = 2


# 游戏初始化
def init_game():
    global game_grid
    game_grid = [0] * NUM_LEDS
    add_new_number()
    add_new_number()

# 主函数
def main():
    init_game()
    display_grid()

# 运行主函数
main()