Skip to content

Commit

Permalink
fix: Avoid panic when "auto-binding" failed #330 (#336)
Browse files Browse the repository at this point in the history
* fix: Avoid panic when "auto-binding" failed #330

* Remove unused parameter
  • Loading branch information
qlli authored Sep 20, 2024
1 parent 5e8dc87 commit 2e78093
Showing 1 changed file with 32 additions and 6 deletions.
38 changes: 32 additions & 6 deletions game.go
Original file line number Diff line number Diff line change
Expand Up @@ -257,14 +257,18 @@ func Gopt_Game_Run(game Gamer, resource interface{}, gameConf ...*Config) {
name, val := getFieldPtrOrAlloc(v, i)
switch fld := val.(type) {
case *Sound:
media, err := g.loadSound(name)
if err != nil {
panic(err)
if g.canBindSound(name) {
media, err := g.loadSound(name)
if err != nil {
panic(err)
}
*fld = media
}
*fld = media
case Spriter:
if err := g.loadSprite(fld, name, v); err != nil {
panic(err)
if g.canBindSprite(name) {
if err := g.loadSprite(fld, name, v); err != nil {
panic(err)
}
}
// p.sprs[name] = fld (has been set by loadSprite)
}
Expand Down Expand Up @@ -354,6 +358,17 @@ func (p *Game) startLoad(fs spxfs.Dir, cfg *Config) {
p.windowHeight_ = cfg.Height
}

func (p *Game) canBindSprite(name string) bool {
// auto bind the sprite, if assets/sprites/{name}/index.json exists.
var baseDir = "sprites/" + name + "/"
f, err := p.fs.Open(baseDir + "index.json")
if err != nil {
return false
}
defer f.Close()
return true
}

func (p *Game) loadSprite(sprite Spriter, name string, gamer reflect.Value) error {
if debugLoad {
log.Println("==> LoadSprite", name)
Expand Down Expand Up @@ -1225,6 +1240,17 @@ func (p *Game) ClearSoundEffects() {

type Sound *soundConfig

func (p *Game) canBindSound(name string) bool {
// auto bind the sound, if assets/sounds/{name}/index.json exists.
prefix := "sounds/" + name
f, err := p.fs.Open(prefix + "/index.json")
if err != nil {
return false
}
defer f.Close()
return true
}

func (p *Game) loadSound(name string) (media Sound, err error) {
if media, ok := p.sounds.audios[name]; ok {
return media, nil
Expand Down

0 comments on commit 2e78093

Please sign in to comment.