Skip to content

Instantly share code, notes, and snippets.

@ryosan-470
Last active August 29, 2015 14:17
Show Gist options
  • Save ryosan-470/47179a4a8afc4811f8ce to your computer and use it in GitHub Desktop.
Save ryosan-470/47179a4a8afc4811f8ce to your computer and use it in GitHub Desktop.
The "BrainF*ck" language is implemented using the Python.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Reference:
+ [Wikipedia:Brainfuck](http://en.wikipedia.org/wiki/Brainfuck)
+ [PythonでBrainf*ckを書いてみた](http://emoson.hateblo.jp/entry/2014/10/14/193825)
"""
pc = 0 # program counter
mem = [0 for i in range(30000)]
ptr = 0 # pointer
def eval(code):
global pc, ptr
while pc < len(code):
if code[pc] == ".":
# output the byte at the data pointer
print(chr(mem[ptr]), end="")
elif code[pc] == ",":
# accept the char input
mem[ptr] = ord(input())
elif code[pc] == "+":
# increment the byte at the data pointer
mem[ptr] += 1
elif code[pc] == "-":
# decrement the byte at the data pointer
mem[ptr] -= 1
elif code[pc] == "<":
# increment the data pointer (to point to the next cell to the right)
ptr += 1
elif code[pc] == ">":
# decrement the data pointer (to point to the next cell to the left)
ptr -= 1
# "[" メモリポインタが指す値が0なら対応する"]"までスキップ
elif code[pc] == "[":
if mem[ptr] == 0:
nest = 0
while True:
pc += 1
if code[pc] == "]" and nest == 0:
break
if code[pc] == "[":
nest += 1
if code[pc] == "]":
nest -= 1
# "]" メモリポインタが指す値が非0なら対応する"["まで戻る
# jump
elif code[pc] == "]":
if mem[ptr] != 0:
while True:
nest = 0
pc -= 1
if code[pc] == "[" and nest == 0:
break
if code[pc] == "[":
nest -= 1
if code[pc] == "]":
nest += 1
pc += 1
sys.stdout.write("\n")
if __name__ == "__main__":
import sys
code = ""
if len(sys.argv) >= 2:
with open(sys.argv[1]) as f:
for d in f:
code += d
else:
code = input(">> ")
eval(code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment