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 change_direction(new_direction):
global direction
opposite_direction = (-direction[0], -direction[1])
if new_direction != opposite_direction:
with direction_lock:
direction = new_direction