Skip to content

Instantly share code, notes, and snippets.

@mavhc
Created February 18, 2016 14:32
Show Gist options
  • Save mavhc/e7fde9bf1ae6a317c331 to your computer and use it in GitHub Desktop.
Save mavhc/e7fde9bf1ae6a317c331 to your computer and use it in GitHub Desktop.
import microbit, random
# blank grid to start
gridImg = microbit.Image("00000\n"
"00000\n"
"00000\n"
"00000\n"
"00000\n")
def get_grid():
return [[microbit.display.get_pixel(x,y) for y in range(5)] for x in range(5)]
def set_grid(grid):
for y in range(5):
for x in range(5):
microbit.display.set_pixel(x,y,grid[y][x])
def drawgrid():
microbit.display.show(gridImg)
# returns 0 to 4 from -1024 to +1024, empirically calculated
def tilt_scale(a):
a = a + 1024 # range 0 to 2048
a = min(a, 2048)
a = max(a, 0)
# < 512 = 0, 512-853(512+341) = 1, 853-1194 = 2, 1194-1536 = 3, 1536-2048 = 4
if a<512: return 0
if a<853: return 1
if a<1194: return 2
if a<1536: return 3
return 4
def get_tilt():
x,y,z = microbit.accelerometer.get_values()
#print(x+1024,y+1024,z+1024)
x = tilt_scale(x)
y = tilt_scale(y)
z = tilt_scale(z)
#print(x,y,z)
return x,y,z
def pick_speed(speed):
while not microbit.button_b.is_pressed():
microbit.display.show(str(speed))
if microbit.button_a.is_pressed():
speed -= 1
if speed < 1: speed = 9
microbit.sleep(200)
return speed
wallBrightness = 5
speed = 9 # set default speed
# play game forever
while True:
# blank screen
drawgrid()
grid = get_grid()
end = False
won = False
score = 0
xpos = 2 # start in centre
ypos = 4 # start at bottom
# pick a speed, A reduces speed, B sets speed
speed = pick_speed(speed)
gameSpeed = 100 * speed
while not end: # run until the game is over
set_grid(grid) # print current screen
xpos,ypos,zpos = get_tilt()
microbit.display.set_pixel(xpos,4,9) # draw player
if grid[4][xpos] == wallBrightness: # did player hit a wall?
end = True
xgap = random.randint(0,4) # pick a random hole in the wall
# only draw a wall every 4 lines
wall = 0
if score % 4 == 0:
wall = wallBrightness
score += 1
newline = [wall] * 5
newline[xgap] = 0
grid.insert(0,newline) # add new line at the top
grid.pop() # delete line from bottom
if gameSpeed > 10: gameSpeed -= 1 # game speeds up
microbit.sleep(gameSpeed)
microbit.display.scroll("Score: "+str(score))
@mavhc
Copy link
Author

mavhc commented Mar 7, 2016

This file is public domain

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment