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)
這是代碼,如果是整列從左到右或者從上到下進行點亮就沒問題,如果是用這個代碼進行單個循環點亮時就會有別的列一起點亮,是為什么呢 |