2D-Reversable 2/Python Implementation

From Esolang
Jump to navigation Jump to search

Original (and ugly) implementation of 2D-Reversable 2 by User:Dulph

class BiReversable2Error(Exception):
	pass

prog = input()
prog.replace("\t","")
prog=prog.split("\n")
endProg = []
for i in prog:
	endProg.append(i.split(" "))

variables={}
direction = [0, 1]
c1=0
c2=0
while c1 >= 0 and c2 >= 0 and c1 < len(endProg) and c2 < len(endProg[c1]) and direction != [0, 0]:
	if endProg[c1][c2] == "UP":
		direction[0] = -1
	elif endProg[c1][c2] == "DOWN":
		direction[0] = 1
	elif endProg[c1][c2] == "RIGHT":
		direction[1] = 1
	elif endProg[c1][c2] == "LEFT":
		direction[1] = -1
	elif endProg[c1][c2] == "REVERSE":
		direction = [-direction[0], -direction[1]]
	elif endProg[c1][c2] == "MIDDLE-V":
		direction[0] = 0
	elif endProg[c1][c2] == "MIDDLE-H":
		direction[1] = 0
	elif endProg[c1][c2] == "SKIP":
		c1 += direction[0]
		c2 += direction[1]
	elif "GET-" in endProg[c1][c2]:
		t=prog[c1][c2].replace("GET-", "")
		if t[0] not in ["I", "S"]:
			raise BiReversable2Error("%s is not a valid variable type"%t[0])
		elif t[0] == "I":
			variables[t]=int(input()[0])
		else:
			variables[t]=input()[0]
	elif "OUT-" in endProg[c1][c2]:
		print(variables[endProg[c1][c2].replace("OUT-","")])
	elif "+" in prog[c1][c2]:
		t=prog[c1][c2].split("+")
		try:
			variables[t[0]]
		except KeyError:
			variables[t[0]]=0
		try:
			variables[t[1]]
		except KeyError:
			variables[t[1]]=0
		variables[t[0]] += variables[t[1]]
	elif "-" in prog[c1][c2]:
		t=prog[c1][c2].split("-")
		try:
			variables[t[0]]
		except KeyError:
			variables[t[0]]=0
		try:
			variables[t[1]]
		except KeyError:
			variables[t[1]]=0
		variables[t[0]] -= variables[t[1]]
	elif "*" in prog[c1][c2]:
		t=prog[c1][c2].split("*")
		try:
			variables[t[0]]
		except KeyError:
			variables[t[0]]=0
		try:
			variables[t[1]]
		except KeyError:
			variables[t[1]]=0
		variables[t[0]] *= variables[t[1]]
	elif "%" in prog[c1][c2]:
		t=prog[c1][c2].split("%")
		try:
			variables[t[0]]
		except KeyError:
			variables[t[0]]=0
		try:
			variables[t[1]]
		except KeyError:
			variables[t[1]]=0
		variables[t[0]] %= variables[t[1]]
	elif endProg[c1][c2] != "NOP":
		print("Unknown function :", endProg[c1][c2])
	c1 += direction[0]
	c2 += direction[1]