這一篇是抄襲自這裡,英文好的可自行看一下原理網站上說明很詳細,這裡一樣主張先做再討論原理。
https://www.raspberrypi.org/learning/sense-hat-marble-maze/worksheet/
開啟文字編輯器輸入以下程式碼。
#-*-coding:cp950-*-
#這一行是讓 Python 能用中文註解
from sense_hat import SenseHat # 載入SenseHat模組
from time import sleep
sense = SenseHat() # 顯示器 = SenseHat
sense.clear() # 清除顯示器
r = (255,0,0) # b= 不亮
g = (0,255,0) # g= 綠色
b = (0,0,0) # r= 紅色
w = (255,255,255) # w= 白色
x = 1 # x 預設 =1
y = 1 # y 預設 =1
maze = [ # 迷宮圖案
[r,r,r,r,r,r,r,r],
[r,b,b,b,b,b,b,r],
[r,r,r,b,r,r,r,r],
[r,b,r,b,b,b,b,r],
[r,b,b,b,b,r,b,r],
[r,b,r,r,r,r,b,r],
[r,b,b,r,g,b,b,r],
[r,r,r,r,r,r,r,r]
]
def move_marble(pitch,roll,x,y): #確認傾斜方向
new_x = x
new_y = y
if 1 < pitch < 179 and x != 0:
new_x -= 1
elif 359 > pitch > 181 and x != 7 :
new_x += 1
if 1 < roll < 179 and y != 7:
new_y += 1
elif 359 > roll > 181 and y != 0 :
new_y -= 1
x,y = check_wall(x,y,new_x,new_y)
return x,y
def check_wall(x,y,new_x,new_y):
#偵側牆面
if maze[new_y][new_x] != r:
return new_x, new_y
elif maze[new_y][x] != r:
return x, new_y
elif maze[y][new_x] != r:
return new_x, y
return x,y
game_over = False
#
def check_win(x,y):
# 確認是否過關
global game_over
if maze[y][x] == g: #如果 x,y 重疊綠色
game_over = True
sense.show_message('You Win') #顯示字串 You Win
while not game_over:
#沒有過關
pitch = sense.get_orientation()['pitch']
roll = sense.get_orientation()['roll']
x,y = move_marble(pitch,roll,x,y)
check_win(x,y)
maze[y][x] = w
sense.set_pixels(sum(maze,[]))
sleep(0.05)
maze[y][x] = b
完成後存成 maez.py,開啟WinSCP填入登入資訊。
.
登入後將 maze.py 拖曳進 sense_hat 資料夾。
登入SSH切換到 sense_hat目錄,執行 python maze.py。
就可開始玩電子迷宮了。
.
參考資料 :
https://www.raspberrypi.org/learning/sense-hat-marble-maze/worksheet/
https://www.raspberrypi.org/learning/sense-hat-data-logger/