で、またゲームを作ったので投稿します。楽しくなってきた。
最近流行りの、子供向けプログラミング教育用ゲームを作ってみました。
指定された場所へ移動するための経路を指示(プログラミング)するというあれです。
橙から青へ移動します。が、動かすだけだと縦横一直線になるので、障害物(緑)もつけてみた。
こっちは完全に逐次処理なので、イベントハンドラは使っていません。
ただ、慣性で動かす、というのはアリかも。
一応、小学生の娘は気に入ってくれた。ヨカッタ。
これでプログラミング学習ができるかは未検証。。
from sense_hat import SenseHat
from time import sleep
from random import randint
sense = SenseHat()
sense.clear()
red = (255, 0, 0)
blue = (0, 0, 255)
yellow=(255,255,0)
purple=(128,0,128)
green=(0,255,0)
indigg=(75,0,130)
orange=(255,128,0)
black=(0,0,0)
sense.set_rotation(0)
num_disturbs = 20
# スタートブロック(橙)をランダム設定
row_init=randint(0, 7)
col_init=randint(0, 7)
color_init=orange
sense.set_pixel(col_init, row_init, color_init)
# ゴールブロック(青)をランダム設定
row_target = randint(0, 7)
col_target = randint(0, 7)
# ゴールがスタート位置と同じにならないようにする
while row_target == row_init and col_target == col_init:
row_target = randint(0, 7)
col_target = randint(0, 7)
color_target = blue
sense.set_pixel(col_target, row_target, color_target)
# 妨害ブロックをランダム設定
disturbs = list()
for i in range(0,num_disturbs):
while True:
row = randint(0, 7)
col = randint(0, 7)
if row == row_init and col == col_init:
continue
if row == row_target and col == col_target:
continue
duplicated = False
for j in disturbs:
if col == j[0] and row == j[1]:
duplicated = True
break
if duplicated:
continue
disturbs.append((col, row))
break
color_disturb = green
for i in disturbs:
sense.set_pixel(i[0], i[1], color_disturb)
# 移動方向をプログラミング
# 中ボタンで完了
commands = list()
set_com=True
while set_com:
for event in sense.stick.get_events():
if event.action == "pressed":
if event.direction == "middle":
set_com = False
else:
commands.append(str(event.direction))
row=row_init
col=col_init
color=red
# プログラミングした通りに、スタートブロックから動かす(赤)
for com in commands:
sense.set_pixel(col, row, black)
sense.set_pixel(col_init, row_init, color_init)
if com == "up":
row = row - 1
elif com == "down":
row = row + 1
elif com == "left":
col = col - 1
elif com == "right":
col = col + 1
elif com == "middle":
row = row_init
col = col_init
if row > 7: row = 7
if row < 0: row = 0
if col > 7: col = 7
if col < 0: col = 0
sense.set_pixel(col, row, color)
sleep(0.5)
disturbed = False
for i in disturbs:
if col == i[0] and row == i[1]:
disturbed = True
break
if disturbed:
break
# 成否を判定
if row == row_target and col == col_target:
sense.show_letter("O")
else:
sense.show_letter("X")
sleep(3)
sense.clear()