from kandinsky import * from ion import keydown,KEY_EXE class cardiac: bgcolor = (176, 208, 184) active = (255, 0, 0) def __init__(self, program, memory, input_tape=[]): self.memory = [1] + [0] * 48 self.pc = min(program.keys()) self.acc = 0 self.input_tape = input_tape self.output_tape = [] self.decimals = 10**4 self.op = "INP","CLA","ADD","TAC","SFT","OUT","STO","SUB","JMP","HRS" for addr, instrs in program.items(): for i, instr in enumerate(instrs): self.memory[addr + i] = instr for addr, value in memory.items(): self.memory[addr] = value def init(self): fill_rect(0,0,320,222,cardiac.bgcolor) for i,v in enumerate((" PC"," IR","COD","OPE","ACC","INP","OUT")): draw_string(v+":", 5, 10 + 25 * i, "black",cardiac.bgcolor) def update(self, state): self.init() for i in range(48): col = cardiac.bgcolor if i != self.pc else cardiac.active draw_string("{:02}".format(i), 90 + 58 * (i // 12), 2 + 18 * (i % 12), "white",col) draw_string("{:03}".format(self.memory[i]), 113 + 58 * (i // 12), 2 + 18 * (i % 12)) for i, v in enumerate(state): draw_string(str(v), 45, 10 + 25 * i) while not(keydown(KEY_EXE)):continue while keydown(KEY_EXE):continue def fetch_execute(self): while True: instr = self.memory[self.pc] opcode, addr = divmod(instr, 100) if opcode == 0: #INP if self.input_tape: self.memory[addr] = self.input_tape.pop(0) else: break elif opcode == 1: #CLA self.acc = self.memory[addr] elif opcode == 2: #ADD self.acc += self.memory[addr] elif opcode == 3: #TAC if self.acc < 0: self.pc = addr - 1 elif opcode == 4: #SFT left, right = divmod(addr, 10) self.acc = (self.acc * (10**left) % self.decimals) // (10**right) elif opcode == 5: #OUT self.output_tape.append(self.memory[addr]) elif opcode == 6: #STO self.memory[addr] = self.acc elif opcode == 7: #SUB self.acc -= self.memory[addr] elif opcode == 8: #JMP self.pc = addr - 1 elif opcode == 9: #HRS break tape = self.input_tape[0] if self.input_tape else "" out = self.output_tape[-1] if self.output_tape else "" self.pc += 1 self.update((self.pc,instr,self.op[opcode],addr,self.acc, tape,out)) def run(self): self.fetch_execute() return self.output_tape