Last active
October 8, 2022 05:05
-
-
Save jsbueno/d64b79441c91dccc42013f87c791d142 to your computer and use it in GitHub Desktop.
brainfuck
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sys import argv | |
from terminedia import getch | |
MEMSIZE = 8192 | |
def main(): | |
program = open(argv[1]).read() | |
memory = bytearray(MEMSIZE) | |
pointer = 0 | |
program_counter = 0 | |
while program_counter < len(program): | |
opcode = program[program_counter] | |
program_counter += 1 | |
if opcode in "\n \t\r": | |
continue | |
if opcode == ">": pointer += 1 | |
elif opcode == "<": pointer -= 1 | |
elif opcode == "+": memory[pointer] += 1 | |
elif opcode == "-": memory[pointer] -= 1 | |
elif opcode == ".": print(chr(memory[pointer]), end="", flush=True) | |
elif opcode == ",": memory[pointer] = ord(getch()) | |
elif opcode == "D": print([int(m) for m in memory[:pointer + 10]]) | |
elif opcode == "[" and memory[pointer] == 0: | |
open_brackets = 1 | |
future_pc = program_counter | |
while open_brackets: | |
if program[future_pc] == "[": open_brackets += 1 | |
elif program[future_pc] == "]": open_brackets -= 1 | |
future_pc += 1 | |
if future_pc >= len(program): raise RuntimeError() | |
program_counter = future_pc + 1 | |
elif opcode == "]" and memory[pointer] != 0: | |
open_brackets = 1 | |
future_pc = program_counter - 2 | |
while open_brackets: | |
opcode = program[future_pc] | |
if program[future_pc] == "]": open_brackets += 1 | |
elif program[future_pc] == "[": open_brackets -= 1 | |
future_pc -= 1 | |
if future_pc < 0: raise RuntimeError() | |
program_counter = future_pc + 1 | |
main() | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+>+ # mark start of string | |
[<-> # decrease 1 on previous so mark is 0 | |
,+ # input and inc to compensate for mark strategy | |
[>+>+<<-]>>[<<+>>-] # dup | |
++++++++++++++[<->-]<]+ # repeat while != 14 (cr plus 1) | |
[<]> # rewind up to last 0 | |
[.>] # printstr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment