标题: esp32和8×8点阵写贪吃蛇会有别的列一起点亮 [打印本页]

作者: yuki·kiko    时间: 2024-9-4 16:07
标题: esp32和8×8点阵写贪吃蛇会有别的列一起点亮
import machine
import time
import random
import _thread  # MicroPython 线程库

# 定义点阵的行和列引脚
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:
        # 随机生成食物的位置
        food = (random.randint(0, 7), random.randint(0, 7))
        if food not in snake_body:
            break  # 找到不重合的位置,退出循环

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):
    """设置点阵某个像素的状态"""
    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
    # 计算新位置
    new_head = (snake_body[0][0] + direction[0], snake_body[0][1] + direction[1])

    # 使用取模运算使蛇在碰到墙壁时从另一侧出现
    new_head = (new_head[0] % 8, new_head[1] % 8)

    if new_head in snake_body:
        return False  # 撞到自己,游戏结束

    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, ()) # 创建线程
    while True:
        if not snake_move():
            break  # 游戏结束
        clear_display()
        draw_snake()
        draw_food()
        time.sleep_ms(500)


这是代码,如果是整列从左到右或者从上到下进行点亮就没问题,如果是用这个代码进行单个循环点亮时就会有别的列一起点亮,是为什么呢
作者: yuki·kiko    时间: 2024-9-4 16:09
就像这样

IMG_20240904_160838.jpg (330.98 KB, 下载次数: 5)

IMG_20240904_160838.jpg

IMG_20240904_160847.jpg (325.44 KB, 下载次数: 2)

IMG_20240904_160847.jpg

作者: GlenXu    时间: 2024-9-6 12:02
显示或循环处理速度过快,加点延时




欢迎光临 (http://www.51hei.com/bbs/) Powered by Discuz! X3.1