16 Aralık 2007 Pazar

Brainfuckcan

Python ile brainfuck interpreter ı yazdım.bikaç yerde(+ ve - operatörleri) azıcık kopya çekmiş olsam da :p.ahanda:


import sys
import array
class brainfuck:
"Brainfuck code.can be interpreted :p"

def __init__(self,code = "",file_or_string = 's',max_size = 30000 ):
self.data= array.array('B', ( 0 for _ in xrange(max_size)))
if (code != ""):
if(file_or_string == 's'):
self.read(code)
elif(file_or_string == 'f'):
self.read_file(code)
else:
print "WARNING: File_or_string invalid - no code loaded."

def read(self,code):
"Reads the code string"
self.code = code

def read_file(self,filename):
"Reads the code from the specified file"
code_file = open(filename, 'r')
self.code = code_file.read()

def run(self):
"Obviously,interpretes and runs the code"
pos = 0 #the position in code
ptr = 0 #data pointer

while pos < curr =" self.code[pos]"><+-.,[]": #operators currd = self.data[ptr] #current data at the pointer if curr == '>':
ptr += 1
elif curr == '<':
ptr -= 1

elif curr == '+':
self.data[ptr] = (currd + 1) & 0xFF
elif curr == '-':
self.data[ptr] = (currd - 1) & 0xFF

elif curr == '.':
sys.stdout.write(chr(currd))
elif curr == ',':
self.data[pos] = raw_input()[0]

elif curr == '[':
if currd == 0:
par = 1
while(par):
pos += 1
if self.code[pos] == ']':
par -= 1
if par == 0:
break
elif self.code[pos] == '[':
par +=1
elif curr == ']':
if currd != 0:
par = 1
while (par):
pos -= 1
if self.code[pos] == '[':
par -= 1
if par == 0:
break
elif self.code[pos] == ']':
par += 1
#end of operator control
pos += 1 #increementing position by 1
#end of brainfuck.run function
#end of brainfuck class

bide inputu tam düzgün çalışmamakta sanki

Hiç yorum yok:

Yorum Gönder