Brainfuck

Usually, programming languages are designed to be efficient, understandable and usable. Their concepts are well thought-out, giving the programmer powerful tools to create their application.
Esoteric programming languages have a slightly different aim. Instead of focusing on the product, they focus on the programmer’s journey and try new approaches to building a program.
One well-known esoteric programming language is Urban Müller’s brainfuck. It is a Turing-complete programming language – meaning that it could with infinite memory do what a Turing machine can do –, which practices extreme minimalism. The language knows of only eight characters (“<>+-[].,”).
The language’s usage is very similar to a Turing machine. Starting the program, the pointer is at cell zero and can be moved left (“<“) or right (“>”) by one cell.
The cells’ values are all starting at 0, but can be either increased (“+”) or decreased (“-“) by one. Because the cells can only store one unsigned byte, adding one to 255 yields in 0 and subtracting one from 0 yields in 255.
Also, a loop is possible by using square brackets. An open square bracket (“[“) starts a loop and a closed square bracket (“]”) ends a loop. When the end of a loop is reached, the interpreter will jump back to its start if and only if the currently selected cell’s value is 0.
The only way to communicate with the user is to print the currently selected cell’s ASCII character to the screen (“.”) and get a user input which will be stored in the currently selected cell as its ASCII value (“,”).

Because of its minimalistic design, writing an interpreter is not particularly hard. Listed below is the Python code of my interpreter, which I used to execute my own brainfuck “Hello World.” program (118 characters).
Online interpreters include for example bf.doleczek.pl and sange.fi.

Useful Wikipedia articles include Esoteric Programming Language, Brainfuck and Turing Machine.

$ python brainfuck.py
Hello World.

# Python 2.7.7 Code
# Jonathan Frech 27th of October , 2016
#         edited  1st of November, 2016
#         edited  3rd of November, 2016
#         edited  9th of May     , 2017
#          * bug fix: '[' with current cell equaling
#            0 will jump to matching ']'
#          * bug fix: brackets now have to match

# import
import sys

# brainfuck "Hello World." code
code = "+++++[>+++++<-]>[>+>++>+++>++++<<<<-]>>>---.>+.+++++++..+++.<<<+++++++.>>+++++++++++++++.>.+++.------.--------.<<----."
#print len(code)

# put character (.)
def putch(ch):
	sys.stdout.write(ch)

# get character (,)
def getch():
	# Windows
	try:
		import msvscrt
		return msvcrt.getch()
	
	# Unix
	except:
		import tty, termios
		fd = sys.stdin.fileno()
		settings = termios.tcgetattr(fd)
		try:
			tty.setraw(sys.stdin.fileno())
			ch = sys.stdin.read(1)
		finally:
			termios.tcsetattr(fd, termios.TCSADRAIN, settings)
		
		if ord(ch) == 3:
			sys.exit()
				
		return ch

# interpret brainfuck code
def brainfuck(code):
	# <coded 9th of may 2017>
	if code.count("[") != code.count("]"):
		print "error: brackets '[' and ']' do not match."
		return
	# </coded>
	
	codepointer = 0
	codepointers = []
	
	cells = [0]
	pointer = 0
	
	# work through code
	while codepointer < len(code):
		# current char
		char = code[codepointer]
		
		# add / subtract
		if char == "+":
			cells[pointer] = (cells[pointer]+1)%256
		elif char == "-":
			cells[pointer] = (cells[pointer]-1)%256
		
		# move left / right
		elif char == "<":
			pointer -= 1
			if pointer < 0:
				cells.insert(0, 0)
				pointer = 0
		elif char == ">":
			pointer += 1
			if pointer >= len(cells):
				cells.append(0)
		
		# loop start / end
		elif char == "[":
			# <coded 9th of may 2017>
			if cells[pointer] != 0:
				codepointers.append(codepointer)

			# ignore loop start if current cells equals zero!
			else:
				codepointer += 1
				i = 1
				while i > 0:
					if code[codepointer] == "[": i += 1
					elif code[codepointer] == "]": i -= 1
					codepointer += 1
			# </coded>
		elif char == "]":
			if len(codepointers) > 0:
				p = codepointers.pop(-1)
				if cells[pointer] != 0:
					codepointer = p-1
		
		# put / get char
		elif char == ".":
			putch(chr(cells[pointer]))
		elif char == ",":
			cells[pointer] = ord(getch())
		
		# advance code pointer
		codepointer += 1
		
	# end screen
	if False:
		print "\n"
		print "======="
		print " CELLS "
		print "======="
		print " ".join(map(str, cells)) + " @ " + str(pointer)
	
	# line buffer
	print

# run code
brainfuck(code)
Advertisements

One thought on “Brainfuck

  1. Pingback: Brainfuck X – J-Blog

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s