ZombieCPU/main.py
2021-02-01 18:25:35 -05:00

105 lines
2.5 KiB
Python

# made by zombie
# 02/01/21
import math
import numpy as np
import opcodes as ops
from console import Console
from memory import Memory
from registers import Registers
np.set_printoptions(threshold=np.inf)
class ZCPU:
_halted = False
_regs = Registers()
_mem = None
def __init__(self, memory, debug=None):
print('Processor Init')
self._debug = debug
self._mem = memory
def reset(self):
print('Processor Resetting')
self._regs.sp = self._mem.size() - 1 # Set stackpointer
self._regs.ip = 0 # Set instruction pointer
def exec(self):
while not self._halted:
# Fetch instruction
opcode = self._mem.read(self._regs.ip)
address = self._mem.read(self._regs.ip + 1)
value = self._mem.read(self._regs.ip + 2)
if self._debug:
print(f'Opcode: {opcode}\nAddress: {address}\nValue: {value}\nIP: {self._regs.ip}')
if opcode == ops.NOP: # No-op
pass
elif opcode == ops.HLT: # Halt
self._halted = True
elif opcode == ops.RST: # Reset
self.reset()
elif opcode == ops.DBG: # Debug (nop if debug is not set) -- This is stoopid
if self._debug:
print(f'Opcode: {opcode}\nAddress: {address}\nValue: {value}')
elif opcode == ops.LDI: # ldi
self._mem.write(address, value)
elif opcode == ops.PUSH: # push
self._mem.write(self._regs.sp, value)
self._regs.sp -= 1
elif opcode == ops.POP: # pop
self._regs.sp += 1
self._mem.write(address, self._mem.read(self._regs.sp))
else:
raise RuntimeException(f'Invalid Opcode: {opcode}')
#increment instruction pointer
self._regs.ip += 3
if __name__ == "__main__":
#hard coded opcodes
ram = Memory(65536)
ram.write(0, ops.LDI)
ram.write(1, 100)
ram.write(2, 5)
ram.write(3, ops.PUSH)
ram.write(4, 0)
ram.write(5, 69)
ram.write(6, ops.POP)
ram.write(7, 101)
ram.write(8, 0)
ram.write(9, ops.DBG)
ram.write(10, 1)
ram.write(11, 2)
ram.write(12, ops.HLT)
ram.write(13, 0)
ram.write(14, 0)
cpu = ZCPU(ram, False)
cpu.reset()
cpu.exec()
print(ram.read(100))
print(ram.read(101))
print(ram.read(102))
#c = Console(cpu.read_memory()) ima finish this later
#c.draw()