separate out running chip8 to goroutine

This commit is contained in:
Sid 2020-10-13 20:46:48 +01:00
parent b0797ff4af
commit 35c01939a0

View File

@ -24,6 +24,7 @@ var graphicsLock sync.Mutex
var keysLock sync.Mutex
var window js.Value
var keys [16]byte
var gameRunning = true
var keyMap = map[int]int{
88: 0, // x
@ -59,6 +60,48 @@ func keyEventHandle(event js.Value) {
}
}
func cpuCycle(cpu *chip8.Chip8, c chan int, i int) {
cpu.PerformCycle()
if cpu.DrawIsNeeded() {
drawNeeded = true
graphicsLock.Lock()
drawBuf = cpu.GetGraphicsBuffer()
graphicsLock.Unlock()
keysLock.Lock()
cpu.UpdateKeys(keys)
keysLock.Unlock()
}
if i > 7 {
cpu.TickTimers()
//println("here!")
}
c <- 1
}
func timeCycle(c chan int) {
time.Sleep(2000 * time.Microsecond)
c <- 0
}
func runGame(game []byte) {
cpu := chip8.NewCHIP8(game)
i := 0
for gameRunning {
c := make(chan int)
go timeCycle(c)
i ++
go cpuCycle(cpu, c, i)
if i > 7 {
i = 0
}
x, y := <-c, <-c
if x == 0 {
println("CPU RUNNING SLOW")
println(x, y)
}
}
}
func main() {
println("CHIP8 IS HERE!")
window = js.Global()
@ -79,36 +122,11 @@ func main() {
height = float64(cvs.Height())
width = float64(cvs.Width())
cpu := chip8.NewCHIP8(getSpaceInvaders())
cvs.Start(60, Render)
i := 0
for {
c := make(chan int)
go timeCycle(c)
cpu.PerformCycle()
if cpu.DrawIsNeeded() {
drawNeeded = true
graphicsLock.Lock()
drawBuf = cpu.GetGraphicsBuffer()
graphicsLock.Unlock()
keysLock.Lock()
cpu.UpdateKeys(keys)
keysLock.Unlock()
}
i++
if i > 7 {
cpu.TickTimers()
i = 0
//println("here!")
}
<-c
}
}
func timeCycle(c chan int) {
time.Sleep(2000 * time.Microsecond)
c <- 0
go runGame(getPong())
never_returns := make(chan int)
<-never_returns
}
func Render(gc *draw2dimg.GraphicContext) bool {