gpt4 book ai didi

java - 在偏好中存储音乐ON/OFF状态-LibGdx

转载 作者:行者123 更新时间:2023-12-02 12:56:14 25 4
gpt4 key购买 nike

我有这样的音乐按钮:

private void drawMusicButton() {
musicButton = new ImageButton(new TextureRegionDrawable(musicTexture1),new TextureRegionDrawable(musicTexture2), new TextureRegionDrawable(musicTexture2));
musicButton.setChecked(!game.menuMusicBool);
stage.addActor(musicButton);

musicButton.setPosition(UiConstants.MUSIC_X, UiConstants.MUSIC_Y, Align.bottom);
musicButton.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
if (!game.buttonClickSoundBool&&game.soundBool)
buttonClickSound.play();
if (game.menuMusicBool)
game.menuMusicBool = false;
else
game.menuMusicBool = true;
musicStateManager.saveMusicState();
}
});
}

最初 menuMusicBool 为 true。

public boolean menuMusicBool = true;

我想优先存储音乐开/关状态,以便在重新启动游戏时,我可以获取之前选择的状态。

我的偏好类别是这样的:

public class MusicStateManager {

private final Preferences prefs;
public final Mgame game;

private static final String MUSIC_STATE = "musicState";

public MusicStateManager(Mgame game){
this.game = game;
prefs = Gdx.app.getPreferences(Mgame.class.getName());
}

public void getPreferenceValues(){ }

public void reset(){ }

public void saveMusicState() {

prefs.putBoolean(MUSIC_STATE, game.menuMusicBool);
prefs.flush();
}

public void getMusicState() {
game.menuMusicBool = prefs.getBoolean(MUSIC_STATE);
}

getMusicState() 我在 render() 内部调用。

但优先考虑的是,值(value)没有得到正确存储。我无法在退出并重新启动游戏时保存之前的状态。

我在代码中做错了什么?

最佳答案

public class MusicStateManager {

private final Preferences prefs;
public final Mgame game;

private static final String PREF_NAME ="APP_NAME";
private static final String MUSIC_STATE = "musicState";

public MusicStateManager(Mgame game){
this.game = game;
prefs = Gdx.app.getPreferences(PREF_NAME);
game.menuMusicBool = prefs.getBoolean(MUSIC_STATE, true); // return true when key not found
}

public void saveMusicState(boolean musicState) {
game.menuMusicBool = musicState;
prefs.putBoolean(MUSIC_STATE, musicState);
prefs.flush();

// music state changed and saved, now need to start or stop music
if(game.menuMusicBool) // I supposed game having music object reference
game.music.play();
else
game.music.stop();
}

public boolean getMusicState() {
return prefs.getBoolean(MUSIC_STATE);
}

当你想播放音乐时,使用game.menuMusicBool作为标志

public void playMusic(Music music){

if(game.menuMusicBool && !music.isPlaying()){
music.play();
music.setLooping(true);
}
}

以及musicButton的内部监听器

musicButton.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
if (!game.buttonClickSoundBool&&game.soundBool)
buttonClickSound.play();
musicStateManager.saveMusicState(!game.menuMusicBool); // state inversed and saved in prefs
}
});

关于java - 在偏好中存储音乐ON/OFF状态-LibGdx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44427155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com