Skip to content

Instantly share code, notes, and snippets.

@VanDavv
Created August 25, 2019 10:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VanDavv/e4f93a64f052b12c70f378933fd42c06 to your computer and use it in GitHub Desktop.
Save VanDavv/e4f93a64f052b12c70f378933fd42c06 to your computer and use it in GitHub Desktop.
Micro:bit catch or loose game with counter
import random
import radio
from microbit import display, Image, button_a, button_b, pin0, running_time
class Utils:
@staticmethod
def deepcopy(arr):
return [row[:] for row in arr]
@staticmethod
def build_img(arr):
result = ""
for subarr in arr:
for item in subarr:
result += str(item)
result += ":"
return Image(result)
class Player:
x = 2
y = 4
health = 9
last_changed = running_time()
def allowed_to_move(self):
return running_time() - self.last_changed > 200
def act(self, frame: Image):
if self.allowed_to_move():
if button_a.is_pressed():
self.x = max(self.x - 1, 0)
self.last_changed = running_time()
elif button_b.is_pressed():
self.x = min(self.x + 1, 4)
self.last_changed = running_time()
frame.set_pixel(self.x, self.y, self.health)
return frame
class Enemies:
max_enemies_count = 2
enemies_positions = []
last_changed = running_time()
def allowed_to_move(self):
return running_time() - self.last_changed > 1000
def act(self, frame, on_hit):
if self.allowed_to_move():
for position in self.enemies_positions:
position[1] += 1
if position[1] == 4:
on_hit(position)
self.enemies_positions = list(filter(lambda position: position[1] < 4, self.enemies_positions))
if len(self.enemies_positions) < self.max_enemies_count:
self.enemies_positions.append([random.randint(0, 4), 0])
self.last_changed = running_time()
for position in self.enemies_positions:
frame.set_pixel(position[0], position[1], 5)
return frame
empty_frame = [
[0] * 5,
[0] * 5,
[0] * 5,
[0] * 5,
[0] * 5,
]
player = Player()
enemies = Enemies()
def on_hit(posiiton):
if player.x != posiiton[0]:
player.health -= 1
else:
radio.send('scored')
radio.on()
while True:
new_frame = Utils.build_img(empty_frame)
new_frame = player.act(new_frame)
new_frame = enemies.act(new_frame, on_hit)
display.show(new_frame)
if player.health < 1:
display.clear()
display.scroll('GAME OVER!')
radio.send('lost')
break
if radio.receive() == 'won':
display.clear()
display.scroll('You won!')
break
if pin0.is_touched():
display.clear()
break
radio.off()
import radio
from microbit import display, pin0, Image
radio.on()
score = 0
while True:
incoming = radio.receive()
if incoming == 'scored':
score += 1
elif incoming == 'lost':
display.show(Image.SAD)
break
if score > 9:
radio.send('won')
display.show(Image.HAPPY)
break
if pin0.is_touched():
display.clear()
break
# display.show(images[score])
display.show(str(score))
radio.off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment