Arrows - Code
From RoboWiki
Return back to project page: Arrows - Unax Murua, Eric Ayestaran, Leire Sáez de Cortázar
Python code for the Arrows project:
from hub import light_matrix
import random
import time
import force_sensor, motor
def main():
actions = {
"arrow_up": [
[0, 0, 1, 0, 0],
[0, 1, 1, 1, 0],
[1, 0, 1, 0, 1],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
],
"arrow_down": [
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[1, 0, 1, 0, 1],
[0, 1, 1, 1, 0],
[0, 0, 1, 0, 0],
],
"arrow_left": [
[0, 0, 1, 0, 0],
[0, 1, 0, 0, 0],
[1, 1, 1, 1, 1],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
],
"arrow_right": [
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 0],
[1, 1, 1, 1, 1],
[0, 0, 0, 1, 0],
[0, 0, 1, 0, 0],
],
"touch_button": [
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0],
],
}
action_ranges = {
"arrow_left": ([-20, 20], [-100, -60]),
"arrow_right": ([-20, 20], [70, 140]),
"arrow_up": ([70, 140], [-20, 20]),
"arrow_down": ([-110, -60], [-20, 20]),
}
def display_action(matrix):
light_matrix.clear()
for y, row in enumerate(matrix):
for x, value in enumerate(row):
light_matrix.set_pixel(x, y, 100 * value)
def detect_action(action_name, remaining_t):
ranges = action_ranges.get(action_name)
if ranges is None:# Force sensor
filtered_ranges = [value for value in action_ranges.values()]
starting_time = time.ticks_ms()
while time.ticks_ms() - starting_time < remaining_t:
#Erroneous movement
position = (motor.absolute_position(1), motor.absolute_position(5))
for filtered_range in filtered_ranges:
fx_range, fy_range = filtered_range
if fx_range[0] <= position[0] <= fx_range[1] and fy_range[0] <= position[1] <= fy_range[1]:
print("Erroneous movement")
return False
#Correct action
if force_sensor.force(2) > 0:
print("Acción detectada")
return True
time.sleep(0.1)
else:# Actions
x_range, y_range = ranges
filtered_ranges = [value for value in action_ranges.values() if value != ranges]
starting_time = time.ticks_ms()
while time.ticks_ms() - starting_time < remaining_t:
position = (motor.absolute_position(1), motor.absolute_position(5))
#Erroneous movement
for filtered_range in filtered_ranges:
fx_range, fy_range = filtered_range
if fx_range[0] <= position[0] <= fx_range[1] and fy_range[0] <= position[1] <= fy_range[1]:
print("Erroneous movement")
return False# End the game
#Erroneous force sensor
if force_sensor.force(2) > 0:
print("Erroneous force sensor")
return False
#Correct action
if x_range[0] <= position[0] <= x_range[1] and y_range[0] <= position[1] <= y_range[1]:
print("Action detected")
return True
time.sleep(0.1)
return False
remaining_time = 5000
keep_on = True
score = 0
while remaining_time > 0:
action_name = random.choice(list(actions.keys()))
display_action(actions[action_name])
keep_on = detect_action(action_name, remaining_time)
if not keep_on:
break
remaining_time *= 0.95
light_matrix.clear()
score += 1
time.sleep(1)
light_matrix.clear()
print("Game Over!")
print("Score: ", score)
light_matrix.write("Score: " + str(score))
main()