Skip to content

Commit

Permalink
Run user script
Browse files Browse the repository at this point in the history
  • Loading branch information
tyfkda committed Jun 5, 2024
1 parent b01e806 commit dc5d53a
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion nodejs/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ class MyApp {
protected cartridge: Cartridge
private nes: Nes
private pad = 0
private additionalPad = 0
private timer: NodeJS.Timer | undefined
private controller: any

private audioManager = new AudioManager()

Expand All @@ -74,6 +76,17 @@ class MyApp {
}
}

async loadController(filename: string) {
try {
const jsCode = await fs.readFile(filename, 'utf8')
const jsCodeFn = `'use strict'; return (() => { ${jsCode} })()`
this.controller = Function('app', jsCodeFn)(this)
} catch (error) {
console.error(error)
process.exit(1)
}
}

constructor() {
this.buffer = Buffer.alloc(0) // Dummy
this.u8buffer = new Uint8Array(this.buffer.buffer)
Expand Down Expand Up @@ -162,7 +175,7 @@ class MyApp {
}

private loop(elapsedTime: number): void {
this.nes.setPadStatus(0, this.pad)
this.nes.setPadStatus(0, this.pad | this.additionalPad)

let et = Math.min(elapsedTime, MAX_ELAPSED_TIME)
this.nes.runMilliseconds(et)
Expand All @@ -178,6 +191,10 @@ class MyApp {
this.prgBanks = this.prgBanksLast
this.prgBanksLast = tmp
}

this.additionalPad = 0
if (this.controller != null && this.controller.onVblank != null)
this.controller.onVblank()
}

private render(): void {
Expand Down Expand Up @@ -302,6 +319,7 @@ async function loadNesRomData(fileName: string): Promise<Uint8Array> {
async function main(argv: string[]) {
program
.option('-s, --silent', 'No audio')
.option('--controller <file>', 'Controller script file')
.parse(argv)
const opts = program.opts()
const args = program.args
Expand All @@ -313,6 +331,8 @@ async function main(argv: string[]) {
}

const myApp = new MyApp()
if (opts.controller != null)
myApp.loadController(opts.controller)
if (args.length > 0)
await MyApp.loadRom(myApp, args[0])
}
Expand Down

0 comments on commit dc5d53a

Please sign in to comment.