ZombieCPU/main.py

106 lines
2.5 KiB
Python
Raw Permalink Normal View History

2021-02-01 18:22:51 -05:00
# made by zombie
# 02/01/21
2021-02-01 14:31:07 -05:00
import math
import numpy as np
2021-02-01 18:22:51 -05:00
import opcodes as ops
2021-02-01 17:14:01 -05:00
from console import Console
2021-02-01 18:22:51 -05:00
from memory import Memory
from registers import Registers
2021-02-01 17:14:01 -05:00
np.set_printoptions(threshold=np.inf)
2021-02-01 14:31:07 -05:00
2021-02-01 18:22:51 -05:00
class ZCPU:
_halted = False
_regs = Registers()
_mem = None
2021-02-01 14:31:07 -05:00
2021-02-01 18:22:51 -05:00
def __init__(self, memory, debug=None):
2021-02-01 14:31:07 -05:00
print('Processor Init')
self._debug = debug
2021-02-01 18:22:51 -05:00
self._mem = memory
2021-02-01 14:31:07 -05:00
def reset(self):
print('Processor Resetting')
2021-02-01 18:22:51 -05:00
self._regs.sp = self._mem.size() - 1 # Set stackpointer
self._regs.ip = 0 # Set instruction pointer
2021-02-01 14:31:07 -05:00
def exec(self):
2021-02-01 18:22:51 -05:00
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)
2021-02-01 14:31:07 -05:00
if self._debug:
2021-02-01 18:22:51 -05:00
print(f'Opcode: {opcode}\nAddress: {address}\nValue: {value}\nIP: {self._regs.ip}')
if opcode == ops.NOP: # No-op
pass
2021-02-01 14:31:07 -05:00
2021-02-01 18:22:51 -05:00
elif opcode == ops.HLT: # Halt
self._halted = True
2021-02-01 14:31:07 -05:00
2021-02-01 18:22:51 -05:00
elif opcode == ops.RST: # Reset
2021-02-01 14:31:07 -05:00
self.reset()
2021-02-01 18:22:51 -05:00
elif opcode == ops.DBG: # Debug (nop if debug is not set) -- This is stoopid
2021-02-01 14:31:07 -05:00
if self._debug:
print(f'Opcode: {opcode}\nAddress: {address}\nValue: {value}')
2021-02-01 18:22:51 -05:00
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
2021-02-01 14:31:07 -05:00
if __name__ == "__main__":
#hard coded opcodes
2021-02-01 18:22:51 -05:00
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()
2021-02-01 17:14:01 -05:00
2021-02-01 14:31:07 -05:00
cpu.exec()
2021-02-01 18:22:51 -05:00
print(ram.read(100))
print(ram.read(101))
print(ram.read(102))
2021-02-01 17:14:01 -05:00
#c = Console(cpu.read_memory()) ima finish this later
#c.draw()
2021-02-01 18:22:51 -05:00