◂ 9 décembre 2022 ▸
Rope Bridge : Corde qui bouge et tire la queue (snake)
L 2
D 2
L 2
R 2
L 1
⋮
- code.py
- snake.png
- snake.py
#############################################################
### Dessine dans le terminal la corde durant son parcours ###
#############################################################
NB_LIGNES_TERMINAL = 50
NB_COLONNES_TERMINAL = 200
DIRECTIONS = {'R':(1,0), 'L':(-1,0), 'U':(0,1), 'D':(0,-1)}
f = open("input.txt", 'r')
splittedLines = [line[:-1].split() for line in f.readlines()]
commands = list(map( lambda t:{'direction':DIRECTIONS[t[0]], 'nb':int(t[1])}, splittedLines))
def sign(x): # (ou utiliser numpy.sign)
return (x>0 and 1) or (x<0 and -1) or 0
def updatePosition(xHead, yHead, xTail, yTail):
diffX = xHead - xTail
diffY = yHead - yTail
return (xTail + diffX - sign(diffX)*(abs(diffX) >= abs(diffY)), yTail + diffY - sign(diffY)*(abs(diffY) >= abs(diffX)))
positions = 10 * [ (0,0) ]
visitedTout = { (0,0) }
visited9 = { (0,0) }
minX = maxX = minY = maxY = x = y = 0
for command in commands:
x += command['nb'] * command['direction'][0]
y += command['nb'] * command['direction'][1]
minX = min(minX, x)
maxX = max(maxX, x)
minY = min(minY, y)
maxY = max(maxY, y)
MARGEV = NB_LIGNES_TERMINAL // 2
MARGEH = NB_COLONNES_TERMINAL // 2
gauche = max(-MARGEH, minX)
droite = min(MARGEH, maxX)
bas = max(-MARGEV, minY)
haut = min(MARGEV, maxY)
for command in commands:
for _ in range(command['nb']):
positions[0] = ( positions[0][0] + command['direction'][0], positions[0][1] + command['direction'][1] )
visitedTout.add(positions[0])
for i in range(1, len(positions)):
positions[i] = updatePosition(*positions[i-1], *positions[i])
visitedTout.add(positions[i])
visited9.add(positions[-1])
if positions[0][0] < gauche:
gauche -= 1
droite -= 1
elif positions[0][0] > droite:
gauche += 1
droite += 1
elif positions[0][1] < bas:
bas -= 1
haut -= 1
elif positions[0][1] > haut:
bas += 1
haut += 1
output = (2*MARGEV + 20)*"\n"
for y in range(haut, bas - 1, -1):
for x in range(gauche, droite + 1):
if (x,y) == positions[0]:
c = '*'
elif (x,y) in positions:
c = '#'
elif (x,y) in visited9:
c = '+'
elif (x,y) in visitedTout:
c = '·'
else:
c = ' '
output += c
output += "\n"
print(output)