Created
December 30, 2023 22:29
-
-
Save Chubek/2ae83d6f65c091b711fc16837b3c0574 to your computer and use it in GitHub Desktop.
Brainfuck in Python generated by ChatGPT
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
class BrainfuckInterpreter: | |
def __init__(self): | |
self.memory = [0] * 30000 | |
self.pointer = 0 | |
self.instruction_pointer = 0 | |
self.input_buffer = "" | |
self.output_buffer = "" | |
def execute(self, code): | |
while self.instruction_pointer < len(code): | |
instruction = code[self.instruction_pointer] | |
if instruction == '>': | |
self.pointer += 1 | |
elif instruction == '<': | |
self.pointer -= 1 | |
elif instruction == '+': | |
self.memory[self.pointer] = (self.memory[self.pointer] + 1) % 256 | |
elif instruction == '-': | |
self.memory[self.pointer] = (self.memory[self.pointer] - 1) % 256 | |
elif instruction == '.': | |
self.output_buffer += chr(self.memory[self.pointer]) | |
elif instruction == ',': | |
if not self.input_buffer: | |
# If input buffer is empty, read a character from standard input | |
self.input_buffer = input("Enter a character: ") + '\n' | |
self.memory[self.pointer] = ord(self.input_buffer[0]) | |
self.input_buffer = self.input_buffer[1:] | |
elif instruction == '[': | |
if self.memory[self.pointer] == 0: | |
# Skip to the matching ']' | |
depth = 1 | |
while depth > 0: | |
self.instruction_pointer += 1 | |
if code[self.instruction_pointer] == '[': | |
depth += 1 | |
elif code[self.instruction_pointer] == ']': | |
depth -= 1 | |
elif instruction == ']': | |
if self.memory[self.pointer] != 0: | |
# Go back to the matching '[' | |
depth = 1 | |
while depth > 0: | |
self.instruction_pointer -= 1 | |
if code[self.instruction_pointer] == ']': | |
depth += 1 | |
elif code[self.instruction_pointer] == '[': | |
depth -= 1 | |
self.instruction_pointer += 1 | |
if __name__ == "__main__": | |
code = input("Enter Brainfuck code: ") | |
interpreter = BrainfuckInterpreter() | |
interpreter.execute(code) | |
print("\nOutput:") | |
print(interpreter.output_buffer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment