From e4f0f805c565eda20a8eb2650eeb336c8d4879ae Mon Sep 17 00:00:00 2001 From: Caesar2011 Date: Mon, 24 Apr 2017 00:21:56 +0200 Subject: [PATCH] Game-service restructured; stable game flow; less waiting dialogs --- ...tion.java => NotInitializedException.java} | 10 +- .../it14/postgrachelor/LoginFragment.java | 4 +- .../it14/postgrachelor/MainActivity.java | 42 +- .../it14/postgrachelor/MainFragment.java | 17 +- .../postgrachelor/QuestionEndFragment.java | 9 +- .../it14/postgrachelor/QuestionFragment.java | 76 +- .../postgrachelor/Services/GameService.java | 834 +++++------------- .../Services/HighscoreService.java | 29 +- .../postgrachelor/Services/LoginService.java | 36 +- .../it14/postgrachelor/Types/Question.java | 10 +- .../{QuestionResult.java => Result.java} | 4 +- .../Types/{GameScores.java => Scores.java} | 9 +- .../it14/postgrachelor/Types/States.java | 25 + .../postgrachelor/Types/StoredNextEntity.java | 153 ++++ .../postgrachelor/Types/StoredObject.java | 67 +- .../postgrachelor/Types/StoredQuestion.java | 207 +++++ .../postgrachelor/Types/StoredScores.java | 40 + .../postgrachelor/Types/StoredStates.java | 48 + .../postgrachelor/Types/StoredTimings.java | 71 ++ .../it14/postgrachelor/Types/Timings.java | 22 +- .../postgrachelor/Utils/HighscoreAdapter.java | 3 +- .../postgrachelor/Utils/JsonRequestPG.java | 22 +- .../main/res/layout/fragment_main_game.xml | 4 +- 23 files changed, 983 insertions(+), 759 deletions(-) rename app/src/main/java/de/hwr_berlin/it14/postgrachelor/Exceptions/{NotInstantiatedException.java => NotInitializedException.java} (55%) rename app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/{QuestionResult.java => Result.java} (85%) rename app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/{GameScores.java => Scores.java} (67%) create mode 100644 app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/States.java create mode 100644 app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredNextEntity.java create mode 100644 app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredQuestion.java create mode 100644 app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredScores.java create mode 100644 app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredStates.java create mode 100644 app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredTimings.java diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Exceptions/NotInstantiatedException.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Exceptions/NotInitializedException.java similarity index 55% rename from app/src/main/java/de/hwr_berlin/it14/postgrachelor/Exceptions/NotInstantiatedException.java rename to app/src/main/java/de/hwr_berlin/it14/postgrachelor/Exceptions/NotInitializedException.java index 2c94e85..98663be 100644 --- a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Exceptions/NotInstantiatedException.java +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Exceptions/NotInitializedException.java @@ -5,22 +5,22 @@ package de.hwr_berlin.it14.postgrachelor.Exceptions; * Exception to indicate a not instantiated service */ -public class NotInstantiatedException extends Exception { +public class NotInitializedException extends Exception { private static final long serialVersionUID = 1997753363232807009L; - public NotInstantiatedException() { + public NotInitializedException() { super(); } - public NotInstantiatedException(String message) { + public NotInitializedException(String message) { super(message); } - public NotInstantiatedException(Throwable cause) { + public NotInitializedException(Throwable cause) { super(cause); } - public NotInstantiatedException(String message, Throwable cause) { + public NotInitializedException(String message, Throwable cause) { super(message, cause); } } diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/LoginFragment.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/LoginFragment.java index cbccace..1ed135c 100644 --- a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/LoginFragment.java +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/LoginFragment.java @@ -11,7 +11,7 @@ import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; -import de.hwr_berlin.it14.postgrachelor.Exceptions.NotInstantiatedException; +import de.hwr_berlin.it14.postgrachelor.Exceptions.NotInitializedException; import de.hwr_berlin.it14.postgrachelor.Services.LoginService; @@ -54,7 +54,7 @@ public class LoginFragment extends Fragment { try { LoginService.doLogin(login_edit.getText().toString()); - } catch (NotInstantiatedException e) { + } catch (NotInitializedException e) { e.printStackTrace(); } diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/MainActivity.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/MainActivity.java index 95d0bbd..b21fbf2 100644 --- a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/MainActivity.java +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/MainActivity.java @@ -15,12 +15,13 @@ import java.util.HashMap; import java.util.Set; import java.util.UUID; -import de.hwr_berlin.it14.postgrachelor.Exceptions.NotInstantiatedException; +import de.hwr_berlin.it14.postgrachelor.Exceptions.NotInitializedException; import de.hwr_berlin.it14.postgrachelor.Exceptions.NotLoggedInException; import de.hwr_berlin.it14.postgrachelor.Services.GameService; import de.hwr_berlin.it14.postgrachelor.Services.HighscoreService; import de.hwr_berlin.it14.postgrachelor.Services.LoginService; import de.hwr_berlin.it14.postgrachelor.Types.RequestActivityInterface; +import de.hwr_berlin.it14.postgrachelor.Types.StoredStates; public class MainActivity extends AppCompatActivity implements RequestActivityInterface { @@ -97,7 +98,7 @@ public class MainActivity extends AppCompatActivity implements RequestActivityIn if (savedInstanceState != null) { - this.fragmentState = savedInstanceState.getInt("selected fragment"); + this.selectFragment(savedInstanceState.getInt("selected fragment")); } } @@ -111,11 +112,6 @@ public class MainActivity extends AppCompatActivity implements RequestActivityIn public void onLoginEvent(String name, String uid) { Log.d("Activity fragment", "onLogin - name: " + name + " - uid: " + uid); that.selectFragment(FragmentState.MAIN); - try { - HighscoreService.updateHighscores(); - } catch (NotInstantiatedException | NotLoggedInException e) { - e.printStackTrace(); - } } @Override @@ -128,16 +124,11 @@ public class MainActivity extends AppCompatActivity implements RequestActivityIn @Override public void onGameStateChangeEvent(int previous, int state) { Log.d("Activity fragment", "onGameStateChange - previous: " + previous + " - state: " + state); - if (state == GameService.States.RUNNING || state == GameService.States.ON_HOLD_LOADING || state == GameService.States.ON_HOLD_RESULT) + if (state == StoredStates.RUNNING || state == StoredStates.ON_HOLD_LOADING || state == StoredStates.ON_HOLD_RESULT) that.selectFragment(FragmentState.QUESTION); - else if (previous == GameService.States.ON_HOLD_RESULT && state == GameService.States.END) { + else if (previous == StoredStates.ON_HOLD_RESULT && state == StoredStates.END) { that.selectFragment(FragmentState.QUESTION_END); - try { - HighscoreService.updateHighscores(); - } catch (NotInstantiatedException | NotLoggedInException e) { - e.printStackTrace(); - } - } else if (state == GameService.States.PAUSED || state == GameService.States.END) { + } else if (state == StoredStates.PAUSED || state == StoredStates.END) { that.selectFragment(FragmentState.MAIN); } } @@ -152,12 +143,10 @@ public class MainActivity extends AppCompatActivity implements RequestActivityIn @Override public void onBackPressed() { - //this.selectFragment(FragmentState.MAIN); boolean success; try { success = GameService.pauseGame(); - HighscoreService.updateHighscores(); - } catch (NotInstantiatedException | NotLoggedInException e) { + } catch (NotInitializedException e) { success = false; e.printStackTrace(); } @@ -165,6 +154,13 @@ public class MainActivity extends AppCompatActivity implements RequestActivityIn super.onBackPressed(); } + @Override + protected void onResume() { + super.onResume(); + Log.d(NAME, "Resuming"); + selectFragment(this.fragmentState); + } + @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. @@ -188,6 +184,7 @@ public class MainActivity extends AppCompatActivity implements RequestActivityIn } private void selectFragment(int item) { + boolean change = this.fragmentState != item; this.fragmentState = item; // Handle navigation view item clicks here. try { @@ -197,7 +194,7 @@ public class MainActivity extends AppCompatActivity implements RequestActivityIn } else if (isLoggedIn && (item == FragmentState.LOGIN)) { return; } - } catch (NotInstantiatedException e) { + } catch (NotInitializedException e) { e.printStackTrace(); return; } @@ -217,6 +214,13 @@ public class MainActivity extends AppCompatActivity implements RequestActivityIn fragmentTransaction.replace(R.id.relative_content, mainFragment, MainFragment.NAME); fragmentTransaction.commit(); } + if (change) { + try { + HighscoreService.updateHighscores(); + } catch (NotInitializedException | NotLoggedInException e) { + e.printStackTrace(); + } + } } else if (item == FragmentState.QUESTION_END) { QuestionEndFragment fragment = (QuestionEndFragment) myFragmentManager.findFragmentByTag(QuestionEndFragment.NAME); if (fragment == null) { diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/MainFragment.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/MainFragment.java index a4094a5..20a1fb0 100644 --- a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/MainFragment.java +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/MainFragment.java @@ -19,13 +19,14 @@ import org.json.JSONObject; import java.util.Iterator; import java.util.Locale; -import de.hwr_berlin.it14.postgrachelor.Exceptions.NotInstantiatedException; +import de.hwr_berlin.it14.postgrachelor.Exceptions.NotInitializedException; import de.hwr_berlin.it14.postgrachelor.Exceptions.NotLoggedInException; import de.hwr_berlin.it14.postgrachelor.Services.GameService; import de.hwr_berlin.it14.postgrachelor.Services.HighscoreService; import de.hwr_berlin.it14.postgrachelor.Services.LoginService; import de.hwr_berlin.it14.postgrachelor.Types.Highscores; import de.hwr_berlin.it14.postgrachelor.Types.HighscoresCategories; +import de.hwr_berlin.it14.postgrachelor.Types.StoredStates; import de.hwr_berlin.it14.postgrachelor.Utils.JsonRequestPG; /** @@ -76,7 +77,6 @@ public class MainFragment extends Fragment { public void onLoginEvent(String name, String uid) { TextView textView = (TextView) view.findViewById(R.id.fragment_main_status).findViewById(R.id.fragment_user_name); textView.setText(name); - Log.d(NAME, "onLogin", new Throwable()); } @Override @@ -133,7 +133,6 @@ public class MainFragment extends Fragment { textView.setText(String.format(Locale.getDefault(), "%1$d", category.getScore())); catProgress = (ProgressBar) categoryView.findViewById(R.id.progressBarCategory); - Log.d(NAME, "all: " + scores.getAll() + " - place: " + category.getPlace() + " - prog: " + (scores.getAll() - category.getPlace() + 1)); catProgress.setProgress(0); catProgress.setMax(scores.getAll()); catProgress.setProgress(scores.getAll() - category.getPlace() + 1); @@ -162,7 +161,7 @@ public class MainFragment extends Fragment { View userGameBackground = view.findViewById(R.id.fragment_main_game).findViewById(R.id.background); TextView userGameTextView = (TextView) view.findViewById(R.id.fragment_main_game).findViewById(R.id.title); ImageButton userStatusImage = (ImageButton) view.findViewById(R.id.fragment_main_game).findViewById(R.id.image_btn); - if (state == GameService.States.END || state == GameService.States.UNINITIALIZED) { + if (state == StoredStates.END || state == StoredStates.UNINITIALIZED) { userGameBackground.setBackgroundResource(android.R.color.holo_green_dark); userGameTextView.setText(R.string.start_test); userStatusImage.setImageResource(android.R.drawable.ic_media_play); @@ -181,14 +180,14 @@ public class MainFragment extends Fragment { @Override public void onClick(View v) { try { - int state = GameService.getState(); + int state = GameService.getState().getState(); Log.d(NAME, "Game click: "+state); - if (state == GameService.States.END || state == GameService.States.UNINITIALIZED) { + if (state == StoredStates.END || state == StoredStates.UNINITIALIZED) { GameService.startGame(); } else { GameService.resumeGame(); } - } catch (NotInstantiatedException | NotLoggedInException e) { + } catch (NotInitializedException | NotLoggedInException e) { e.printStackTrace(); } } @@ -217,11 +216,11 @@ public class MainFragment extends Fragment { } }); - } catch (NotInstantiatedException ignored) { + } catch (NotInitializedException ignored) { } catch (NotLoggedInException e) { try { LoginService.setLogout(15999, "Not logged in"); - } catch (NotInstantiatedException ignored) { + } catch (NotInitializedException ignored) { } } } diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/QuestionEndFragment.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/QuestionEndFragment.java index 779c525..e29975b 100644 --- a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/QuestionEndFragment.java +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/QuestionEndFragment.java @@ -11,9 +11,10 @@ import android.widget.TextView; import java.util.Locale; -import de.hwr_berlin.it14.postgrachelor.Exceptions.NotInstantiatedException; +import de.hwr_berlin.it14.postgrachelor.Exceptions.NotInitializedException; import de.hwr_berlin.it14.postgrachelor.Services.GameService; -import de.hwr_berlin.it14.postgrachelor.Types.GameScores; +import de.hwr_berlin.it14.postgrachelor.Types.Scores; +import de.hwr_berlin.it14.postgrachelor.Types.StoredScores; import de.hwr_berlin.it14.postgrachelor.Utils.Conversion; @@ -53,7 +54,7 @@ public class QuestionEndFragment extends Fragment { public void onClick(View v) { try { GameService.endGame(); - } catch (NotInstantiatedException e) { + } catch (NotInitializedException e) { e.printStackTrace(); } } @@ -61,7 +62,7 @@ public class QuestionEndFragment extends Fragment { GameService.addGameEndEventListener(NAME, new GameService.OnGameEndEventListener() { @Override - public void onGameEndEvent(GameScores scores) { + public void onGameEndEvent(Scores scores) { Log.d(NAME, "onGameEndEvent" + scores); if (scores != null) { TextView textView = (TextView) view.findViewById(R.id.textViewScore); diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/QuestionFragment.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/QuestionFragment.java index fe417f1..1d1e66e 100644 --- a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/QuestionFragment.java +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/QuestionFragment.java @@ -17,11 +17,13 @@ import android.widget.TextView; import java.util.Locale; import de.hwr_berlin.it14.postgrachelor.Exceptions.NoCurrentQuestionException; -import de.hwr_berlin.it14.postgrachelor.Exceptions.NotInstantiatedException; +import de.hwr_berlin.it14.postgrachelor.Exceptions.NotInitializedException; import de.hwr_berlin.it14.postgrachelor.Exceptions.NotLoggedInException; import de.hwr_berlin.it14.postgrachelor.Services.GameService; import de.hwr_berlin.it14.postgrachelor.Types.Question; -import de.hwr_berlin.it14.postgrachelor.Types.QuestionResult; +import de.hwr_berlin.it14.postgrachelor.Types.Result; +import de.hwr_berlin.it14.postgrachelor.Types.StoredStates; +import de.hwr_berlin.it14.postgrachelor.Types.StoredTimings; import de.hwr_berlin.it14.postgrachelor.Types.Timings; import de.hwr_berlin.it14.postgrachelor.Utils.Conversion; import de.hwr_berlin.it14.postgrachelor.Utils.ReverseInterpolator; @@ -79,7 +81,7 @@ public class QuestionFragment extends Fragment { if (GameService.isNextNeeded()) try { GameService.runNext(); - } catch (NotInstantiatedException e) { + } catch (NotInitializedException e) { e.printStackTrace(); } } @@ -90,26 +92,28 @@ public class QuestionFragment extends Fragment { questionAnswerViews[i].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - if (GameService.isNextNeeded()) { - try { - GameService.runNext(); - } catch (NotInstantiatedException e) { - e.printStackTrace(); - } - } else { - try { - if (GameService.getState() != GameService.States.ON_HOLD_RESULT) + if (GameService.isNextNeeded()) { + try { + GameService.runNext(); + } catch (NotInitializedException e) { + e.printStackTrace(); + } + } else if (GameService.getState().getState() != StoredStates.ON_HOLD_RESULT) { + try { GameService.answer((int) v.getTag()); - } catch (NotInstantiatedException | NotLoggedInException | NoCurrentQuestionException e) { - e.printStackTrace(); + } catch (NotInitializedException | NotLoggedInException | NoCurrentQuestionException e) { + e.printStackTrace(); + } + } else { + GameService.haltGame(); } } - } }); } Context context = getActivity().getApplicationContext(); - final int colorBgClicked = ContextCompat.getColor(context, android.R.color.holo_red_dark); + final int colorBgFalse = ContextCompat.getColor(context, android.R.color.holo_red_dark); + final int colorBgClicked = ContextCompat.getColor(context, android.R.color.holo_orange_dark); final int colorBg = ContextCompat.getColor(context, android.R.color.holo_green_dark); final int colorText = ContextCompat.getColor(context, android.R.color.black); final Animation animation = AnimationUtils.loadAnimation(context, R.anim.scale_up); @@ -123,10 +127,11 @@ public class QuestionFragment extends Fragment { } } }); - GameService.addNextQuestionEventListener(NAME, new GameService.OnNextQuestionEventListener() { + GameService.addQuestionUpdateEventListener(NAME, new GameService.OnQuestionUpdateEventListener() { @Override - public void onNextQuestionEvent(Question question) { - Log.d(NAME, "onNextQuestionEvent - question: " + question); + public void onQuestionUpdateEvent(Question question, int answer, Result result) { + Log.d(NAME, "onQuestionUpdateEvent - question: " + question); + for (int i = 0; i < 4; i++) { questionAnswerViews[i].setBackgroundColor( ContextCompat.getColor(view.getContext(), R.color.colorPrimary) @@ -135,6 +140,7 @@ public class QuestionFragment extends Fragment { ContextCompat.getColor(view.getContext(), android.R.color.white) ); } + if (question != null) { questionTitleView.setText(question.getQuestion()); questionCategoryView.setText(view.getContext().getResources().getString(R.string.category, question.getCategory())); @@ -148,28 +154,16 @@ public class QuestionFragment extends Fragment { questionAnswerViews[i].setText(""); } } - } - }); - GameService.addResultEventListener(NAME, new GameService.OnResultEventListener() { - @Override - public void onResultEvent(QuestionResult result) { - Log.d(NAME, "onResultEvent - result: " + result); - if (result != null) { - int answerID; - try { - answerID = GameService.getAnswer(); - } catch (NotInstantiatedException e) { - answerID = -1; - e.printStackTrace(); - } - Log.d(NAME, "onResultEvent - answerID: " + answerID); - if (answerID != -1) { - questionAnswerViews[answerID].setBackgroundColor(colorBgClicked); - questionAnswerViews[result.getCorrectPos()].setBackgroundColor(colorBg); - questionAnswerViews[result.getCorrectPos()].setTextColor(colorText); - } + if (answer != -1 && result != null) { + questionAnswerViews[answer].setBackgroundColor(colorBgFalse); + } else if (answer != -1) { + questionAnswerViews[answer].setBackgroundColor(colorBgClicked); + } + if (result != null && result.getCorrectPos()>=0 && result.getCorrectPos()<=3) { + questionAnswerViews[result.getCorrectPos()].setBackgroundColor(colorBg); + questionAnswerViews[result.getCorrectPos()].setTextColor(colorText); totalView.setText(Conversion.intToStr(result.getTotal())); scoreView.setText(Conversion.intToStr(result.getScore())); @@ -180,14 +174,16 @@ public class QuestionFragment extends Fragment { } } }); + GameService.addGameStateChangeEventListener(NAME, new GameService.OnGameStateChangeEventListener() { @Override public void onGameStateChangeEvent(int previous, int state) { Log.d(NAME, Conversion.intToStr(previous, 5)+Conversion.intToStr(state,5)); - if (previous != GameService.States.ON_HOLD_RESULT && state == GameService.States.RUNNING) + if (previous != StoredStates.ON_HOLD_RESULT && state == StoredStates.RUNNING) totalView.setText(R.string._0); } }); + return view; } } diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Services/GameService.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Services/GameService.java index 70c64ec..7f0ab22 100644 --- a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Services/GameService.java +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Services/GameService.java @@ -6,20 +6,24 @@ import android.content.SharedPreferences; import android.util.Log; import org.json.JSONArray; -import org.json.JSONException; import org.json.JSONObject; -import java.util.ArrayList; import java.util.HashMap; import java.util.Timer; import java.util.TimerTask; import de.hwr_berlin.it14.postgrachelor.Exceptions.NoCurrentQuestionException; -import de.hwr_berlin.it14.postgrachelor.Exceptions.NotInstantiatedException; +import de.hwr_berlin.it14.postgrachelor.Exceptions.NotInitializedException; import de.hwr_berlin.it14.postgrachelor.Exceptions.NotLoggedInException; -import de.hwr_berlin.it14.postgrachelor.Types.GameScores; +import de.hwr_berlin.it14.postgrachelor.Types.Scores; +import de.hwr_berlin.it14.postgrachelor.Types.States; +import de.hwr_berlin.it14.postgrachelor.Types.StoredNextEntity; +import de.hwr_berlin.it14.postgrachelor.Types.StoredQuestion; +import de.hwr_berlin.it14.postgrachelor.Types.StoredScores; import de.hwr_berlin.it14.postgrachelor.Types.Question; -import de.hwr_berlin.it14.postgrachelor.Types.QuestionResult; +import de.hwr_berlin.it14.postgrachelor.Types.Result; +import de.hwr_berlin.it14.postgrachelor.Types.StoredStates; +import de.hwr_berlin.it14.postgrachelor.Types.StoredTimings; import de.hwr_berlin.it14.postgrachelor.Types.Timings; import de.hwr_berlin.it14.postgrachelor.Utils.Conversion; import de.hwr_berlin.it14.postgrachelor.Utils.JsonRequestPG; @@ -31,58 +35,45 @@ import de.hwr_berlin.it14.postgrachelor.Utils.JsonRequestPG; public class GameService { private static final int GAME_TICK_INTERVAL = 100; - private static final int NEXT_QUESTION_DELAY = 1250; private static final int QUESTION_COUNT = 10; private static final String NAME = "SERVICE_GAME"; - - - private static long startTime; - private static long endTime; - private static int answer = -1; - private static Timer timer; - private static JSONObject data = null; - - public static final class States { - private States() {} - public static final int UNINITIALIZED = 1; - public static final int END = 2; - public static final int ON_HOLD_LOADING = 4; - public static final int ON_HOLD_RESULT = 8; - public static final int RUNNING = 16; - public static final int PAUSED = 32; - } - private static final String PREFS_NAME = "PrefsGame"; - private static SharedPreferences settings = null; + + + private static StoredStates states = null; + private static StoredTimings timings = null; + private static StoredScores scores = null; + private static StoredNextEntity next = null; + private static StoredQuestion question = null; + private static boolean initialized = false; @SuppressLint("StaticFieldLeak") private static Activity activity = null; + private static SharedPreferences settings = null; + private static Timer timer = null; private static final HashMap gameStateChangeEventListeners = new HashMap<>(); - private static final HashMap nextQuestionEventListeners = new HashMap<>(); - private static final HashMap resultEventListeners = new HashMap<>(); + private static final HashMap questionUpdateEventListeners = new HashMap<>(); private static final HashMap gameEndEventListeners = new HashMap<>(); private static final HashMap gameTickEventListeners = new HashMap<>(); - private static int state = States.UNINITIALIZED; - private static Question question = null; - private static QuestionResult result = null; - private static GameScores scores = null; + + public static void haltGame() { + Log.d(NAME, "Halt game!", new Throwable("HAlt game!")); + try { + GameService.endGame(); + } catch (NotInitializedException e) { + e.printStackTrace(); + } + } public interface OnGameStateChangeEventListener { void onGameStateChangeEvent(int previous, int state); } - - public interface OnNextQuestionEventListener { - void onNextQuestionEvent(Question question); + public interface OnQuestionUpdateEventListener { + void onQuestionUpdateEvent(Question question, int answer, Result result); } - - public interface OnResultEventListener { - void onResultEvent(QuestionResult result); - } - public interface OnGameEndEventListener { - void onGameEndEvent(GameScores scores); + void onGameEndEvent(Scores scores); } - public interface OnTickEventListener { void onTickEvent(Timings timings); } @@ -93,104 +84,71 @@ public class GameService { GameService.activity = activity; GameService.settings = activity.getSharedPreferences(GameService.PREFS_NAME, 0); GameService.initialized = true; - try { - GameService.data = GameService.getNeededNext(); - } catch (NotInstantiatedException e) { - e.printStackTrace(); - } + + GameService.states = new StoredStates(GameService.settings, ""); + GameService.timings = new StoredTimings(GameService.settings, ""); + GameService.scores = new StoredScores(GameService.settings, ""); + GameService.next = new StoredNextEntity(GameService.settings, ""); + GameService.question = new StoredQuestion(GameService.settings, ""); + + if (GameService.getState().getState()==StoredStates.RUNNING) + GameService.startTimer(); emitTickEvent(); - emitNextQuestionEvent(); + emitQuestionUpdateEvent(); emitGameEndEvent(); - emitResultEvent(); emitGameStateChangeEvent(); } - public static void addGameStateChangeEventListener(String key, OnGameStateChangeEventListener onGameStateChangeEventListener) { - gameStateChangeEventListeners.put(key, onGameStateChangeEventListener); - if (GameService.initialized) - onGameStateChangeEventListener.onGameStateChangeEvent(-2, GameService.getStateSave()); + public static void addGameStateChangeEventListener(String key, OnGameStateChangeEventListener listener) { + gameStateChangeEventListeners.put(key, listener); + if (GameService.initialized) { + States states = GameService.getState(); + listener.onGameStateChangeEvent(states.getPrevious(), states.getState()); + } } private static void emitGameStateChangeEvent() { - for (OnGameStateChangeEventListener listener: gameStateChangeEventListeners.values()) { - listener.onGameStateChangeEvent(-1, GameService.getStateSave()); + if (GameService.initialized) { + States states = GameService.getState(); + for (OnGameStateChangeEventListener listener: gameStateChangeEventListeners.values()) { + listener.onGameStateChangeEvent(states.getPrevious(), states.getState()); + } } } - private static void emitGameStateChangeEvent(int previousState) { - for (OnGameStateChangeEventListener listener: gameStateChangeEventListeners.values()) { - listener.onGameStateChangeEvent(previousState, GameService.getStateSave()); - } - } - - @SuppressWarnings("SameParameterValue") - public static void addNextQuestionEventListener(String key, OnNextQuestionEventListener onNextQuestionEventListener) { - Log.d("GameService Fragment", "addNextQuestionEventListener"); - nextQuestionEventListeners.put(key, onNextQuestionEventListener); + public static void addQuestionUpdateEventListener(String key, OnQuestionUpdateEventListener listener) { + questionUpdateEventListeners.put(key, listener); if (GameService.initialized) - onNextQuestionEventListener.onNextQuestionEvent(GameService.getQuestionSave()); + listener.onQuestionUpdateEvent(GameService.getQuestion(), GameService.getAnswer(), GameService.getResult()); } - private static void emitNextQuestionEvent() { - for (OnNextQuestionEventListener listener: nextQuestionEventListeners.values()) { - listener.onNextQuestionEvent(GameService.getQuestionSave()); - } - } - - @SuppressWarnings("SameParameterValue") - public static void addResultEventListener(String key, OnResultEventListener onResultEventListener) { - resultEventListeners.put(key, onResultEventListener); - if (GameService.initialized) - onResultEventListener.onResultEvent(GameService.getResultSave()); - } - - private static void emitResultEvent() { - for (OnResultEventListener listener: resultEventListeners.values()) { - listener.onResultEvent(GameService.getResultSave()); + private static void emitQuestionUpdateEvent() { + for (OnQuestionUpdateEventListener listener: questionUpdateEventListeners.values()) { + listener.onQuestionUpdateEvent(GameService.getQuestion(), GameService.getAnswer(), GameService.getResult()); } } public static void addGameEndEventListener(String key, OnGameEndEventListener onGameEndEventListener) { gameEndEventListeners.put(key, onGameEndEventListener); if (GameService.initialized) - onGameEndEventListener.onGameEndEvent(GameService.getScoresSave()); + onGameEndEventListener.onGameEndEvent(GameService.getScores()); } private static void emitGameEndEvent() { for (OnGameEndEventListener listener: gameEndEventListeners.values()) { - listener.onGameEndEvent(GameService.getScoresSave()); + listener.onGameEndEvent(GameService.getScores()); } } - @SuppressWarnings("SameParameterValue") public static void addTickEventListener(String key, OnTickEventListener onTickEventListener) { gameTickEventListeners.put(key, onTickEventListener); - onTickEventListener.onTickEvent(GameService.getTimingsSave()); - } - - private static Timings getTimingsSave() { - try { - return GameService.getTimings(); - } catch (NotInstantiatedException e) { - e.printStackTrace(); - return null; - } - } - - private static Timings getTimings() throws NotInstantiatedException { - long timeDiff = GameService.getEndTime(); - if (timeDiff != 0) - timeDiff = timeDiff-GameService.getStartTime(); - else - timeDiff = System.currentTimeMillis() - GameService.getStartTime(); - - return new Timings(timeDiff); + onTickEventListener.onTickEvent(GameService.getTimings()); } private static void emitTickEvent() { for (OnTickEventListener listener: gameTickEventListeners.values()) { - listener.onTickEvent(GameService.getTimingsSave()); + listener.onTickEvent(GameService.getTimings()); } } @@ -211,237 +169,183 @@ public class GameService { } private static void stopTimer() { - if (GameService.timer != null) + if (GameService.timer != null) { GameService.timer.cancel(); GameService.timer = null; - } - - private static GameScores getScores() throws NotInstantiatedException { - if (GameService.scores == null) { - if (!GameService.initialized) - throw new NotInstantiatedException(); - GameScores scores; - if (GameService.settings.contains("gameScore")) { - scores = new GameScores( - GameService.settings.getInt("gameScore", 0), - GameService.settings.getInt("gameTime", 0) - ); - } else { - scores = null; - } - GameService.scores = scores; - } - return GameService.scores; - } - - private static GameScores getScoresSave() { - try { - return GameService.getScores(); - } catch (NotInstantiatedException e) { - e.printStackTrace(); - return null; } } - public static int getState() throws NotInstantiatedException { - if (GameService.state == GameService.States.UNINITIALIZED) { - if (!GameService.initialized) - throw new NotInstantiatedException(); - int state = GameService.settings.getInt("gameState", GameService.States.UNINITIALIZED); - if (state == GameService.States.UNINITIALIZED) { - state = GameService.States.END; - SharedPreferences.Editor editor = GameService.settings.edit(); - editor.putInt("gameState", state); - editor.apply(); - } - GameService.state = state; - } - return GameService.state; + // GETTER + + private static Timings getTimings() { + return GameService.timings.get(); } - private static int getStateSave() { - try { - return GameService.getState(); - } catch (NotInstantiatedException e) { - e.printStackTrace(); - return States.UNINITIALIZED; - } + private static Scores getScores() { + return GameService.scores.get(); } - private static Question getQuestion() throws NotInstantiatedException { - if (GameService.question == null) { - if (!GameService.initialized) - throw new NotInstantiatedException(); - Question question; - if (GameService.settings.contains("question")) { - question = new Question( - GameService.settings.getString("questionCategory", ""), - GameService.settings.getInt("questionCategoryID", 0), - GameService.settings.getString("question", ""), - new String [] { - GameService.settings.getString("answer0", ""), - GameService.settings.getString("answer1", ""), - GameService.settings.getString("answer2", ""), - GameService.settings.getString("answer3", "") - } - ); - } else { - question = null; - } - GameService.question = question; - } - return GameService.question; + public static States getState() { + if (!GameService.initialized) + return new States(StoredStates.END, StoredStates.END); + return GameService.states.get(); } - private static Question getQuestionSave() { - try { - return GameService.getQuestion(); - } catch (NotInstantiatedException e) { - e.printStackTrace(); - return null; - } + private static Question getQuestion() { + return GameService.question.getQuestion(); } - private static QuestionResult getResult() throws NotInstantiatedException { - Log.d(NAME, "getResult start "+GameService.result); - if (GameService.result == null) { - if (!GameService.initialized) - throw new NotInstantiatedException(); - QuestionResult result; - if (GameService.settings.contains("resultCorrect")) { - Log.d(NAME, "getResult contains"); - result = new QuestionResult( - GameService.settings.getBoolean("resultCorrect", true), - GameService.settings.getInt("resultScore", 0), - GameService.settings.getInt("resultPos", 0), - GameService.settings.getInt("resultTotal", 0) - ); - } else { - Log.d(NAME, "getResult nulliiii"); - result = null; - } - GameService.result = result; - } - Log.d(NAME, "getResult end "+GameService.result); - return GameService.result; + private static Result getResult() { + return GameService.question.getResult(); } - private static QuestionResult getResultSave() { - try { - return GameService.getResult(); - } catch (NotInstantiatedException e) { - e.printStackTrace(); - return null; - } + private static int getAnswer() { + return GameService.question.getAnswer(); } - private static long getStartTime() throws NotInstantiatedException { - if (GameService.startTime == 0) { - if (!GameService.initialized) - throw new NotInstantiatedException(); - GameService.startTime = GameService.settings.getLong("startTime", 0); - } - return GameService.startTime; + private static Question getNeededNext() { + return GameService.next.getNext(); } - private static long getEndTime() throws NotInstantiatedException { - Log.d(NAME, "getEndTime begin"+GameService.endTime); - if (GameService.endTime == 0) { - if (!GameService.initialized) - throw new NotInstantiatedException(); - GameService.endTime = GameService.settings.getLong("endTime", 0); - } - Log.d(NAME, "getEndTime end"+GameService.endTime); - return GameService.endTime; + private static Scores getNeededEnd() { + return GameService.next.getEnd(); } - private static int getAnswer(int id) throws NotInstantiatedException { - if (GameService.answer == -1) { - if (!GameService.initialized) - throw new NotInstantiatedException(); - GameService.answer = GameService.settings.getInt("answer", id); - } - return GameService.answer; + // SETTER + + private static void startTimings() { + GameService.timings.start(); } - public static int getAnswer() throws NotInstantiatedException { - return GameService.getAnswer(-1); - + private static void stopTimings() { + GameService.timings.stop(); } - public static boolean pauseGame() throws NotInstantiatedException { - int state = GameService.getState(); - if (state == States.RUNNING || state == States.ON_HOLD_LOADING || state == States.ON_HOLD_RESULT) { - GameService.setState(States.PAUSED); + private static void setNeededNext(Question question) { + GameService.next.setNext(question); + } + + private static void setNeededEnd(Scores scores) { + GameService.next.setEnd(scores); + } + + // UNSETTER + + private static void resetTimings() { + GameService.timings.reset(); + } + + private static void unsetQuestion() { + GameService.question.remove(); + } + + private static void unsetScores() { + GameService.scores.remove(); + } + + private static void unsetNext() { + GameService.next.remove(); + } + + //END + + public static boolean pauseGame() throws NotInitializedException { + if (!GameService.initialized) + throw new NotInitializedException(); + + int state = GameService.getState().getState(); + if (state == StoredStates.RUNNING || state == StoredStates.ON_HOLD_LOADING || state == StoredStates.ON_HOLD_RESULT) { + GameService.setState(StoredStates.PAUSED); return true; } else { return false; } } - public static void resumeGame() throws NotInstantiatedException { - if (GameService.isNextNeeded()) { - GameService.setState(States.ON_HOLD_RESULT); - } else if (GameService.getAnswer() != -1) { - GameService.setState(States.ON_HOLD_LOADING); + public static boolean resumeGame() throws NotInitializedException { + if (!GameService.initialized) + throw new NotInitializedException(); + + int state = GameService.getState().getState(); + if (state == StoredStates.PAUSED) { + GameService.setState(GameService.getState().getPrevious()); + return true; } else { - GameService.setState(States.RUNNING); + return false; } } - public static void endGame() throws NotInstantiatedException { - GameService.setState(States.END); - GameService.unsetEndTime(); - GameService.unsetStartTime(); + public static void endGame() throws NotInitializedException { + if (!GameService.initialized) + throw new NotInitializedException(); + + GameService.setState(StoredStates.END); + GameService.unsetQuestion(); GameService.unsetScores(); + GameService.unsetNext(); + GameService.resetTimings(); + } - public static void answer(int id) throws NotInstantiatedException, NotLoggedInException, NoCurrentQuestionException { + public static void answer(int id) throws NotInitializedException, NotLoggedInException, NoCurrentQuestionException { + if (!GameService.initialized) + throw new NotInitializedException(); if (GameService.isNextNeeded()) throw new IllegalStateException(); - if (!GameService.initialized) - throw new NotInstantiatedException(); - final int state = GameService.getState(); - long time; - if (state == States.ON_HOLD_LOADING) { - long end = GameService.getEndTime(); - long start = GameService.getStartTime(); - time = end - start; - id = GameService.getAnswer(id); - } else if (state == States.RUNNING) { - GameService.setState(States.ON_HOLD_LOADING); - long end = System.currentTimeMillis(); - long start = GameService.getStartTime(); - GameService.setEndTime(end); - time = end - start; - GameService.setAnswer(id); - } else { - throw new NoCurrentQuestionException(); + GameService.stopTimings(); + GameService.setAnswer(id); + GameService.setState(StoredStates.ON_HOLD_LOADING); + + if (GameService.getQuestion()==null || GameService.getAnswer()==-1) { + GameService.haltGame(); + return; } + final String currentToken = GameService.getQuestion().getToken(); + HashMap params = new HashMap<>(); - String uid; - uid = LoginService.getLoginUID(); - params.put("answer", Integer.toString(id)); - params.put("uid", uid); - params.put("time", Long.toString(time)); + params.put("answer", Conversion.intToStr(GameService.getAnswer())); + params.put("uid", LoginService.getLoginUID()); + params.put("token", currentToken); + params.put("time", String.valueOf(GameService.getTimings().getTimeDiff())); Log.d("GameServiceFragment", "answer/processFinish - before"); - JsonRequestPG requester = new JsonRequestPG("answer.php", params, GameService.activity, new JsonRequestPG.AsyncResponse() { + JsonRequestPG requester = new JsonRequestPG("answer.php", params, /*activity*/null, new JsonRequestPG.AsyncResponse() { @Override public void processFinish(final JSONObject data) { Log.d("GameServiceFragment", "answer/processFinish - " + data.toString()); JSONObject data_result = data.optJSONObject("results"); - QuestionResult result = new QuestionResult( + if (data_result == null) { + if (GameService.getState().getState()==StoredStates.ON_HOLD_LOADING && GameService.getQuestion()!=null && GameService.getQuestion().getToken().equals(currentToken)) + try { + GameService.endGame(); + } catch (NotInitializedException e) { + e.printStackTrace(); + } + return; // token already used -> ignore + } + + Result result = new Result( data_result.optBoolean("correct", false), data_result.optInt("score", 0), data_result.optInt("correctPos", 0), data_result.optInt("total", 0) ); - GameService.setResultSave(result); - GameService.setNeededNextSave(data); - GameService.setAnswerSave(-1); - GameService.setStateSave(States.ON_HOLD_RESULT); + GameService.setResult(result); + + JSONObject data_next = data.optJSONObject("next"); + if (data_next != null) { + Question question = parseQuestion(data_next); + GameService.setNeededNext(question); + } + + JSONObject data_end = data.optJSONObject("end"); + if (data_end != null) { + Scores scores = parseScores(data_end); + GameService.setNeededEnd(scores); + } + + GameService.setState(StoredStates.ON_HOLD_RESULT); } @Override @@ -450,7 +354,7 @@ public class GameService { if (status==13104 || status==13102) try { GameService.endGame(); - } catch (NotInstantiatedException e) { + } catch (NotInitializedException e) { e.printStackTrace(); } } @@ -458,11 +362,15 @@ public class GameService { requester.execute(); } - public static void startGame() throws NotInstantiatedException, NotLoggedInException { + public static void startGame() throws NotInitializedException, NotLoggedInException { if (!GameService.initialized) - throw new NotInstantiatedException(); + throw new NotInitializedException(); + + GameService.unsetNext(); + GameService.unsetScores(); + GameService.unsetQuestion(); + GameService.resetTimings(); - GameService.setNeededNext(null); HashMap params = new HashMap<>(); String uid; uid = LoginService.getLoginUID(); @@ -473,23 +381,20 @@ public class GameService { public void processFinish(JSONObject data) { JSONObject data_next = data.optJSONObject("next"); if (data_next != null) { - GameService.setStateSave(States.RUNNING); - GameService.setStartTimeSave(System.currentTimeMillis()); - GameService.unsetEndTimeSave(); - GameService.unsetScoresSave(); - GameService.setQuestionSave(GameService.parseQuestion(data_next)); + Question question = GameService.parseQuestion(data_next); + GameService.setQuestion(question); } else { - GameService.setStateSave(States.END); + GameService.setState(StoredStates.END); } } @Override public void processError(int status, String message) { - GameService.setStateSave(States.END); + GameService.setState(StoredStates.END); if (status==12104) { // user uid not found try { LoginService.setLogout(status, message); - } catch (NotInstantiatedException e) { + } catch (NotInitializedException e) { e.printStackTrace(); } } @@ -498,324 +403,60 @@ public class GameService { requester.execute(); } - private static void setNeededNext(JSONObject data) throws NotInstantiatedException { - GameService.data = data; - if (!GameService.initialized) - throw new NotInstantiatedException(); - SharedPreferences.Editor editor = GameService.settings.edit(); - if (data!=null && data.has("next")) { - data = data.optJSONObject("next"); - JSONArray array = data.optJSONArray("answers"); - editor.putString("nextCategoryName", data.optString("categoryName", "")); - editor.putInt("nextCategoryID", data.optInt("categoryID", 0)); - editor.putString("nextQuestion", data.optString("question", "")); - editor.putString("nextAnswers0", array.optString(0, "")); - editor.putString("nextAnswers1", array.optString(1, "")); - editor.putString("nextAnswers2", array.optString(2, "")); - editor.putString("nextAnswers3", array.optString(3, "")); - } else { - editor.remove("nextCategoryName"); - editor.remove("nextCategoryID"); - editor.remove("nextQuestion"); - editor.remove("nextAnswers0"); - editor.remove("nextAnswers1"); - editor.remove("nextAnswers2"); - editor.remove("nextAnswers3"); - } - if (data!=null && data.has("end")) { - data = data.optJSONObject("end"); - editor.putInt("endScore", data.optInt("score", 0)); - editor.putLong("endTime", data.optLong("time", 0)); - } else { - editor.remove("endScore"); - editor.remove("endTime"); - } - editor.apply(); - } - - private static void setNeededNextSave(JSONObject data) { - try { - GameService.setNeededNext(data); - } catch (NotInstantiatedException e) { - e.printStackTrace(); - } - } - - private static JSONObject getNeededNext() throws NotInstantiatedException { - if (GameService.data == null) { - if (!GameService.initialized) - throw new NotInstantiatedException(); - JSONObject data; - if (GameService.settings.contains("nextCategoryName")) { - data = new JSONObject(); - try { - data.put("categoryName", GameService.settings.getString("nextCategoryName", "")); - data.put("categoryID", GameService.settings.getInt("nextCategoryID", 0)); - data.put("question", GameService.settings.getString("nextQuestion", "")); - ArrayList list = new ArrayList<>(); - list.add(GameService.settings.getString("nextAnswers0", "")); - list.add(GameService.settings.getString("nextAnswers1", "")); - list.add(GameService.settings.getString("nextAnswers2", "")); - list.add(GameService.settings.getString("nextAnswers3", "")); - data.put("answers", new JSONArray(list)); - data = (new JSONObject()).put("next", data); - } catch (JSONException e) { - data = null; - e.printStackTrace(); - } - } else if (GameService.settings.contains("endScore")) { - data = new JSONObject(); - try { - data.put("score", GameService.settings.getInt("endScore", 0)); - data.put("time", GameService.settings.getLong("endTime", 0)); - data = (new JSONObject()).put("end", data); - } catch (JSONException e) { - data = null; - e.printStackTrace(); - } - } else { - data = null; - } - GameService.data = data; - } - return GameService.data; - } - public static boolean isNextNeeded() { - return GameService.data != null; + return GameService.initialized && GameService.next.isLoaded(); } - public static void runNext() throws IllegalStateException, NotInstantiatedException { - JSONObject data = GameService.getNeededNext(); - if (data == null) - throw new IllegalStateException(); - if (data.has("next")) { - JSONObject data_next = data.optJSONObject("next"); - GameService.setQuestionSave(GameService.parseQuestion(data_next)); - GameService.setStartTimeSave(System.currentTimeMillis()); - GameService.unsetEndTimeSave(); - GameService.setStateSave(States.RUNNING); - } else { - JSONObject data_end = data.optJSONObject("end"); - GameService.setScoresSave(GameService.parseScores(data_end)); - GameService.setStateSave(States.END); - GameService.unsetStartTimeSave(); - GameService.unsetEndTimeSave(); - GameService.setResultSave(null); - } - GameService.setNeededNext(null); - } + public static void runNext() throws IllegalStateException, NotInitializedException { + if (!GameService.initialized) + throw new NotInitializedException(); + if (!GameService.isNextNeeded()) + GameService.endGame(); - private static void setQuestion(Question question) throws NotInstantiatedException { - if (!initialized) - throw new NotInstantiatedException(); - GameService.question = question; - SharedPreferences.Editor editor = GameService.settings.edit(); + Question question = GameService.getNeededNext(); + Scores scores = GameService.getNeededEnd(); if (question != null) { - editor.putString("questionCategory", question.getCategory()); - editor.putInt("questionCategoryID", question.getCategoryID()); - editor.putString("question", question.getQuestion()); - String[] answers = question.getAnswers(); - editor.putString("answer0", answers[0]); - editor.putString("answer1", answers[1]); - editor.putString("answer2", answers[2]); - editor.putString("answer3", answers[3]); - } else { - editor.remove("questionCategory"); - editor.remove("questionCategoryID"); - editor.remove("question"); - editor.remove("answer0"); - editor.remove("answer1"); - editor.remove("answer2"); - editor.remove("answer3"); - } - editor.apply(); - GameService.emitNextQuestionEvent(); - } - - private static void setQuestionSave(Question question) { - try { GameService.setQuestion(question); - } catch (NotInstantiatedException e) { - e.printStackTrace(); + } else if (scores != null) { + GameService.setScores(scores); + } else { + GameService.haltGame(); } + GameService.unsetNext(); } - private static void setState(int state) throws NotInstantiatedException { - if (!initialized) - throw new NotInstantiatedException(); - int previous = GameService.getState(); - GameService.state = state; - SharedPreferences.Editor editor = GameService.settings.edit(); - if (state!=States.UNINITIALIZED) { - editor.putInt("gameState", state); - } - else - editor.remove("gameState"); - editor.apply(); - if (GameService.state != States.RUNNING) + private static void setQuestion(Question question) { + Log.d(NAME, "token: "+question.getToken()); + GameService.question.setQuestion(question); + GameService.startTimings(); + GameService.setState(StoredStates.RUNNING); + GameService.emitQuestionUpdateEvent(); + } + + private static void setState(int state) { + GameService.states.nextState(state); + + if (GameService.getState().getState() != StoredStates.RUNNING) GameService.stopTimer(); - GameService.emitGameStateChangeEvent(previous); - if (GameService.state == States.RUNNING) + GameService.emitGameStateChangeEvent(); + if (GameService.getState().getState() == StoredStates.RUNNING) GameService.startTimer(); } - private static void setStateSave(int state) { - try { - GameService.setState(state); - } catch (NotInstantiatedException e) { - e.printStackTrace(); - } + private static void setResult(Result result) { + GameService.question.setResult(result); + GameService.emitQuestionUpdateEvent(); } - private static void setResult(QuestionResult result) throws NotInstantiatedException { - if (!initialized) - throw new NotInstantiatedException(); - GameService.result = result; - SharedPreferences.Editor editor = GameService.settings.edit(); - if (result != null) { - editor.putInt("resultScore", result.getScore()); - editor.putBoolean("resultCorrect", result.isCorrect()); - editor.putInt("resultPos", result.getCorrectPos()); - editor.putInt("resultTotal", result.getTotal()); - } else { - editor.remove("resultScore"); - editor.remove("resultCorrect"); - editor.remove("resultPos"); - editor.remove("resultTotal"); - } - editor.apply(); - GameService.emitResultEvent(); - } - - private static void setResultSave(QuestionResult result) { - try { - GameService.setResult(result); - } catch (NotInstantiatedException e) { - e.printStackTrace(); - } - } - - private static void setScores(GameScores gameScores) throws NotInstantiatedException { - if (!initialized) - throw new NotInstantiatedException(); - GameService.scores = gameScores; - SharedPreferences.Editor editor = GameService.settings.edit(); - if (gameScores != null) { - editor.putInt("gameScore", gameScores.getScore()); - editor.putInt("gameTime", gameScores.getTime()); - } else { - editor.remove("gameScore"); - editor.remove("gameTime"); - } - editor.apply(); + private static void setScores(Scores scores) { + GameService.scores.set(scores); + GameService.setState(StoredStates.END); GameService.emitGameEndEvent(); } - private static void setScoresSave(GameScores gameScores) { - try { - GameService.setScores(gameScores); - } catch (NotInstantiatedException e) { - e.printStackTrace(); - } - } - - private static void unsetScores() throws NotInstantiatedException { - if (!initialized) - throw new NotInstantiatedException(); - GameService.scores = null; - SharedPreferences.Editor editor = GameService.settings.edit(); - editor.remove("gameScore"); - editor.remove("gameTime"); - editor.apply(); - } - - private static void unsetScoresSave() { - try { - GameService.unsetScores(); - } catch (NotInstantiatedException e) { - e.printStackTrace(); - } - } - - private static void setStartTime(long startTime) throws NotInstantiatedException { - if (!initialized) - throw new NotInstantiatedException(); - GameService.startTime = startTime; - SharedPreferences.Editor editor = GameService.settings.edit(); - editor.putLong("startTime", startTime); - editor.apply(); - } - - private static void setStartTimeSave(long startTime) { - try { - GameService.setStartTime(startTime); - } catch (NotInstantiatedException e) { - e.printStackTrace(); - } - } - - private static void setEndTime(long endTime) throws NotInstantiatedException { - Log.d(NAME, "setEndTime "+endTime); - if (!initialized) - throw new NotInstantiatedException(); - GameService.endTime = endTime; - SharedPreferences.Editor editor = GameService.settings.edit(); - editor.putLong("endTime", endTime); - editor.apply(); - } - - private static void unsetStartTime() throws NotInstantiatedException { - Log.d(NAME, "unsetStartTime"); - if (!initialized) - throw new NotInstantiatedException(); - GameService.startTime = 0; - SharedPreferences.Editor editor = GameService.settings.edit(); - editor.remove("startTime"); - editor.apply(); - } - - private static void unsetStartTimeSave() { - try { - GameService.unsetStartTime(); - } catch (NotInstantiatedException e) { - e.printStackTrace(); - } - } - - private static void unsetEndTime() throws NotInstantiatedException { - Log.d(NAME, "unsetEndTime"); - if (!initialized) - throw new NotInstantiatedException(); - GameService.endTime = 0; - SharedPreferences.Editor editor = GameService.settings.edit(); - editor.remove("endTime"); - editor.apply(); - } - - private static void unsetEndTimeSave() { - try { - GameService.unsetEndTime(); - } catch (NotInstantiatedException e) { - e.printStackTrace(); - } - } - - private static void setAnswer(int id) throws NotInstantiatedException { - if (!initialized) - throw new NotInstantiatedException(); - GameService.answer = id; - SharedPreferences.Editor editor = GameService.settings.edit(); - editor.putInt("answer", id); - editor.apply(); - } - - private static void setAnswerSave(int id) { - try { - GameService.setAnswer(id); - } catch (NotInstantiatedException e) { - e.printStackTrace(); - } + private static void setAnswer(int id) { + GameService.question.setAnswer(id); + GameService.emitQuestionUpdateEvent(); } private static Question parseQuestion(JSONObject data_next) { @@ -823,6 +464,7 @@ public class GameService { return new Question( data_next.optString("categoryName", ""), data_next.optInt("categoryID", 0), + data_next.optString("token", ""), data_next.optString("question", ""), new String[]{ data_next_arr.optString(0, ""), @@ -833,8 +475,8 @@ public class GameService { ); } - private static GameScores parseScores(JSONObject data_end) { - return new GameScores( + private static Scores parseScores(JSONObject data_end) { + return new Scores( data_end.optInt("score", 0), data_end.optInt("time", 0) ); diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Services/HighscoreService.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Services/HighscoreService.java index b69d58b..ec2e871 100644 --- a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Services/HighscoreService.java +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Services/HighscoreService.java @@ -11,9 +11,8 @@ import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; -import de.hwr_berlin.it14.postgrachelor.Exceptions.NotInstantiatedException; +import de.hwr_berlin.it14.postgrachelor.Exceptions.NotInitializedException; import de.hwr_berlin.it14.postgrachelor.Exceptions.NotLoggedInException; -import de.hwr_berlin.it14.postgrachelor.Types.GameScores; import de.hwr_berlin.it14.postgrachelor.Types.Highscores; import de.hwr_berlin.it14.postgrachelor.Types.HighscoresUser; import de.hwr_berlin.it14.postgrachelor.Utils.Conversion; @@ -42,12 +41,12 @@ public class HighscoreService { public static void addHighscoreUpdateEventListener(OnHighscoreUpdateEventListener onLoginEventListener) { highscoreUpdateEventListeners.add(onLoginEventListener); - onLoginEventListener.onHighscoreUpdateEvent(HighscoreService.latestScores); + onLoginEventListener.onHighscoreUpdateEvent(getLatestScores()); } private static void emitHighscoreUpdateEvent() { for (OnHighscoreUpdateEventListener listener: highscoreUpdateEventListeners) { - listener.onHighscoreUpdateEvent(latestScores); + listener.onHighscoreUpdateEvent(getLatestScores()); } } @@ -57,11 +56,11 @@ public class HighscoreService { instantiated = true; } - public static boolean available() { + private static boolean available() { return (HighscoreService.latestScores != null); } - public static Highscores getLatestScores() { + private static Highscores getLatestScores() { return HighscoreService.latestScores; } @@ -70,22 +69,24 @@ public class HighscoreService { emitHighscoreUpdateEvent(); } - public static void updateHighscores() throws NotInstantiatedException, NotLoggedInException { + public static void updateHighscores() throws NotInitializedException, NotLoggedInException { HighscoreService.updateHighscores(null); } - public static void updateHighscores(final JsonRequestPG.AsyncResponse asyncResponse) throws NotInstantiatedException, NotLoggedInException { - //if (lastUpdate >= System.currentTimeMillis()-MIN_REFRESH_RATE) - // return; - //lastUpdate = System.currentTimeMillis(); + public static void updateHighscores(final JsonRequestPG.AsyncResponse asyncResponse) throws NotInitializedException, NotLoggedInException { + if (lastUpdate >= System.currentTimeMillis()-MIN_REFRESH_RATE && available()) { + emitHighscoreUpdateEvent(); + return; + } + lastUpdate = System.currentTimeMillis(); if (!instantiated) - throw new NotInstantiatedException(); + throw new NotInitializedException(); HashMap params = new HashMap<>(); String uid = LoginService.getLoginUID(); Log.d(NAME, uid); params.put("uid", LoginService.getLoginUID()); - JsonRequestPG requester = new JsonRequestPG("highscores.php", params, activity, new JsonRequestPG.AsyncResponse() { + JsonRequestPG requester = new JsonRequestPG("highscores.php", params, /*activity*/null, new JsonRequestPG.AsyncResponse() { @Override public void processFinish(JSONObject output) { // never reached if not instantiated @@ -124,7 +125,7 @@ public class HighscoreService { if (status==15102) { // user uid not found try { LoginService.setLogout(status, message); - } catch (NotInstantiatedException e) { + } catch (NotInitializedException e) { e.printStackTrace(); } } diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Services/LoginService.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Services/LoginService.java index 25c4c6a..4680a1e 100644 --- a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Services/LoginService.java +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Services/LoginService.java @@ -9,7 +9,7 @@ import org.json.JSONObject; import java.util.HashMap; -import de.hwr_berlin.it14.postgrachelor.Exceptions.NotInstantiatedException; +import de.hwr_berlin.it14.postgrachelor.Exceptions.NotInitializedException; import de.hwr_berlin.it14.postgrachelor.Exceptions.NotLoggedInException; import de.hwr_berlin.it14.postgrachelor.Utils.JsonRequestPG; @@ -36,11 +36,9 @@ public class LoginService { if (isLoggedInSave()) { try { onLoginEventListener.onLoginEvent(getLoginName(), getLoginUID()); - } catch (NotInstantiatedException | NotLoggedInException e) { + } catch (NotInitializedException | NotLoggedInException e) { e.printStackTrace(); } - } else { - //onLoginEventListener.onLogoutEvent(-6, null); } } @@ -65,7 +63,7 @@ public class LoginService { try { name = getLoginName(); uid = getLoginUIDSave(); - } catch (NotInstantiatedException e) { + } catch (NotInitializedException e) { e.printStackTrace(); } if (isLoggedInSave()) { @@ -75,41 +73,41 @@ public class LoginService { } } - public static boolean isLoggedIn() throws NotInstantiatedException { + public static boolean isLoggedIn() throws NotInitializedException { if (!instantiated) - throw new NotInstantiatedException(); + throw new NotInitializedException(); return settings.getBoolean("isLoggedIn", false); } private static boolean isLoggedInSave() { try { return isLoggedIn(); - } catch (NotInstantiatedException e) { + } catch (NotInitializedException e) { return false; } } - private static String getLoginName() throws NotInstantiatedException { + private static String getLoginName() throws NotInitializedException { if (!LoginService.isLoggedIn()) return ""; return settings.getString("loginName", ""); } - static String getLoginUID() throws NotInstantiatedException, NotLoggedInException { + static String getLoginUID() throws NotInitializedException, NotLoggedInException { if (!LoginService.isLoggedIn()) throw new NotLoggedInException(); return settings.getString("loginUID", ""); } - static String getLoginUIDSave() throws NotInstantiatedException { + private static String getLoginUIDSave() throws NotInitializedException { if (!LoginService.isLoggedIn()) return ""; return settings.getString("loginUID", ""); } - private static void setLogin(String name, String uid) throws NotInstantiatedException { + private static void setLogin(String name, String uid) throws NotInitializedException { if (!instantiated) - throw new NotInstantiatedException(); + throw new NotInitializedException(); SharedPreferences.Editor editor = settings.edit(); editor.putString("loginName", name); editor.putString("loginUID", uid); @@ -118,9 +116,9 @@ public class LoginService { emitLoginEvent(name, uid); } - public static void setLogout(int status, String message) throws NotInstantiatedException { + public static void setLogout(int status, String message) throws NotInitializedException { if (!instantiated) - throw new NotInstantiatedException(); + throw new NotInitializedException(); SharedPreferences.Editor editor = settings.edit(); editor.clear(); editor.apply(); @@ -130,20 +128,20 @@ public class LoginService { private static void setLoginSave(String name, String uid) { try { setLogin(name, uid); - } catch (NotInstantiatedException ignored) { + } catch (NotInitializedException ignored) { } } private static void setLogoutSave(int status, String message) { try { setLogout(status, message); - } catch (NotInstantiatedException ignored) { + } catch (NotInitializedException ignored) { } } - public static void doLogin(String name) throws NotInstantiatedException { + public static void doLogin(String name) throws NotInitializedException { if (!instantiated) - throw new NotInstantiatedException(); + throw new NotInitializedException(); HashMap params = new HashMap<>(); params.put("name", name); JsonRequestPG requester = new JsonRequestPG("register.php", params, activity, new JsonRequestPG.AsyncResponse() { diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/Question.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/Question.java index e34ebaf..3306eba 100644 --- a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/Question.java +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/Question.java @@ -8,12 +8,14 @@ package de.hwr_berlin.it14.postgrachelor.Types; public class Question { private final String category; private final int categoryID; + private final String token; private final String question; private final String[] answers; - public Question(String category, int categoryID, String question, String[] answers) { + public Question(String category, int categoryID, String token, String question, String[] answers) { this.category = category; this.categoryID = categoryID; + this.token = token; this.question = question; this.answers = answers; } @@ -22,10 +24,14 @@ public class Question { return category; } - public int getCategoryID() { + int getCategoryID() { return categoryID; } + public String getToken() { + return token; + } + public String getQuestion() { return question; } diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/QuestionResult.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/Result.java similarity index 85% rename from app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/QuestionResult.java rename to app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/Result.java index 223ca3c..1cbce26 100644 --- a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/QuestionResult.java +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/Result.java @@ -5,13 +5,13 @@ package de.hwr_berlin.it14.postgrachelor.Types; * Contains statistics of answering the last question */ -public class QuestionResult { +public class Result { private final int score; private final int correctPos; private final int total; private final boolean correct; - public QuestionResult(boolean correct, int score, int correctPos, int total) { + public Result(boolean correct, int score, int correctPos, int total) { this.correct = correct; this.score = score; this.correctPos = correctPos; diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/GameScores.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/Scores.java similarity index 67% rename from app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/GameScores.java rename to app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/Scores.java index df29ef8..066bf95 100644 --- a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/GameScores.java +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/Scores.java @@ -1,16 +1,15 @@ package de.hwr_berlin.it14.postgrachelor.Types; /** - * Created by Sebastian on 30.03.2017. - * Games scores on game end + * Created by Sebastian on 22.04.2017. + * Scores of a game */ -public class GameScores { - +public class Scores { private final int score; private final int time; - public GameScores(int score, int time) { + public Scores(int score, int time) { this.score = score; this.time = time; } diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/States.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/States.java new file mode 100644 index 0000000..05b3c51 --- /dev/null +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/States.java @@ -0,0 +1,25 @@ +package de.hwr_berlin.it14.postgrachelor.Types; + +/** + * Created by Sebastian on 23.04.2017. + * Current and previous game state + */ + +public class States { + private final int previous; + private final int state; + + public States(int previous, int state) { + + this.previous = previous; + this.state = state; + } + + public int getPrevious() { + return previous; + } + + public int getState() { + return state; + } +} diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredNextEntity.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredNextEntity.java new file mode 100644 index 0000000..f00c2c0 --- /dev/null +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredNextEntity.java @@ -0,0 +1,153 @@ +package de.hwr_berlin.it14.postgrachelor.Types; + +import android.content.SharedPreferences; +import android.util.Log; + +/** + * Created by Sebastian on 22.04.2017. + * Stored next entity + */ + +public class StoredNextEntity extends StoredObject { + private class Next extends StoredObject { + + private static final String STR_CATEGORY = "category"; + private String category; + private static final String STR_CATEGORY_ID = "categoryID"; + private int categoryID; + private static final String STR_TOKEN = "token"; + private String token; + private static final String STR_QUESTION = "question"; + private String question; + private static final String STR_ANSWER0 = "answer0"; + private String answer0; + private static final String STR_ANSWER1 = "answer1"; + private String answer1; + private static final String STR_ANSWER2 = "answer2"; + private String answer2; + private static final String STR_ANSWER3 = "answer3"; + private String answer3; + + private Next(SharedPreferences prefs, String prefix) { + super(prefs, prefix+".next"); + this.category = this.loadFromPref(STR_CATEGORY, ""); + this.categoryID = this.loadFromPref(STR_CATEGORY_ID, -1); + this.token = this.loadFromPref(STR_TOKEN, ""); + this.question = this.loadFromPref(STR_QUESTION, ""); + this.answer0 = this.loadFromPref(STR_ANSWER0, ""); + this.answer1 = this.loadFromPref(STR_ANSWER1, ""); + this.answer2 = this.loadFromPref(STR_ANSWER2, ""); + this.answer3 = this.loadFromPref(STR_ANSWER3, ""); + } + + private void set(Question question) { + this.category = question.getCategory(); + this.saveToPref(STR_CATEGORY, this.category); + this.categoryID = question.getCategoryID(); + this.saveToPref(STR_CATEGORY_ID, this.categoryID); + this.token = question.getToken(); + this.saveToPref(STR_TOKEN, this.token); + this.question = question.getQuestion(); + this.saveToPref(STR_QUESTION, this.question); + this.answer0 = question.getAnswers()[0]; + this.saveToPref(STR_ANSWER0, this.answer0); + this.answer1 = question.getAnswers()[1]; + this.saveToPref(STR_ANSWER1, this.answer1); + this.answer2 = question.getAnswers()[2]; + this.saveToPref(STR_ANSWER2, this.answer2); + this.answer3 = question.getAnswers()[3]; + this.saveToPref(STR_ANSWER3, this.answer3); + this.unremove(); + } + + public Question get() { + if (!this.isLoaded()) + return null; + return new Question(this.category, this.categoryID, this.token, this.question, new String[]{ + this.answer0, + this.answer1, + this.answer2, + this.answer3 + }); + } + + protected void remove() { + super.remove(); + } + } + + private class End extends StoredObject { + private static final String STR_SCORE = "score"; + private int score; + private static final String STR_TIME = "time"; + private int time; + + private End(SharedPreferences prefs, String prefix) { + super(prefs, prefix+".end"); + this.score = this.loadFromPref(STR_SCORE, 0); + this.time = this.loadFromPref(STR_TIME, 0); + } + + private void set(Scores scores) { + this.score = scores.getScore(); + this.saveToPref(STR_SCORE, this.score); + this.time = scores.getTime(); + this.saveToPref(STR_TIME, this.time); + this.unremove(); + } + + private Scores get() { + if (!this.isLoaded()) + return null; + return new Scores(this.score, this.time); + } + + @Override + public void remove() { + super.remove(); + } + } + + private final Next next; + private final End end; + + public StoredNextEntity(SharedPreferences prefs, String prefix) { + super(prefs, prefix+".nextEntity"); + this.next = new Next(prefs, prefix+".nextEntity"); + this.end = new End(prefs, prefix+".nextEntity"); + } + + public void setNext(Question question) { + this.next.set(question); + this.end.remove(); + this.unremove(); + } + + public void setEnd(Scores scores) { + this.end.set(scores); + this.next.remove(); + this.unremove(); + } + + public Question getNext() { + Log.d("getNext", String.valueOf(this.next.get() != null)); + return this.next.get(); + } + + public Scores getEnd() { + Log.d("getEnd", String.valueOf(this.end.get() != null)); + return this.end.get(); + } + + public boolean isNext() { + return this.next.isLoaded(); + } + + public boolean isEnd() { + return this.end.isLoaded(); + } + + public void remove() { + super.remove(); + } +} diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredObject.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredObject.java index 304c8dc..8e41022 100644 --- a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredObject.java +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredObject.java @@ -1,49 +1,90 @@ package de.hwr_berlin.it14.postgrachelor.Types; import android.content.SharedPreferences; +import android.util.Log; +import android.util.NoSuchPropertyException; + +import java.util.NoSuchElementException; /** * Created by Sebastian on 18.04.2017. + * Stored object */ -public class StoredObject { +abstract class StoredObject { private SharedPreferences prefs; private String prefix; - public StoredObject(SharedPreferences prefs, String prefix){ + StoredObject(SharedPreferences prefs, String prefix){ this.prefs = prefs; this.prefix = prefix; } - protected void saveToPref(String name, String value) { + protected void remove() { + SharedPreferences.Editor editor = this.prefs.edit(); + editor.putBoolean("L"+this.prefix, false); + editor.apply(); + Log.d("StoredObject-remove", "L"+this.prefix); + } + + void unremove() { + SharedPreferences.Editor editor = this.prefs.edit(); + editor.putBoolean("L"+this.prefix, true); + editor.apply(); + Log.d("StoredObject-unremove", "L"+this.prefix); + } + + public boolean isLoaded() { + return this.prefs.getBoolean("L"+this.prefix, false); + } + + void saveToPref(String name, String value) { SharedPreferences.Editor editor = this.prefs.edit(); editor.putString(this.prefix+"."+name, value); editor.apply(); } - protected void saveToPref(String name, int value) { + void saveToPref(String name, int value) { SharedPreferences.Editor editor = this.prefs.edit(); editor.putInt(this.prefix+"."+name, value); editor.apply(); } - protected void saveToPref(String name, long value) { + void saveToPref(String name, long value) { SharedPreferences.Editor editor = this.prefs.edit(); editor.putLong(this.prefix+"."+name, value); editor.apply(); } - - - protected String loadString(String name) { - return this.prefs.getString(name, ""); + void saveToPref(String name, boolean value) { + SharedPreferences.Editor editor = this.prefs.edit(); + editor.putBoolean(this.prefix+"."+name, value); + editor.apply(); } - protected int loadInt(String name) { - return this.prefs.getInt(name, 0); + + + String loadFromPref(String name, String defValue) { + if (!this.isLoaded()) + return defValue; + return this.prefs.getString(this.prefix+"."+name, defValue); } - protected long loadLong(String name) { - return this.prefs.getLong(name, 0); + int loadFromPref(String name, int defValue) { + if (!this.isLoaded()) + return defValue; + return this.prefs.getInt(this.prefix+"."+name, defValue); + } + + long loadFromPref(String name, long defValue) { + if (!this.isLoaded()) + return defValue; + return this.prefs.getLong(this.prefix+"."+name, defValue); + } + + boolean loadFromPref(String name, boolean defValue) { + if (!this.isLoaded()) + return defValue; + return this.prefs.getBoolean(this.prefix+"."+name, defValue); } } diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredQuestion.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredQuestion.java new file mode 100644 index 0000000..6d28542 --- /dev/null +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredQuestion.java @@ -0,0 +1,207 @@ +package de.hwr_berlin.it14.postgrachelor.Types; + +import android.content.SharedPreferences; + +/** + * Created by Sebastian on 22.04.2017. + * Stored question object + */ + +public class StoredQuestion extends StoredObject { + private class Question extends StoredObject { + + private static final String STR_CATEGORY = "category"; + private String category; + private static final String STR_CATEGORY_ID = "categoryID"; + private int categoryID; + private static final String STR_TOKEN = "token"; + private String token; + private static final String STR_QUESTION = "question"; + private String question; + private static final String STR_ANSWER0 = "answer0"; + private String answer0; + private static final String STR_ANSWER1 = "answer1"; + private String answer1; + private static final String STR_ANSWER2 = "answer2"; + private String answer2; + private static final String STR_ANSWER3 = "answer3"; + private String answer3; + + private Question(SharedPreferences prefs, String prefix) { + super(prefs, prefix+".question"); + this.category = this.loadFromPref(STR_CATEGORY, ""); + this.categoryID = this.loadFromPref(STR_CATEGORY_ID, -1); + this.token = this.loadFromPref(STR_TOKEN, ""); + this.question = this.loadFromPref(STR_QUESTION, ""); + this.answer0 = this.loadFromPref(STR_ANSWER0, ""); + this.answer1 = this.loadFromPref(STR_ANSWER1, ""); + this.answer2 = this.loadFromPref(STR_ANSWER2, ""); + this.answer3 = this.loadFromPref(STR_ANSWER3, ""); + } + + private void set(de.hwr_berlin.it14.postgrachelor.Types.Question question) { + this.category = question.getCategory(); + this.saveToPref(STR_CATEGORY, this.category); + this.categoryID = question.getCategoryID(); + this.saveToPref(STR_CATEGORY_ID, this.categoryID); + this.token = question.getToken(); + this.saveToPref(STR_TOKEN, this.token); + this.question = question.getQuestion(); + this.saveToPref(STR_QUESTION, this.question); + this.answer0 = question.getAnswers()[0]; + this.saveToPref(STR_ANSWER0, this.answer0); + this.answer1 = question.getAnswers()[1]; + this.saveToPref(STR_ANSWER1, this.answer1); + this.answer2 = question.getAnswers()[2]; + this.saveToPref(STR_ANSWER2, this.answer2); + this.answer3 = question.getAnswers()[3]; + this.saveToPref(STR_ANSWER3, this.answer3); + this.unremove(); + } + + public de.hwr_berlin.it14.postgrachelor.Types.Question get() { + if (!this.isLoaded()) + return null; + return new de.hwr_berlin.it14.postgrachelor.Types.Question(this.category, this.categoryID, this.token, this.question, new String[]{ + this.answer0, + this.answer1, + this.answer2, + this.answer3 + }); + } + + protected void remove() { + super.remove(); + } + } + + private class Answer extends StoredObject { + private static final String STR_ANSWER = "answer"; + private int answer; + + private Answer(SharedPreferences prefs, String prefix) { + super(prefs, prefix+".answer"); + this.answer = this.loadFromPref(STR_ANSWER, -1); + } + + private void set(int answer) { + if (this.isLoaded()) + return; + this.answer = answer; + this.saveToPref(STR_ANSWER, this.answer); + this.unremove(); + } + + private int get() { + if (this.isLoaded()) + return this.answer; + else return -1; + } + + @Override + public void remove() { + super.remove(); + } + } + + private class Result extends StoredObject { + + private static final String STR_SCORE = "score"; + private int score; + private static final String STR_CORRECT_POS = "correctPos"; + private int correctPos; + private static final String STR_TOTAL = "total"; + private int total; + private static final String STR_IS_CORRECT = "isCorrect"; + private boolean isCorrect; + + private Result(SharedPreferences prefs, String prefix) { + super(prefs, prefix + ".result"); + this.score = this.loadFromPref(STR_SCORE, 0); + this.correctPos = this.loadFromPref(STR_CORRECT_POS, 0); + this.total = this.loadFromPref(STR_TOTAL, 0); + this.isCorrect = this.loadFromPref(STR_IS_CORRECT, false); + } + + private void set(de.hwr_berlin.it14.postgrachelor.Types.Result result) { + this.isCorrect = result.isCorrect(); + this.saveToPref(STR_IS_CORRECT, this.isCorrect); + this.score = result.getScore(); + this.saveToPref(STR_SCORE, this.score); + this.correctPos = result.getCorrectPos(); + this.saveToPref(STR_CORRECT_POS, this.correctPos); + this.total = result.getTotal(); + this.saveToPref(STR_TOTAL, this.total); + this.unremove(); + } + + private de.hwr_berlin.it14.postgrachelor.Types.Result get() { + if (!this.isLoaded()) + return null; + return new de.hwr_berlin.it14.postgrachelor.Types.Result( + this.isCorrect, + this.score, + this.correctPos, + this.total + ); + } + } + + private final Question question; + private final Answer answer; + private final Result result; + + public StoredQuestion(SharedPreferences prefs, String prefix) { + super(prefs, prefix+".question"); + this.question = new Question(prefs, prefix+".question"); + this.answer = new Answer(prefs, prefix+".question"); + this.result = new Result(prefs, prefix+".question"); + if (this.question.isLoaded()) + this.unremove(); + else + this.remove(); + } + + public void setQuestion(de.hwr_berlin.it14.postgrachelor.Types.Question question) { + this.question.set(question); + this.answer.remove(); + this.result.remove(); + this.unremove(); + } + + public void setAnswer(int answer) { + this.answer.set(answer); + } + + public void setResult(de.hwr_berlin.it14.postgrachelor.Types.Result result) { + this.result.set(result); + } + + public de.hwr_berlin.it14.postgrachelor.Types.Question getQuestion() { + return this.question.get(); + } + + public int getAnswer() { + return this.answer.get(); + } + + public de.hwr_berlin.it14.postgrachelor.Types.Result getResult() { + return this.result.get(); + } + + public boolean isQuestion() { + return this.question.isLoaded(); + } + + public boolean isAnswer() { + return this.answer.isLoaded(); + } + + public boolean isResult() { + return this.result.isLoaded(); + } + + public void remove() { + super.remove(); + } +} diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredScores.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredScores.java new file mode 100644 index 0000000..37ef9f0 --- /dev/null +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredScores.java @@ -0,0 +1,40 @@ +package de.hwr_berlin.it14.postgrachelor.Types; + +import android.content.SharedPreferences; + +/** + * Created by Sebastian on 30.03.2017. + * Games scores on game end + */ + +public class StoredScores extends StoredObject { + + private int score; + private static final String STR_SCORE = "score"; + private int time; + private static final String STR_TIME = "time"; + + public StoredScores(SharedPreferences prefs, String prefix) { + super(prefs, prefix+".scores"); + this.score = this.loadFromPref(STR_SCORE, -1); + this.time = this.loadFromPref(STR_TIME, -1); + } + + public void remove() { + super.remove(); + } + + public void set(Scores scores) { + this.score = scores.getScore(); + this.saveToPref(STR_SCORE, this.score); + this.time = scores.getTime(); + this.saveToPref(STR_TIME, this.time); + this.unremove(); + } + + public Scores get() { + if (!this.isLoaded()) + return null; + return new Scores(this.score, this.time); + } +} diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredStates.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredStates.java new file mode 100644 index 0000000..1d15aab --- /dev/null +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredStates.java @@ -0,0 +1,48 @@ +package de.hwr_berlin.it14.postgrachelor.Types; + +import android.content.SharedPreferences; + +import java.util.NoSuchElementException; + +/** + * Created by Sebastian on 21.04.2017. + * Stored game state object + */ +public final class StoredStates extends StoredObject { + + public static final int UNINITIALIZED = 1; + public static final int END = 2; + public static final int ON_HOLD_LOADING = 4; + public static final int ON_HOLD_RESULT = 8; + public static final int RUNNING = 16; + public static final int PAUSED = 32; + + + private int state; + private static final String STR_STATE = "state"; + private int previous; + private static final String STR_PREVIOUS = "previous"; + + public StoredStates(SharedPreferences prefs, String prefix) { + super(prefs, prefix+".states"); + this.previous = this.loadFromPref(STR_PREVIOUS, END); + this.state = this.loadFromPref(STR_STATE, END); + this.unremove(); + } + + @Override + public boolean isLoaded() { + return true; + } + + public States get() { + return new States(this.previous, this.state); + } + + public void nextState(int state) { + this.previous = this.state; + this.state = state; + this.saveToPref(STR_PREVIOUS, this.previous); + this.saveToPref(STR_STATE, this.state); + } +} diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredTimings.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredTimings.java new file mode 100644 index 0000000..9075639 --- /dev/null +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/StoredTimings.java @@ -0,0 +1,71 @@ +package de.hwr_berlin.it14.postgrachelor.Types; + +import android.content.SharedPreferences; +import android.provider.Settings; + +/** + * Created by Sebastian on 06.04.2017. + * Timing results on each tick, when game is running + */ +public class StoredTimings extends StoredObject { + private static final int M = 1000; + private static final int N = 100; + private static final int R = 30; + private static final int S = 0; + private static final int T = 100; + + private long startTime; + private static final String STR_STARTTIME = "startTime"; + private long endTime; + private static final String STR_ENDTIME = "endTime"; + + public StoredTimings(SharedPreferences prefs, String prefix) { + super(prefs, prefix+".timings"); + this.startTime = this.loadFromPref(STR_STARTTIME, (long) -1); + this.endTime = this.loadFromPref(STR_ENDTIME, (long) -1); + if (this.startTime == -1) + this.remove(); + else + this.unremove(); + } + + public void start() { + this.startTime = System.currentTimeMillis(); + this.saveToPref(STR_STARTTIME, this.startTime); + this.endTime = -1; + this.saveToPref(STR_ENDTIME, this.endTime); + this.unremove(); + } + + public void stop() { + if (this.endTime != -1) + return; + this.endTime = System.currentTimeMillis(); + this.saveToPref(STR_ENDTIME, this.endTime); + } + + public void reset() { + this.remove(); + } + + public Timings get() { + return new Timings(this.getTimeDiff(), this.getScore()); + } + + private long getTimeDiff() { + if (!this.isLoaded()) + return 0; + else if (this.endTime != -1) + return this.endTime-this.startTime; + else + return System.currentTimeMillis()-this.startTime; + } + + private int getScore() { + //this.score = Math.max((int) Math.floor(1025 - 5*Math.sqrt(2*timeDiff-3975)), 10); + //this.score = (int) Math.max(N, M-(R*Math.sqrt(T*(-8*S+T+8*this.timeDiff))-T)/2/T); + + // simplified + return (int) Math.max(N, M-(R*Math.sqrt(T*(T + 8 * this.getTimeDiff()))-T)/2/T); + } +} diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/Timings.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/Timings.java index 31de1bf..9a2497a 100644 --- a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/Timings.java +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Types/Timings.java @@ -1,29 +1,17 @@ package de.hwr_berlin.it14.postgrachelor.Types; /** - * Created by Sebastian on 06.04.2017. - * Timing results on each tick, when game is running + * Created by Sebastian on 23.04.2017. + * Time and score measurement */ + public class Timings { - private static final int M = 1000; - private static final int N = 100; - private static final int R = 30; - private static final int S = 0; - private static final int T = 100; private final long timeDiff; private final int score; - public Timings(long timeDiff) { + Timings(long timeDiff, int score) { this.timeDiff = timeDiff; - if (timeDiff <= S) - this.score = M; - else { - //this.score = Math.max((int) Math.floor(1025 - 5*Math.sqrt(2*timeDiff-3975)), 10); - //this.score = (int) Math.max(N, M-(R*Math.sqrt(T*(-8*S+T+8*this.timeDiff))-T)/2/T); - - // simplified - this.score = (int) Math.max(N, M-(R*Math.sqrt(T*(T + 8 * this.timeDiff))-T)/2/T); - } + this.score = score; } public long getTimeDiff() { diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Utils/HighscoreAdapter.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Utils/HighscoreAdapter.java index f99c551..8947d5f 100644 --- a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Utils/HighscoreAdapter.java +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Utils/HighscoreAdapter.java @@ -14,6 +14,7 @@ import de.hwr_berlin.it14.postgrachelor.Types.HighscoresUser; /** * Created by Sebastian on 11.04.2017. + * Async highscore adapter for list view */ public class HighscoreAdapter extends AsyncAdapter { @@ -81,6 +82,6 @@ public class HighscoreAdapter extends AsyncAdapter { @Override protected int getRequestedLength(int position) { - return Math.min(1, getCount()-position); + return Math.min(10, getCount()-position); } } diff --git a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Utils/JsonRequestPG.java b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Utils/JsonRequestPG.java index 28333d1..32fe861 100644 --- a/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Utils/JsonRequestPG.java +++ b/app/src/main/java/de/hwr_berlin/it14/postgrachelor/Utils/JsonRequestPG.java @@ -3,6 +3,7 @@ package de.hwr_berlin.it14.postgrachelor.Utils; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; +import android.util.Log; import org.json.JSONArray; import org.json.JSONException; @@ -96,16 +97,17 @@ public class JsonRequestPG extends JsonRequest { int status = meta.optInt("status", -3); String message = meta.optString("message", ""); if (status != 0) { - new AlertDialog.Builder(this.activity) - .setTitle("Error "+status) - .setMessage(message) - .setNegativeButton(android.R.string.ok, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - // do nothing - } - }) - .setIcon(android.R.drawable.ic_dialog_alert) - .show(); + if (this.activity != null) + new AlertDialog.Builder(this.activity) + .setTitle("Error "+status) + .setMessage(message) + .setNegativeButton(android.R.string.ok, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + // do nothing + } + }) + .setIcon(android.R.drawable.ic_dialog_alert) + .show(); this.processError(status, message); return; } diff --git a/app/src/main/res/layout/fragment_main_game.xml b/app/src/main/res/layout/fragment_main_game.xml index ae750e8..b3512ab 100644 --- a/app/src/main/res/layout/fragment_main_game.xml +++ b/app/src/main/res/layout/fragment_main_game.xml @@ -5,6 +5,7 @@ android:layout_width="match_parent" android:layout_height="match_parent" tools:showIn="@layout/fragment_main" + android:clickable="true" android:padding="5dp"> + android:paddingLeft="50dp" + android:clickable="false" /> \ No newline at end of file