標(biāo)題: esp32和8×8點(diǎn)陣寫貪吃蛇會有別的列一起點(diǎn)亮 [打印本頁]

作者: yuki·kiko    時(shí)間: 2024-9-4 16:07
標(biāo)題: esp32和8×8點(diǎn)陣寫貪吃蛇會有別的列一起點(diǎn)亮
import machine
import time
import random
import _thread  # MicroPython 線程庫

# 定義點(diǎn)陣的行和列引腳
rows = [machine.Pin(i, machine.Pin.OUT) for i in [32, 33, 25, 26, 27, 14, 12, 13]]
cols = [machine.Pin(i, machine.Pin.OUT) for i in [19, 18, 5, 17, 16, 4, 2, 15]]

snake_body = []  # 初始化蛇身體
direction = ()  # 蛇的方向
food = ()  # 食物的位置
direction_lock = _thread.allocate_lock()

def create_food():
    """生成不與蛇重合的食物位置"""
    global food
    while True:
        # 隨機(jī)生成食物的位置
        food = (random.randint(0, 7), random.randint(0, 7))
        if food not in snake_body:
            break  # 找到不重合的位置,退出循環(huán)

def init_snake():
    """初始化蛇的位置和方向"""
    global snake_body, direction
    snake_body = [(3, 3), (3, 2), (3, 1)]  # 初始化蛇身體
    direction = (0, 1)  # 初始化食物方向
    create_food()  # 初始化食物

def set_pixel(x, y, state):
    """設(shè)置點(diǎn)陣某個(gè)像素的狀態(tài)"""
    rows[x].value(not state)
    cols[y].value(state)

def clear_display():
    print("clear")
    for i in range(8):
        for j in range(8):
            set_pixel(i, j, 0)

def draw_snake():
    """繪制蛇和食物"""
    for segment in snake_body:
        print(f"{segment}")
        set_pixel(segment[0], segment[1], 1)
   
def draw_food():
    """繪制蛇和食物"""
    set_pixel(1, 1, 1)
    print(f"{food}")



def change_direction(new_direction):
    global direction
    opposite_direction = (-direction[0], -direction[1])
    if new_direction != opposite_direction:
        with direction_lock:
            direction = new_direction

def snake_move():
    """移動蛇的位置"""
    global snake_body, food
    # 計(jì)算新位置
    new_head = (snake_body[0][0] + direction[0], snake_body[0][1] + direction[1])

    # 使用取模運(yùn)算使蛇在碰到墻壁時(shí)從另一側(cè)出現(xiàn)
    new_head = (new_head[0] % 8, new_head[1] % 8)

    if new_head in snake_body:
        return False  # 撞到自己,游戲結(jié)束

    snake_body.insert(0, new_head)  # 更新蛇頭位置

    # 吃到食物
    if new_head == food:
        create_food()
    else:
        snake_body.pop()  # 如果沒有吃到食物,尾巴移動
    return True





if __name__ == "__main__":
    init_snake()
#     _thread.start_new_thread(key_scan, ()) # 創(chuàng)建線程
    while True:
        if not snake_move():
            break  # 游戲結(jié)束
        clear_display()
        draw_snake()
        draw_food()
        time.sleep_ms(500)


這是代碼,如果是整列從左到右或者從上到下進(jìn)行點(diǎn)亮就沒問題,如果是用這個(gè)代碼進(jìn)行單個(gè)循環(huán)點(diǎn)亮?xí)r就會有別的列一起點(diǎn)亮,是為什么呢
作者: yuki·kiko    時(shí)間: 2024-9-4 16:09
就像這樣

IMG_20240904_160838.jpg (330.98 KB, 下載次數(shù): 5)

IMG_20240904_160838.jpg

IMG_20240904_160847.jpg (325.44 KB, 下載次數(shù): 2)

IMG_20240904_160847.jpg

作者: GlenXu    時(shí)間: 2024-9-6 12:02
顯示或循環(huán)處理速度過快,加點(diǎn)延時(shí)




歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1