Skip to content

Instantly share code, notes, and snippets.

@VanDavv
Created Aug 25, 2019
Embed
What would you like to do?
Micro:bit catch or loose game
from microbit import display, Image, button_a, button_b, pin0, running_time
import random
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
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!')
break
if pin0.is_touched():
display.clear()
break
@hahsbu4udhdbb

This comment has been minimized.

Copy link

@hahsbu4udhdbb hahsbu4udhdbb commented Nov 20, 2020

Where is the blocks

@VanDavv

This comment has been minimized.

Copy link
Owner Author

@VanDavv VanDavv commented Nov 20, 2020

@hahsbu4udhdbb could you be more specific?

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