Advertisement
Python253

brainfuck_interpreter_manager

Jun 6th, 2024 (edited)
428
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.35 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: brainfuck_interpreter_manager.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.     - PasteBin Version Without Any Brainfuck Code (To Bypass PasteBin/NSA Idiotic Censors)
  10.    - This script provides a Brainfuck interpreter, enabling users to execute Brainfuck code.
  11.    - It utilizes a Python wrapper for the Brainfuck code execution.
  12.    - It includes functions to encode text into Brainfuck code and decode Brainfuck code back into text.
  13.    - It features a menu-driven interface for user interaction ease.
  14.    - The ASCII art header adds a visually appealing introduction to the Brainfuck Interpreter Manager.
  15.  
  16. Requirements:
  17.    - Python 3.x
  18.  
  19. Functions:
  20.    - brainfuck_interpreter(code):
  21.        Executes Brainfuck code and generates the corresponding output.
  22.    - encode_to_brainfuck(text):
  23.        Converts text into Brainfuck code for execution.
  24.    - decode_from_brainfuck(code):
  25.        Converts Brainfuck code into its original text.
  26.    - header():
  27.        Prints a visually appealing ASCII art header.
  28.  
  29. Usage:
  30.    Run the script and follow the menu prompts to encode text into Brainfuck or decode Brainfuck code into text.
  31.  
  32. Additional Notes:
  33.    - This script assumes the user input is valid Brainfuck code during decoding.
  34. """
  35.  
  36. def brainfuck_interpreter(code):
  37.     """
  38.    Interprets Brainfuck code.
  39.  
  40.    Args:
  41.        code (str): The Brainfuck code to interpret.
  42.  
  43.    Returns:
  44.        None
  45.  
  46.    Raises:
  47.        None
  48.    """
  49.  
  50.     # Convert the input code string into a list containing only valid Brainfuck commands
  51.     code = [c for c in code if c in ['>', '<', '+', '-', '.', ',', '[', ']']]
  52.  
  53.     # Initialize variables: tape (memory), pointer, code pointer, and loop stack
  54.     tape = [0] * 30000
  55.     ptr = 0
  56.     code_ptr = 0
  57.     loop_stack = []
  58.  
  59.     # Execute the Brainfuck code
  60.     while code_ptr < len(code):
  61.         command = code[code_ptr]  # Get the current command
  62.  
  63.         # Execute different commands based on the Brainfuck syntax
  64.         if command == '>':
  65.             ptr += 1  # Move the pointer to the right
  66.         elif command == '<':
  67.             ptr -= 1  # Move the pointer to the left
  68.         elif command == '+':
  69.             tape[ptr] = (tape[ptr] + 1) % 256  # Increment the value at the pointer
  70.         elif command == '-':
  71.             tape[ptr] = (tape[ptr] - 1) % 256  # Decrement the value at the pointer
  72.         elif command == '.':
  73.             print(chr(tape[ptr]), end='')  # Output the ASCII character at the pointer
  74.         elif command == ',':
  75.             tape[ptr] = ord(input('Input: ')[0])  # Input a character and store its ASCII value
  76.         elif command == '[':
  77.             if tape[ptr] == 0:  # If the value at the pointer is zero, skip to the matching ']'
  78.                 open_brackets = 1
  79.                 while open_brackets != 0:
  80.                     code_ptr += 1
  81.                     if code[code_ptr] == '[':
  82.                         open_brackets += 1
  83.                     elif code[code_ptr] == ']':
  84.                         open_brackets -= 1
  85.             else:
  86.                 loop_stack.append(code_ptr)  # Otherwise, push the current code pointer to the loop stack
  87.         elif command == ']':
  88.             if tape[ptr] != 0:  # If the value at the pointer is not zero, jump back to the matching '['
  89.                 code_ptr = loop_stack[-1]
  90.             else:
  91.                 loop_stack.pop()  # Otherwise, pop the last code pointer from the loop stack
  92.  
  93.         code_ptr += 1  # Move to the next command in the code
  94.  
  95. def encode_to_brainfuck(text):
  96.     """
  97.    Encodes text into Brainfuck code.
  98.  
  99.    Args:
  100.        text (str): The text to encode.
  101.  
  102.    Returns:
  103.        str: The Brainfuck code.
  104.  
  105.    Raises:
  106.        None
  107.    """
  108.  
  109.     # Initialize an empty string to store the Brainfuck code
  110.     brainfuck_code = ""
  111.  
  112.     # Iterate through each character in the input text
  113.     for char in text:
  114.         # Get the ASCII value of the character
  115.         ascii_value = ord(char)
  116.         # Append '+' repeated ascii_value times followed by '.>' to the Brainfuck code string
  117.         brainfuck_code += "+" * ascii_value + ".>"
  118.    
  119.     # Remove the last '>' from the Brainfuck code and return the encoded string
  120.     return brainfuck_code[:-1]
  121.  
  122. def decode_from_brainfuck(code):
  123.     """
  124.    Decodes Brainfuck code into text.
  125.  
  126.    Args:
  127.        code (str): The Brainfuck code to decode.
  128.  
  129.    Returns:
  130.        str: The decoded text.
  131.  
  132.    Raises:
  133.        None
  134.    """
  135.  
  136.     # Initialize variables: tape (memory), pointer, decoded text, code pointer, and loop stack
  137.     tape = [0] * 30000
  138.     ptr = 0
  139.     decoded_text = ""
  140.     code_ptr = 0
  141.     loop_stack = []
  142.  
  143.     # Execute the Brainfuck code
  144.     while code_ptr < len(code):
  145.         command = code[code_ptr]  # Get the current command
  146.  
  147.         # Execute different commands based on the Brainfuck syntax
  148.         if command == '>':
  149.             ptr += 1  # Move the pointer to the right
  150.         elif command == '<':
  151.             ptr -= 1  # Move the pointer to the left
  152.         elif command == '+':
  153.             tape[ptr] = (tape[ptr] + 1) % 256  # Increment the value at the pointer
  154.         elif command == '-':
  155.             tape[ptr] = (tape[ptr] - 1) % 256  # Decrement the value at the pointer
  156.         elif command == '.':
  157.             decoded_text += chr(tape[ptr])  # Append the ASCII character at the pointer to the decoded text
  158.         elif command == ',':
  159.             raise ValueError("Input command ',' is not supported in this decoding function.")
  160.         elif command == '[':
  161.             if tape[ptr] == 0:  # If the value at the pointer is zero, skip to the matching ']'
  162.                 open_brackets = 1
  163.                 while open_brackets != 0:
  164.                     code_ptr += 1
  165.                     if code[code_ptr] == '[':
  166.                         open_brackets += 1
  167.                     elif code[code_ptr] == ']':
  168.                         open_brackets -= 1
  169.             else:
  170.                 loop_stack.append(code_ptr)  # Otherwise, push the current code pointer to the loop stack
  171.         elif command == ']':
  172.             if tape[ptr] != 0:  # If the value at the pointer is not zero, jump back to the matching '['
  173.                 code_ptr = loop_stack[-1]
  174.             else:
  175.                 loop_stack.pop()  # Otherwise, pop the last code pointer from the loop stack
  176.  
  177.         code_ptr += 1  # Move to the next command in the code
  178.  
  179.     # Return the decoded text
  180.     return decoded_text
  181.  
  182. def header():
  183.     """
  184.    Prints the ASCII art header for the Brainfuck interpreter manager.
  185.    This function displays a stylized text banner for the Brainfuck interpreter manager,
  186.    providing a visually appealing introduction when the program is run.
  187.    """
  188.     print(r"""
  189.             ____   ____    ____  ____  ____   _____  __ __    __  __  _            
  190.            |    \ |    \ /    ||    ||    \ |     ||  |  |  /  ]|  |/ ]          
  191.            |  o  )|  D  )|  o  | |  | |  _  ||   __||  |  | /  / |  ' /            
  192.            |     ||    / |     | |  | |  |  ||  |_  |  |  |/  /  |    \          
  193.            |  O  ||    \ |  _  | |  | |  |  ||   _] |  :  /   \_ |     \          
  194.            |     ||  .  \|  |  | |  | |  |  ||  |   |     \    ||  .  |          
  195.            |_____||__|\_||__|__||____||__|__||__|    \__,_|\____||__|\_|                                                      
  196.                 ___ ___   ____  ____    ____   ____    ___  ____                  
  197.                |   |   | /    ||    \ /    | /    |  /  _]|    \                
  198.                | _   _ ||  o  ||  _  ||  o  ||   __| /  [_ |  D  )                
  199.                |  \_/  ||     ||  |  ||     ||  |  ||    _]|    /                  
  200.                |   |   ||  _  ||  |  ||  _  ||  |_ ||   [_ |    \                
  201.                |   |   ||  |  ||  |  ||  |  ||     ||     ||  .  \                
  202.                |___|___||__|__||__|__||__|__||___,_||_____||__|\_|                                                                                            
  203. """)
  204.    
  205. def main_loop():
  206.     """
  207.    Main loop for the Brainfuck interpreter menu.
  208.    """
  209.     while True:
  210.         print("\n\t\t\t:: BRAINFUCK INTERPRETER MENU ::\n")
  211.         print("1: Encode")
  212.         print("2: Decode")
  213.         print("0: Exit")
  214.         choice = input("\nSelect an option (or press '0' to exit): ")
  215.  
  216.         if choice == "1":
  217.             # Encode text
  218.             text = input("\nEnter text to encode: ")
  219.             brainfuck_code = encode_to_brainfuck(text)
  220.             print("\nEncoded Brainfuck code:", brainfuck_code)
  221.         elif choice == "2":
  222.             # Decode Brainfuck code
  223.             code = input("Enter Brainfuck code to decode: ")
  224.             decoded_text = decode_from_brainfuck(code)
  225.             print("\nDecoded text:", decoded_text)
  226.         elif choice == "0":
  227.             # Print Header & Exit Program
  228.             header()
  229.             print("_" * 100)
  230.             print("\n\t\t\t Exiting Program...   Goodbye!")
  231.             print("_" * 100)
  232.             break
  233.         else:
  234.             # Invalid choice
  235.             print("\nInvalid choice! Please select again.\n")
  236.  
  237. def main():
  238.     """
  239.    Main function to run the Brainfuck interpreter.
  240.    """
  241.     # Print the header ascii text
  242.     header()
  243.     input("Hit [ANY] Key To Continue.\n")
  244.    
  245.     # Print additional Brainfuck code and its execution result
  246.     print("_" * 100)
  247.     print(
  248.         """
  249.                       :: Brainfuck Commands ::
  250.  
  251.        > Increment the data pointer (move to the next cell to the right).
  252.        < Decrement the data pointer (move to the next cell to the left).
  253.        + Increment the byte at the data pointer.
  254.        - Decrement the byte at the data pointer.
  255.        . Output the byte at the data pointer as ASCII character.
  256.        , Input a character and store it in the byte at the data pointer.
  257.        [ If the byte at the data pointer is zero jump forward to the command after the matching ].
  258.        ] If the byte at the data pointer is nonzero jump back to the command after the matching [.
  259.        """)
  260.     print()  # Newline for ending
  261.     print("_" * 100)
  262.  
  263.     input("Hit [ANY] Key To Continue.\n")
  264.    
  265.     # Print Header Once More
  266.     print("\n" * 2)
  267.     header()
  268.    
  269.     # Run the main loop
  270.     main_loop()
  271.  
  272. if __name__ == "__main__":
  273.     main()
  274.  
  275.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement