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, X):
    col = (cycle - 1) % 40 + 1    # de 1 à 40
    if col == 1:
        chars = "\n"
    else:
        chars = ""
    if col in list(range(X,X+3)):   # ou:  col >= X and col <= X+2
        chars += "##"    # doublé pour plus de lisibilité
    else:
        chars += "  "    # doublé
    return chars


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

X = 1
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, X)

    if cmd == 'addx':
        X += int(tokens[1])

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