val instruction = fetchNextInstruction() when (instruction) { 0x0 -> handleBreak() 0x8 -> handlePushProcessorStatus() 0x10 -> handleBranchOnPlus() // Many other instructions... else -> throw IllegalStateException("Unknown instruction: ${instruction.toHex()}") } inline fun Int.toHex() = this.toString(16)
fun getCartridgeMapper(rom: Cartridge): Mapper { var mapper: Mapper? = null when (rom.mapperId) { 1 -> mapper = MMC1(rom) 3 -> mapper = CNROM(rom) 4 -> mapper = MMC3(rom) // Etc… } return mapper ?: throw NotImplementedError("Mapper for ${rom.mapperId} not yet implemented") }
fun getCartridgeMapper(rom: Cartridge): Mapper = when (rom.mapperId) { 1 -> MMC1(rom) 3 -> CNROM(rom) 4 -> MMC3(rom) // Etc... else -> throw NotImplementedError("Mapper for ${rom.mapperId} not yet implemented") }
val data = when (addressToRead) { in 0..0x1fff -> { // With this mapper, the graphics for the game can be in one of two locations. // We can figure out which one to look in based on the memory address. val bank = addressToRead / 0x1000 val bankAddress = addressToRead % 0x1000 readBank(bank, bankAddress) } in 0x6000..0x7fff -> { // There's 8k of program (PRG) RAM in the cartridge mapped here. readPrgRam(addressToRead - 0x6000) } // etc... }
sealed class Interrupt class NonMaskableInterrupt : Interrupt() class ResetInterrupt : Interrupt() class BreakInterrupt : Interrupt() class InterruptRequestInterrupt(val number: Int) : Interrupt()
interrupt?.let { val handled = when (interrupt) { is NonMaskableInterrupt -> handleNMI() is ResetInterrupt -> handleReset() is BreakInterrupt -> handleBreak() is InterruptRequestInterrupt -> handleIRQ(interrupt.number) } }
when { address < 0x2000 -> writeBank(address, value) address >= 0x6000 && address < 0x8000 -> writeSRam(address, value) address >= 0x8000 -> writeRegister(address, value) else -> throw RuntimeException("Unhandled write to address ${address.toHex()}") }
getMapper().let { mapper -> when (mapper) { is MMC5 -> mapper.audioTick() is Mapper49 -> mapper.processQuirks() // Etc... } }
when (val mapper = getMapper()) { is MMC5 -> mapper.audioTick() is Mapper49 -> mapper.processQuirks() // Etc... }