Android Studio游戏 - 节省高分

时间:2016-02-10 13:08:55

标签: android android-sharedpreferences

我想使用sharedPreferences保存游戏的高分,但是扩展gameScreen类不是活动吗?

public class HighscoreGameScreen extends GameScreen {
/**
 * Create a new game screen associated with the specified game instance
 *
 * @param name
 * @param game
 */
private TextView mTopScoreTextView;
private ScreenViewport mScreenViewport;
private LayerViewport mLayerViewport;
private Music mMusic;
private Paint highScorePaint = new Paint();
private Paint head = new Paint();
private Paint scores = new Paint();
private Paint paint;
private int newScore;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor preferenceEditor;
private static final int PREDERENCE_MODE_PRIVATE = 0;
private String highScoreString;




//    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the view for this fragment
    View view = inflater.inflate(R.layout.shared_preferences_fragment,
            container, false);

    // Extract and store the top score text view
    mTopScoreTextView = (TextView) view
            .findViewById(R.id.shared_preferences_textview);

    // Load and display the top scores
    loadTopScores();
    displayTopScores();

    // Setup the edit text to accept scores and update the top scores
    EditText editText = (EditText) view
            .findViewById(R.id.shared_preferences_edittext);
    editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView textView, int actionId,
                                      KeyEvent event) {

            // Extract and score and convert it into an integer

            int score = 0;
            try {
                score = Integer.parseInt(textView.getText().toString());
            } catch (NumberFormatException e) {
            }

            // Clear the entered text
            textView.setText("");

            // Update the top scores
            if (updateTopScores(score)) {
                // If we have a new top score then save and update
                //saveTopScores();
                displayTopScores();
            }

            return true;
        }
    });

    return view;
}




@TargetApi(Build.VERSION_CODES.KITKAT)
public HighscoreGameScreen(Game game, int hScore) {
    super("HighscoreGameScreen", game);
    newScore = hScore;

    // Create the screen viewport
    mScreenViewport = new ScreenViewport(0, 0, game.getScreenWidth(),
            game.getScreenHeight());

    // Create the layer viewport, taking into account the orientation
    // and aspect ratio of the screen.
    if (mScreenViewport.width > mScreenViewport.height)
        mLayerViewport = new LayerViewport(240.0f, 240.0f
                * mScreenViewport.height / mScreenViewport.width, 240,
                240.0f * mScreenViewport.height / mScreenViewport.width);
    else
        mLayerViewport = new LayerViewport(240.0f * mScreenViewport.height
                / mScreenViewport.width, 240.0f, 240.0f
                * mScreenViewport.height / mScreenViewport.width, 240);
/*
 * (non-Javadoc)
 *
 * @see android.app.Fragment#onCreateView(android.view.LayoutInflater,
 * android.view.ViewGroup, android.os.Bundle)
 */
    AssetStore assetManager = mGame.getAssetManager();
    assetManager.loadAndAddMusic("Background", "music/background.mp3");
    mMusic = mGame.getAssetManager().getMusic("Background");
    mMusic.play();
    mMusic.setLopping(true);
}

// ////////////////////////////////////////////////////////////////////
// Top Scores
// ////////////////////////////////////////////////////////////////////

/**
 * Number of top scores that will be stored
 */
private final int NUM_TOP_SCORES = 5;

/**
 * Array of top scores
 */

private int mTopScores[] = new int[NUM_TOP_SCORES];




/**
 * Display the top scores
 */

    mTopScores = mSharedPreferences.getInt(highScoreString,0);

    private void displayTopScores() {
        StringBuilder builder = new StringBuilder();

        for (int scoreIdx = 0; scoreIdx < NUM_TOP_SCORES; scoreIdx++) {
            builder.append("Top score ");
            builder.append((scoreIdx + 1));
            builder.append(" = ");
            builder.append(mTopScores[scoreIdx]);
            builder.append("\n");
        }


        mTopScoreTextView.setText(getString(R.string.high_score) + builder.toString());
    }


@Override
public void update(ElapsedTime elapsedTime) {


}
private boolean updateTopScores(int newScore) {

    boolean isChanged = false;

    int score = newScore, temp;
    for (int scoreIdx = 0; scoreIdx < NUM_TOP_SCORES; scoreIdx++) {
        if (score > mTopScores[scoreIdx]) {
            temp = mTopScores[scoreIdx];
            mTopScores[scoreIdx] = score;
            score = temp;

            isChanged = true;
        }
    }

    return isChanged;
}

@Override
public void draw(ElapsedTime elapsedTime, IGraphics2D graphics2D) {
    graphics2D.clear(Color.BLACK);
    highScorePaint.setColor(Color.WHITE);
    highScorePaint.setStyle(Paint.Style.FILL);
    //drawPaint(scorePaint);

    highScorePaint.setColor(Color.WHITE);
    highScorePaint.setTextSize(80);
    graphics2D.drawText("HighScores ", 0, 80, highScorePaint);

    head.setColor(Color.WHITE);
    head.setStyle(Paint.Style.FILL);
    //drawPaint(scorePaint);

    head.setColor(Color.WHITE);
    head.setTextSize(60);
    head.setTextAlign(head.getTextAlign());
    graphics2D.drawText("Name:              Scores: " + newScore, 100, 200, head);

}

@Override
protected void onPause(){
    super.onPause();
    mSharedPreferences.edit.putInt(highScoreString, highScore).commit();
}
}

0 个答案:

没有答案