Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Avoid panic when "auto-binding" failed #330 #336

Merged
merged 2 commits into from
Sep 20, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading