# -*- coding: utf-8 -*- """ Created on Fri Nov 27 10:34:13 2020 @author: Studente Write a function that takes as an input an image with black background and several segmented lines together with a point of the image and returns the number of turns made by the segmented line the point belongs to """ black = (0,0,0) white = (255,255,255) class Position: def __init__(self,row,pix): self.row = row self.pix = pix def __add__(self, p): return Position(self.row+p.row, self.pix+p.pix) def __repr__(self): return f'({self.row},{self.pix})' def __eq__(self, p): return p.row==self.row and p.pix==self.pix di = {'d':Position(1,0), 'u':Position(-1,0), 'r':Position(0,1), 'l':Position(0,-1) } class Turtle: def __init__(self, initial_point, image): self.pos = initial_point self.imm = image def check_pos(self, p): return 0 <= p.row < len(self.imm) and 0 <= p.pix < len(self.imm[0]) def color(self, p=None): ''' if p is None we return the color of the pixel where we are ''' if not p: return self.imm[self.pos.row][self.pos.pix] if self.check_pos(p): return self.imm[p.row][p.pix] return None def directions(self, p=None): if not p: p=self.pos ret = [] if self.color() == black: return [] elif self.color() == white: for direction in di.values(): if self.color(p+direction) == white: ret.append(direction) return ret def move(self, direction): self.pos+=direction def go_to(self, p): self.pos = p def check_corner(self, p=None): if not p: p=self.pos movements = self.directions(p) if len(movements) == 2: pos = movements[0]+movements[1] return pos.row + pos.pix return False def explore(self, pos, direction): self.pos = pos corners = 0 while self.color() != black: self.move(direction) if self.check_corner(): corners+=1 ## CHANGE DIRECTION movements = self.directions() if movements[0] == Position(-direction.row, -direction.pix): direction = movements[1] else: direction = movements[0] # if len(self.directions()) == 1: # return corners return corners def count_corners(self): movements = self.directions() corners = 0 if not movements: return 0 initial_pos = self.pos if len(movements) == 2: if self.check_corner(): corners+=1 corners += self.explore(initial_pos, movements[0]) + self.explore(initial_pos, movements[1]) return corners # # first_direction = # second_direction = # #def count_turns(imm, row, pixel): # ''' returns the number of turns made by the line the point imm[row][pixel] belongs to (if any) ''' # #