Pre-restucture

This commit is contained in:
Caesar2011
2017-04-21 11:41:23 +02:00
parent 976d74676c
commit 362e387d26
9 changed files with 276 additions and 96 deletions

2
.idea/misc.xml generated
View File

@@ -29,7 +29,7 @@
</value>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" assert-keyword="true" jdk-15="true" project-jdk-name="1.8 (2)" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" assert-keyword="true" jdk-15="true" project-jdk-name="1.8 (1)" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">

View File

@@ -2,21 +2,67 @@ package de.hwr_berlin.it14.postgrachelor;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
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.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;
public class MainActivity extends AppCompatActivity {
public class MainActivity extends AppCompatActivity implements RequestActivityInterface {
private HashMap<String, ProgressDialog> dialogs = new HashMap<>();
@Override
public String showDialog() {
ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage(this.getString(R.string.please_wait));
pDialog.setCancelable(false);
if (!this.isFinishing())
pDialog.show();
String uuid = UUID.randomUUID().toString();
this.dialogs.put(uuid, pDialog);
return uuid;
}
@Override
public void errorJsonParsing() {
Toast.makeText(this.getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
@Override
public void errorJsonLoadingFailed(String message) {
Toast.makeText(this.getApplicationContext(),
"Json parsing error: " + message,
Toast.LENGTH_LONG)
.show();
}
@Override
public void hideDialog(String uuid) {
if (dialogs.containsKey(uuid)) {
ProgressDialog dialog = dialogs.get(uuid);
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}
private static class FragmentState {
private static final int LOGIN = 0x1;
@@ -106,12 +152,17 @@ public class MainActivity extends AppCompatActivity {
@Override
public void onBackPressed()
{
this.selectFragment(FragmentState.MAIN);
//this.selectFragment(FragmentState.MAIN);
boolean success;
try {
success = GameService.pauseGame();
HighscoreService.updateHighscores();
} catch (NotInstantiatedException | NotLoggedInException e) {
success = false;
e.printStackTrace();
}
if (!success)
super.onBackPressed();
}
@Override
@@ -188,4 +239,17 @@ public class MainActivity extends AppCompatActivity {
savedInstanceState.putInt("selected fragment", this.fragmentState);
super.onSaveInstanceState(savedInstanceState);
}
@Override
protected void onDestroy() {
Set<String> keys = dialogs.keySet();
for (String key: keys) {
ProgressDialog dialog = dialogs.get(key);
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
//dialogs.put(key, null);
}
super.onDestroy();
}
}

View File

@@ -1,5 +1,6 @@
package de.hwr_berlin.it14.postgrachelor;
import android.content.Context;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v4.content.ContextCompat;
@@ -106,42 +107,26 @@ public class QuestionFragment extends Fragment {
}
});
}
GameService.addResultEventListener(NAME, new GameService.OnResultEventListener() {
@Override
public void onResultEvent(QuestionResult result) {
Log.d(NAME, "onResultEvent - result: " + result);
if (result != null) {
int colorBgClicked = ContextCompat.getColor(getActivity().getApplicationContext(), android.R.color.holo_red_dark);
int colorBg = ContextCompat.getColor(getActivity().getApplicationContext(), android.R.color.holo_green_dark);
int colorText = ContextCompat.getColor(getActivity().getApplicationContext(), android.R.color.black);
int answerID;
try {
answerID = GameService.getAnswer();
} catch (NotInstantiatedException e) {
answerID = 0;
e.printStackTrace();
}
Log.d(NAME, "onResultEvent - answerID: " + answerID);
Context context = getActivity().getApplicationContext();
final int colorBgClicked = ContextCompat.getColor(context, android.R.color.holo_red_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);
questionAnswerViews[answerID].setBackgroundColor(colorBgClicked);
questionAnswerViews[result.getCorrectPos()].setBackgroundColor(colorBg);
questionAnswerViews[result.getCorrectPos()].setTextColor(colorText);
totalView.setText(Conversion.intToStr(result.getTotal()));
scoreView.setText(Conversion.intToStr(result.getScore()));
if (result.isCorrect()) {
Animation animation = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.scale_up);
animation.setInterpolator(new ReverseInterpolator(new AccelerateInterpolator()));
totalView.startAnimation(animation);
}
GameService.addTickEventListener(NAME, new GameService.OnTickEventListener() {
@Override
public void onTickEvent(Timings timings) {
if (timings != null) {
timeView.setText(Conversion.millisToTime(timings.getTimeDiff()));
scoreView.setText(String.format(Locale.getDefault(), "%1d", timings.getScore()));
}
}
});
GameService.addNextQuestionEventListener(NAME, new GameService.OnNextQuestionEventListener() {
@Override
public void onNextQuestionEvent(Question question) {
}
});
GameService.addNextQuestionEventListener(NAME, new GameService.OnNextQuestionEventListener() {
@Override
public void onNextQuestionEvent(Question question) {
Log.d(NAME, "onNextQuestionEvent - question: " + question);
for (int i = 0; i < 4; i++) {
questionAnswerViews[i].setBackgroundColor(
ContextCompat.getColor(view.getContext(), R.color.colorPrimary)
@@ -163,25 +148,46 @@ 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);
}
totalView.setText(Conversion.intToStr(result.getTotal()));
scoreView.setText(Conversion.intToStr(result.getScore()));
if (result.isCorrect()) {
animation.setInterpolator(new ReverseInterpolator(new AccelerateInterpolator()));
totalView.startAnimation(animation);
}
}
});
GameService.addTickEventListener(NAME, new GameService.OnTickEventListener() {
@Override
public void onTickEvent(Timings timings) {
if (timings != null) {
timeView.setText(Conversion.millisToTime(timings.getTimeDiff()));
scoreView.setText(String.format(Locale.getDefault(), "%1d", timings.getScore()));
}
}
});
GameService.addGameStateChangeEventListener(NAME, new GameService.OnGameStateChangeEventListener() {
}
});
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)
totalView.setText(R.string._0);
}
});
});
return view;
}
}

View File

@@ -38,7 +38,7 @@ public class GameService {
private static long startTime;
private static long endTime;
private static int answer;
private static int answer = -1;
private static Timer timer;
private static JSONObject data = null;
@@ -99,6 +99,7 @@ public class GameService {
e.printStackTrace();
}
emitTickEvent();
emitNextQuestionEvent();
emitGameEndEvent();
emitResultEvent();
@@ -165,6 +166,7 @@ public class GameService {
@SuppressWarnings("SameParameterValue")
public static void addTickEventListener(String key, OnTickEventListener onTickEventListener) {
gameTickEventListeners.put(key, onTickEventListener);
onTickEventListener.onTickEvent(GameService.getTimingsSave());
}
private static Timings getTimingsSave() {
@@ -177,16 +179,13 @@ public class GameService {
}
private static Timings getTimings() throws NotInstantiatedException {
long timeDiff = GameService.getStartTime();
timeDiff = System.currentTimeMillis()-timeDiff;
int score;
if (timeDiff <= 2000)
score = 1000;
long timeDiff = GameService.getEndTime();
if (timeDiff != 0)
timeDiff = timeDiff-GameService.getStartTime();
else
score = Math.max((int) Math.floor(1025 - 5*Math.sqrt(2*timeDiff-3975)), 10);
timeDiff = System.currentTimeMillis() - GameService.getStartTime();
return new Timings(timeDiff, score);
return new Timings(timeDiff);
}
private static void emitTickEvent() {
@@ -304,11 +303,13 @@ public class GameService {
}
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),
@@ -316,10 +317,12 @@ public class GameService {
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;
}
@@ -342,16 +345,18 @@ public class GameService {
}
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 int getAnswer(int id) throws NotInstantiatedException {
if (GameService.answer == 0) {
if (GameService.answer == -1) {
if (!GameService.initialized)
throw new NotInstantiatedException();
GameService.answer = GameService.settings.getInt("answer", id);
@@ -360,16 +365,28 @@ public class GameService {
}
public static int getAnswer() throws NotInstantiatedException {
return GameService.getAnswer(0);
return GameService.getAnswer(-1);
}
public static void pauseGame() throws NotInstantiatedException {
GameService.setState(States.PAUSED);
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);
return true;
} else {
return false;
}
}
public static void resumeGame() throws NotInstantiatedException {
GameService.setState(States.RUNNING);
if (GameService.isNextNeeded()) {
GameService.setState(States.ON_HOLD_RESULT);
} else if (GameService.getAnswer() != -1) {
GameService.setState(States.ON_HOLD_LOADING);
} else {
GameService.setState(States.RUNNING);
}
}
public static void endGame() throws NotInstantiatedException {
@@ -423,13 +440,14 @@ public class GameService {
);
GameService.setResultSave(result);
GameService.setNeededNextSave(data);
GameService.setAnswerSave(-1);
GameService.setStateSave(States.ON_HOLD_RESULT);
}
@Override
public void processError(int status, String message) {
Log.d("GameServiceFragment", "answer/processError "+status+" "+message);
if (status==13104)
if (status==13104 || status==13102)
try {
GameService.endGame();
} catch (NotInstantiatedException e) {
@@ -575,6 +593,7 @@ public class GameService {
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");
@@ -582,6 +601,7 @@ public class GameService {
GameService.setStateSave(States.END);
GameService.unsetStartTimeSave();
GameService.unsetEndTimeSave();
GameService.setResultSave(null);
}
GameService.setNeededNext(null);
}
@@ -736,6 +756,7 @@ public class GameService {
}
private static void setEndTime(long endTime) throws NotInstantiatedException {
Log.d(NAME, "setEndTime "+endTime);
if (!initialized)
throw new NotInstantiatedException();
GameService.endTime = endTime;
@@ -745,6 +766,7 @@ public class GameService {
}
private static void unsetStartTime() throws NotInstantiatedException {
Log.d(NAME, "unsetStartTime");
if (!initialized)
throw new NotInstantiatedException();
GameService.startTime = 0;
@@ -762,6 +784,7 @@ public class GameService {
}
private static void unsetEndTime() throws NotInstantiatedException {
Log.d(NAME, "unsetEndTime");
if (!initialized)
throw new NotInstantiatedException();
GameService.endTime = 0;
@@ -787,6 +810,14 @@ public class GameService {
editor.apply();
}
private static void setAnswerSave(int id) {
try {
GameService.setAnswer(id);
} catch (NotInstantiatedException e) {
e.printStackTrace();
}
}
private static Question parseQuestion(JSONObject data_next) {
JSONArray data_next_arr = data_next.optJSONArray("answers");
return new Question(

View File

@@ -0,0 +1,12 @@
package de.hwr_berlin.it14.postgrachelor.Types;
/**
* Created by Sebastian on 20.04.2017.
*/
public interface RequestActivityInterface {
String showDialog();
void errorJsonParsing();
void errorJsonLoadingFailed(String message);
void hideDialog(String uuid);
}

View File

@@ -0,0 +1,49 @@
package de.hwr_berlin.it14.postgrachelor.Types;
import android.content.SharedPreferences;
/**
* Created by Sebastian on 18.04.2017.
*/
public class StoredObject {
private SharedPreferences prefs;
private String prefix;
public StoredObject(SharedPreferences prefs, String prefix){
this.prefs = prefs;
this.prefix = prefix;
}
protected 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) {
SharedPreferences.Editor editor = this.prefs.edit();
editor.putInt(this.prefix+"."+name, value);
editor.apply();
}
protected 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, "");
}
protected int loadInt(String name) {
return this.prefs.getInt(name, 0);
}
protected long loadLong(String name) {
return this.prefs.getLong(name, 0);
}
}

View File

@@ -4,15 +4,26 @@ package de.hwr_berlin.it14.postgrachelor.Types;
* Created by Sebastian on 06.04.2017.
* Timing results on each tick, when game is running
*/
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, int score) {
public Timings(long timeDiff) {
this.timeDiff = timeDiff;
this.score = score;
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);
}
}
public long getTimeDiff() {

View File

@@ -41,7 +41,11 @@ public class HighscoreAdapter extends AsyncAdapter<HighscoresUser> {
userPlaceView.setText(convertView.getContext().getResources().getString(R.string.place, Conversion.intToStr(item.getPlace())));
}
if (userScoreView != null) {
userScoreView.setText(Conversion.intToStr(item.getScore()));
int score = item.getScore();
if (score != -1)
userScoreView.setText(Conversion.intToStr(score));
else
userScoreView.setText(convertView.getContext().getResources().getString(R.string.no_score));
}
}
@@ -77,6 +81,6 @@ public class HighscoreAdapter extends AsyncAdapter<HighscoresUser> {
@Override
protected int getRequestedLength(int position) {
return Math.min(10, getCount()-position);
return Math.min(1, getCount()-position);
}
}

View File

@@ -21,6 +21,8 @@ import java.util.Map;
import java.util.Scanner;
import de.hwr_berlin.it14.postgrachelor.R;
import de.hwr_berlin.it14.postgrachelor.Types.RequestActivityInterface;
import de.hwr_berlin.it14.postgrachelor.Types.Requestable;
import static android.content.ContentValues.TAG;
@@ -29,13 +31,17 @@ abstract class JsonRequest extends AsyncTask<Void, Void, JSONObject> {
private final String path;
private final HashMap<String, String> params;
final Activity activity;
private ProgressDialog pDialog;
private String uuid;
JsonRequest(String path, HashMap<String, String> params, Activity activity) {
this.connectionURL = getConnectionURL();
this.path = path;
this.params = params;
this.activity = activity;
if (activity instanceof RequestActivityInterface) {
this.activity = activity;
} else {
this.activity = null;
}
Log.d("JSONRequest create", connectionURL+path);
}
@@ -53,10 +59,8 @@ abstract class JsonRequest extends AsyncTask<Void, Void, JSONObject> {
super.onPreExecute();
Log.d("fragment, JSONRequest", "onPre1");
// Showing progress dialog
pDialog = new ProgressDialog(this.activity);
pDialog.setMessage(this.activity.getString(R.string.please_wait));
pDialog.setCancelable(false);
pDialog.show();
if (this.activity != null)
this.uuid = ((RequestActivityInterface) this.activity).showDialog();
}
@@ -100,28 +104,27 @@ abstract class JsonRequest extends AsyncTask<Void, Void, JSONObject> {
jsonObj = new JSONObject(jsonText);
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity.getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
if (this.activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
((RequestActivityInterface) activity).errorJsonLoadingFailed(e.getMessage());
}
});
}
}
} else {
Log.e(TAG, "Couldn't get json from server.");
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity.getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
if (this.activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
((RequestActivityInterface) activity).errorJsonParsing();
}
});
}
}
@@ -131,8 +134,8 @@ abstract class JsonRequest extends AsyncTask<Void, Void, JSONObject> {
@Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
if (this.activity != null)
((RequestActivityInterface) activity).hideDialog(this.uuid);
}
private String parseURL(String url, Map<String, String> params)