Advent of code

 10 décembre 2022 

  Cathode-Ray Tube : Sprite et cycles pour dessiner un écran
addx 1
   
addx 5
   
noop
   
addx -1
   
noop
   
   
  1. code.py
  2. codeBuffer.py
NB_CYCLES = {'noop':1, 'addx':2}
INTERESTING_CYCLES = list(range(20, 221, 40))

# Partie 1
def interestingSignalStrength(cycle, X):
    if cycle in INTERESTING_CYCLES:
        return cycle * X
    else:
        return 0

# Partie 2
def pixel(cycle, xBuffer):
    col = (cycle - 1) % 40    # de 0 à 39
    return (col == 0 and "\n" or "")  +  2 * xBuffer[col]


f = open("input.txt", 'r')
lines = [line[:-1] for line in f.readlines()]

X = 1
SPRITEBUFFER = 40*" " + "###" + 40*" "    #   … ...........###........... …
xBuffer = SPRITEBUFFER[40:80]             #   ###........... …
cycle = 0
sommeSignaux = 0  # Partie 1
output = ""       # Partie 2

for line in lines:
    tokens = line.split()
    cmd = tokens[0]

    for _ in range(NB_CYCLES[cmd]):
        cycle += 1
        sommeSignaux += interestingSignalStrength(cycle, X)
        output += pixel(cycle, xBuffer)

    if cmd == 'addx':
        X += int(tokens[1])
        xBuffer = SPRITEBUFFER[41-X:81-X]

print("Réponse partie 1:", sommeSignaux)
print("Réponse partie 2:" + output)