HQ9+2D

From Esolang
Jump to navigation Jump to search

HQ9+2D is an extension of HQ9+ by Kenner Gordon. It has an instruction pointer which starts at the first byte of the program, moving east. It has the following commands:

Command Description
H Print "Hello, world!"
Q Print the source code of the program.
9 Print the lyrics to "99 Bottles of Beer on the Wall".
+ Increment the instruction counter.
> Move east.
< Move west.
^ Move north.
v Move south.

Interpreters

Python 3 interpreter:

def run_HQ9p2D(code_string: str, textfile = False):
    code = []
    direction = '>'
    instruction_counter = 0
    if textfile:
        temp = ''
        for line in open(code_string, 'r'):
            temp += line
            code.append(line.strip('\n'))
        code_string = temp
    else:
        code = code_string.split('\n')
    code_width = max([len(line) for line in code])
    pointer = (0,0)
    while 0 <= pointer[0] < len(code) and 0 <= pointer[1] < code_width:
        south = pointer[0]
        east = pointer[1]
        if east >= len(code[south]) or code[south][east] not in 'HQ9+^v<>':
            pass
        else:
            char = code[south][east]
            if char in '^v<>':
                direction = char
            elif char == 'H':
                print('Hello, world!')
            elif char == 'Q':
                print(code_string)
            elif char == '9':
                for i in range(99, 2, -1):
                    print(f'{i} bottles of beer on the wall,\n'
                          f'{i} bottles of beer!\n'
                          f"Take one down, pass it around,\n"
                          f"{i-1} bottles of beer on the wall!")
                print("2 bottles of beer on the wall\n"
                      "2 bottles of beer!\n"
                      "Take one down, pass it around\n"
                      "1 bottle of beer on the wall!\n"
                      "1 bottle of beer on the wall,\n"
                      "1 bottle of beer!\n"
                      "Take one down, pass it around,\n"
                      "No bottles of beer on the wall!")
            elif char == '+':
                instruction_counter += 1
        if direction == '>':
            pointer = (pointer[0],pointer[1]+1)
        elif direction == 'v':
            pointer = (pointer[0]+1,pointer[1])
        elif direction == '<':
            pointer = (pointer[0],pointer[1]-1)
        else:
            pointer = (pointer[0]-1,pointer[1])