Created
August 25, 2019 10:49
-
-
Save VanDavv/6116d67543a617b64707d88dd6234033 to your computer and use it in GitHub Desktop.
Micro:bit catch or loose game
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Where is the blocks