Brainfuck X

While browsing StackExchange PCG questions and answers, I came across a challenge regarding drawing the swiss flag. In particular, I was interested in benzene’s answer, in which they showcased a Brainfuck dialect capable of creating two-dimensional 24-bit color images. In this post I present this dialect with slight changes of my own, as well as an interpreter I wrote in Python 2.7 (source code is listed below and can also be downloaded).

Brainfuck X generated Swiss flagUrban Müller’s original Brainfuck (my vanilla Brainfuck post can be found here) works similar to a Turing machine, in that the memory consists of a theoretically infinitely large tape with individual cells which can be modified. What allows Brainfuck X (or Braindraw, as benzene called their dialect) to create color images is, that instead of a one-dimensional tape, a three-dimensional tape is used. This tape extends infinitely in two spacial dimensions and has three color planes. Each cell’s value is limited to a byte (an integer value from 0 to 255) which results in a 24-bit color depth.

Adding to Brainfucks eight commands (+-<>[].,), there are two characters to move up and down the tape (^v) and one character to move forwards in the color dimension (*). Starting on the red color plane, continuing with the green and ending in the blue. After the blue color plane, the color planes cycle and the red color plane is selected. benzene’s original language design which I altered slightly had three characters (rgb) to directly select a color plane. Whilst this version is supported by my interpreter (the flag --colorletters is necessary for that functionality), I find my color star more Brainfucky — directly calling color planes by their name seems nearly readable.
Brainfuck’s vanilla eight characters still work in the same way, Brainfuck X can thereby execute any vanilla Brainfuck program. Also, there still is a plaintext output — the tape’s image is a program’s secondary output.

Having executed the final Brainfuck instruction, the interpreter prints out the tape to the terminal — using ANSI escape codes. Because of this, the color depth is truncated in the terminal view, as there are only 216 colors supported.
For the full 24-bit color depth output, I use the highly inefficient Portable Pixmap Format (.ppm) as an output image file format. To open .ppm files, I recommend using the GNU Image Manipulation Program; specifying the output file name is done via the --output flag.

The Swiss flag image above was generated by benzene’s Braindraw code (see their StackExchange answer linked to above); the resulting .ppm file was then scaled and converted using GIMP.
Interpreter command: python brainfuckx.py swiss.bfx -l -o swiss.ppm

Usage

  • Being written in pure Python, the interpreter is completely controlled via the command line. The basic usage is python brainfuckx.py <source code file>; by using certain flags the functionality can be altered.
  • --input <input string>-i <input string> specifies Brainfuck’s input and is given as a byte stream (string).
  • --simplify, -s outputs the source code’s simplified version; the source code with all unnecessary characters removed.
  • --colorstar selects the color star color plane change model which is the default.
  • --colorletters, -l selects the color letter color plane change model.
  • --silent stops the interpreter from outputting warnings, infos and the final tape.
  • --maxcycles <cycles>, -m <cycles> defines the maximum number of cycles the Brainfuck program can run; the default is one million.
  • --watch, -w allows the user to watch the program’s execution.
  • --watchdelay <delay> defines the time in seconds the interpreter sleeps between each watch frame.
  • --watchskip <N> tells the interpreter to only show every Nth cycle of the execution.
  • --output <output file name>, -o <output file name> saves the final tape as a .ppm image file.

# Python 2.7 Code; Jonathan Frech, 24th, 25th of August 2017

"""
	=============
	 BRAINFUCK X 
	=============
	
	Python 2.7 Brainfuck X interpreter; written by Jonathan Frech.
	Brainfuck X is a Brainfuck extension that adds three new operators ('^', 'v', '*') and 24 bit color support. It is also called Braindraw.
	Input files have the .bfx extension.
	
	The source code is one-dimensional, read from left to right.
	Looping works like in Brainfuck, using '[' and ']':
		if the code pointer reaches an open bracket, it is ignored if the current cell is non-zero and jumped to the matching closing bracket if it is zero
		if the code pointer reaches a closed bracket, it is ignored if the current cell is zero and jumped to the (prior) matching open bracket if it is non-zero
	The used tape is three-dimensional, two spacial and one color dimension. Each cell's value is limited to 8 bits (0-255). Values outside the value bound are modulo-wrapped.
	The tape's size is only restricted in the color dimension (there are three color planes).
	Moving around the tape is done via moving in the four cardinal directions using '^', '>', 'v' (only lowercase!) and '<'
	Movement through the three color planes depends on the '--colorletters' flag. (1)
		Using color letters, one can jump to a color plane using its one-letter acronym ('r', 'g' and 'b')
		Not using color letters, one can move forwards through the color planes using '*' (starting at 'r', continuing with 'g' and 'b', then wrapping around).
	Input and output works like in the original Brainfuck; '.' output the current cell's value interpreted as an ASCII character and ',' takes a character as input and saves it in the current cell.

	(1) The original StackExchange answer used the color letters model. Though, I found it more Brainfucky to simply use a single character.
"""

# import
import argparse, time
	
# main function
def main():
	# start timer
	t0 = time.time()
	
	# ==================
	#  ARGUMENT PARSING 
	# ==================
	
	# using argparse to parse command line arguments
	parser = argparse.ArgumentParser(description = "A Brainfuck dialect. Colorful, three-dimensional.")
	parser.add_argument("source"        ,       metavar = "S", type = str                   , help = "Source code file name"                                                                 )
	parser.add_argument("--input"       , "-i", metavar = "I", type = str                   , help = "String as input character stream. It is warned when the input stream is too short."    )
	parser.add_argument("--simplify"    , "-s", action  = "store_true"                      , help = "Ouput the given source code's simplified version (all unnecessary characters removed).")
	parser.add_argument("--colorstar"   ,       action  = "store_true"                      , help = "Use color star ('*') to move through color planes (the default)."                      )
	parser.add_argument("--colorletters", "-l", action  = "store_true"                      , help = "Use color letters ('rgb') to swap color planes."                                       )
	parser.add_argument("--silent"      ,       action  = "store_true"                      , help = "Silent mode, disable infos and warnings."                                              )
	parser.add_argument("--maxcycles"   , "-m", metavar = "C", type = int  , default = 10**6, help = "Maximum number of cycles."                                                             )
	parser.add_argument("--watch"       , "-w", action  = "store_true"                      , help = "Watch the program's execution."                                                        )
	parser.add_argument("--watchdelay"  ,       metavar = "T", type = float, default = .1   , help = "Time between cycles in seconds while watching."                                        )
	parser.add_argument("--watchskip"   ,       metavar = "N", type = int  , default = 1    , help = "Only the Nth cycle is printed in watch mode."                                          )
	parser.add_argument("--output"      , "-o", metavar = "O", type = str                   , help = "Output tape filememory (saved in the ppm file format)."                                )
	parsed = parser.parse_args()
	
	# colored ANSI escape codes; error, warning, info, output, tape, code
	err, wrn, inf = "\033[38;5;9mError\033[0m: ", "\033[38;5;11mWarning\033[0m: ", "\033[38;5;10mInfo\033[0m: "
	out, tap, cod = "\033[38;5;12mOut\033[0m: " , "\033[38;5;12mTape\033[0m: "   , "\033[38;5;12mCode\033[0m: "
	Wrn, Inf, Out = [], [], []
	
	# ===========
	#  FUNCTIONS 
	# ===========
	
	# return given string's ANSI-colored version (colors in 0..255 range, are converted to 0..5 range)
	def ansi(s, r, g, b): r, g, b = int(r/255.*5), int(g/255.*5), int(b/255.*5); return "\033[48;5;%dm%s\033[0m" % (16+36*r+6*g+b, s)
	
	# print code with highlighted code pointer and tape position and current cycle information
	def printcode(): n = 20; c = (" "*n)+code+(" "*n); print "%s{... %s\033[48;7;1m%s\033[0m%s ...}; Code pointer: %d; Tape position: {%d, %d, %d}; Cycles: %d" % (cod, c[codepointer-1-n+n:codepointer-1+n], c[codepointer-1+n], c[codepointer+n:codepointer+n+n], codepointer, x, y, z, cycles)
	
	# print tape with highlighted tape position
	def printtape(): print tap + "\n" + "\n".join(["{%s}" % "".join([("\033[38;5;%dm%02X\033[0m" % ((9, 10, 12)[z], tape[z][y][x])) if X == x and Y == y else (ansi("%02X"%tape[z][Y][X], tape[0][Y][X], tape[1][Y][X], tape[2][Y][X])) for X in range(len(tape[0][0])) ]) for Y in range(len(tape[0])) ])
	
	# save tape in ppm file format
	def saveppm(tape, fn): w, h = len(tape[0][0]), len(tape[0]); f = open(fn, "w"); f.write("P3 %d %d 255\n" % (w, h) + "\n".join(["\n".join(["%03d %03d %03d" % (tape[0][y][x], tape[1][y][x], tape[2][y][x]) for x in range(w)]) for y in range(h)])); f.close()
	
	# ==================
	#  INPUT VALIDATION 
	# ==================
	
	# attempt to open source code file
	try   : f = open(parsed.source); rawcode = f.read(); f.close()
	except: print err + "Could not open source code file."; return
	
	# color movement
	colormovement = "*"
	if parsed.colorstar   : colormovement = "*"
	if parsed.colorletters: colormovement = "l"
	if parsed.colorstar and parsed.colorletters: colormovement = "*"; Wrn.append("Cannot use both color star and letters; using color star.")
	
	# cycles / watch
	if parsed.maxcycles <= 0: Wrn.append("Maximum cycles are minimal.")
	if parsed.watchdelay < 0: parsed.watchdelay = 0; Wrn.append("Watch delay less than 0, assuming 0.")
	if parsed.watchskip < 1: parsed.watchskip = 1; Wrn.append("Watch skip less than 1, assuming 1.")
	
	# possible version problem
	if colormovement == "*" and ("r" in rawcode or "g" in rawcode or "b" in rawcode): Wrn.append("Code may require color letters.")
	if colormovement == "l" and  "*" in rawcode                                     : Wrn.append("Code may require color stars."  )
	
	# output file format
	if parsed.output and parsed.output[-4:] != ".ppm": Wrn.append("Output file is saved as a Portable Pixel Map; given file name does not end in .ppm.")
			
	# =============
	#  INTERPRETER 
	# =============

	# simplify code
	if colormovement == "*": code = "".join([c if c in "+-^v<>[].,*"   else "" for c in rawcode])
	if colormovement == "l": code = "".join([c if c in "+-^v<>[].,rgb" else "" for c in rawcode])
	
	# print out simplified code
	if parsed.simplify: print code; return
	# program input
	inputpointer = -1
	inputstring = parsed.input or ""
	outputstring = ""
	
	# pointer to current place in code
	codepointer = 0
	
	# three-dimensional tape
	tape = [
		[[0]],
		[[0]],
		[[0]]
	]
	x, y, z = 0, 0, 0
	
	# number of cycles needed
	cycles = 0
	
	# main loop
	while codepointer < len(code):
		# another cycle needed; fetch char
		cycles += 1; c = code[codepointer]; codepointer += 1
		
		# interpret character
		if   c == "+": tape[z][y][x] = (tape[z][y][x]+1)%256
		elif c == "-": tape[z][y][x] = (tape[z][y][x]-1)%256
		elif c == "^":
			y -= 1
			while y < 0:
				for Z in range(len(tape)): tape[Z].insert(0, [0]*len(tape[0][0]))
				y += 1
		elif c == "v":
			y += 1
			while y >= len(tape[0]):
				for Z in range(len(tape)): tape[Z].append([0]*len(tape[0][0]))
		elif c == "<":
			x -= 1
			while x < 0:
				for Z in range(len(tape)):
					for Y in range(len(tape[0])): tape[Z][Y].insert(0, 0)
				x += 1
		elif c == ">":
			x += 1
			while x >= len(tape[0][0]):
				for Z in range(len(tape)):
					for Y in range(len(tape[0])): tape[Z][Y].append(0)
		elif c == "[":
			if tape[z][y][x] == 0:
				b = 1
				codepointer -= 1
				while b > 0:
					codepointer += 1
					if codepointer >= len(code): print err + "Looping outside source (>)."; return
					if code[codepointer] == "[": b += 1
					if code[codepointer] == "]": b -= 1
				codepointer += 1
		elif c == "]":
			if tape[z][y][x] != 0:
				b = 1
				codepointer -= 1
				while b > 0:
					codepointer -= 1
					if codepointer < 0: print err + "Looping outside source (<)."; return
					if code[codepointer] == "[": b -= 1
					if code[codepointer] == "]": b += 1
				codepointer += 1
		elif c == ".": outputstring += chr(tape[z][y][x])
		elif c == ",": inputpointer += 1; tape[z][y][x] = ord(inputstring[inputpointer]) if inputpointer < len(intputstring) else 0
		elif c == "*": z = (z+1)%3
		elif c == "r": z =  0
		elif c == "g": z =  1
		elif c == "b": z =  2
		
		# watch the program's execution
		if parsed.watch and cycles % parsed.watchskip == 0: printtape(); printcode(); time.sleep(parsed.watchdelay)
		
		# maximum number of cycles
		if cycles >= parsed.maxcycles: Wrn.append("Cycles required exceeded maximum cycles cap (program was halted)."); break
	
	# input length
	if inputpointer >= len(inputstring): Wrn.append("Given input was too short.")
	
	# output
	Out.append(outputstring.encode("string_escape"))
	
	# stop timer, print final status message
	t = time.time()-t0; Inf.append("Taken %d cycle%s and %.2f seconds (%s seconds/cycle)." % (cycles, "s "[cycles == 1], t, "%.8f" % (t/cycles) if cycles != 0 else "/"))
	
	# save final tape
	if parsed.output:
		try   : saveppm(tape, parsed.output)
		except: Wrn.append("Could not save tape.")
	
	# print final tape, warnings, info and output
	if not parsed.silent                 : printtape(); printcode()
	if not parsed.silent and len(Wrn) > 0: print "\n".join([wrn+w for w in Wrn])
	if not parsed.silent and len(Inf) > 0: print "\n".join([inf+i for i in Inf])
	print "\n".join(["%s'%s'" % (out, o) for o in Out])
	
# main	
if __name__ == "__main__": main()
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.