In January we wrote a post on how to integrate scoreoid in Libgdx for Android. In this post we would be integrating it for the desktop/PC version.
For parsing JSON we are using the source code available in this link JSON in Java. Here is the Github link. In this post we would only explain the desktop specific part of the code. Please check the previous post Using Scoreoid with Libgdx/Android for more details.
Here is the ScoreInterface.java file which we would be calling in the main game code. This would be implemented differently in different environments to handle platform specific requirements.
[sourcecode language=”java”]
public interface ScoreInterface {
public void OpenHighScores();
}
[/sourcecode]
The Main.java in desktop would implement ScoreInterface and we would pass this object to our ApplicationListener super class (starting point for a libgdx game). Below is a snippet.
Main.java
[sourcecode language=”java”]
public class Main implements ScoreInterface {
static Main app;
public static final String SCOREOID_URL = “https://www.scoreoid.com/api/”;
public static final String GETBESTSCORES = “getBestScores”;
public static void main(String[] args) {
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.title = “ScoreoidExample”;
cfg.useGL20 = false;
cfg.width = 480;
cfg.height = 320;
if (app == null)
app = new Main();
new LwjglApplication(new ScoreoidExample(app), cfg);
}
@Override
public void OpenHighScores() {
//….
}
[/sourcecode]
So the Main class implements ScoreInterface and then it passed as argument when creating ScoreoidExample object. So when OpenHighScores is called, depending on the platform, desktop/android version is executed.
To get this working we would need to :
- Make Http calls to receive response from Scoreoid Api.
- Parse the json response
Make Http calls to receive response from Scoreoid Api
As scoreoid api provides post services, so we have to make a post request and pass parameters to get the score data. This is similar to handling any other post services in java. Here is a snippet for fetching the response.
[sourcecode language=”java”]
public class ScoreoidConstants {
public static final String SCOREOID_APIKEY=”PLACE YOUR API KEY HERE !!!”;
public static final String SCOREOID_GAME_ID=”PLACE YOUR GAME ID HERE !!!”;
public static final String SCOREOID_RESPONSETYPE=”json”;
public static final String SCOREOID_SCORE_ORDERBY=”score”;
public static final String SCOREOID_SCORE_ORDER=”desc”;
}
[/sourcecode]
The constants file where we are storing the apikey,gameid etc which would be used to form the parameters we pass to the url.
[sourcecode language=”java”]
Url url=null;
public StringBuffer GetResponse(URL url) throws Exception {
this.url = url;
StringBuffer buffer;
String line;
int responseCode;
HttpURLConnection connection;
InputStream input;
BufferedReader dataInput;
//ADD PARAMETERS TO FETCH DATA FOR GETBESTSCORES API
String urlParameters=”api_key=”+ ScoreoidConstants.SCOREOID_APIKEY+”&”
+”game_id=”+ScoreoidConstants.SCOREOID_GAME_ID+”&”
+”response=”+ScoreoidConstants.SCOREOID_RESPONSETYPE+”&”
+”order_by=”+ScoreoidConstants.SCOREOID_SCORE_ORDERBY+”&”
+”order=”+ScoreoidConstants.SCOREOID_SCORE_ORDER+”&”
+”limit=”+”0,20″;
//CREATE CONNECTION
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(“POST”);
connection.setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded”);
connection.setDoOutput(true);
connection.setRequestProperty(“charset”, “utf-8”);
connection.setRequestProperty(“Content-Length”, “” + Integer.toString(urlParameters.getBytes().length));
connection.setUseCaches (false);
//WRITE PARAMETERS TO CONNECTION
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
connection.disconnect();
responseCode = connection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new Exception(“HTTP response code: ”
+ String.valueOf(responseCode));
}
try {
buffer = new StringBuffer();
input = connection.getInputStream();
dataInput = new BufferedReader(new InputStreamReader(input));
while ((line = dataInput.readLine()) != null) {
buffer.append(line);
buffer.append(“\r\n”);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace(System.err);
return null;
}
return buffer;
}
[/sourcecode]
We would pass the scoreoid url for the api as agrument for the above function. In the source code provided we are getching best scores. So url would be “https://www.scoreoid.com/api/getBestScores”
First we make the parameters string which we would pass in to the url (urlParameters). Then we open the connection. Set its properties. For our case it is POST method and Content-Type is “application/x-www-form-urlencoded”. We have to pass parameters also so we set the Content-Length to the size of the string and then write the parameters into the connection using DataOutputStream.
After this is done we check for the response. If we receive successful response (HttpURLConnection.HTTP_OK) then we read the response in a string buffer and return it.
Parse the json response
Now we just have to parse the json response. Here is the Score class which would be used store score values.
[sourcecode language=”java”]
public class Score {
public String PlayerName;
public String ScoreValue;
public long Position;
public Score(String pn,String sv){
Set(pn,sv);
}
public void Set(String pn,String sv){
PlayerName=pn;
ScoreValue=sv;
}
}
[/sourcecode]
Here is the JSON Parser class.
[sourcecode language=”java”]
List<Score> scores;
public JSONParser(){
scores=new ArrayList<Score>();
}
public List<Score> ParseScores(String response){
scores.clear();
if(response==null)
return scores;
try {
//For parsing the data just look at the content in the Scoreoid Console
//and then we can understand the structure of the return data
//We receive a json array of player scores
JSONArray json=new JSONArray(response);
for (int i = 0; i < json.length(); i++) {
//To get each player score object from the array
JSONObject jsonObject = json.getJSONObject(i);
//Inside this object we have two objects of Player and Score
//Create json object from player String
JSONObject playerobj=jsonObject.getJSONObject(“Player”);
//Retrieve the player first name
String playerFName=playerobj.getString(“first_name”);
if(playerFName.equals(“”))
playerFName=playerobj.getString(“username”);
//Create json object from score string
JSONObject scoreobj=jsonObject.getJSONObject(“Score”);
//Retrieve score
String score=scoreobj.getString(“score”);
//Create a Score object and add it in the arraylist
scores.add(new Score(playerFName, score));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return scores;
}
[/sourcecode]
It is mostly similar to the class we wrote for the Android version. There is a slight difference in reading JSON Objects from JSON Arrays. In Android version first we used to create a JSONString object for a string value(eg “Score”) and then create JSONObject using it. Here we are directly creating JSON Object using the string value (eg “Score”);
So for parsing the scores we just have to know the structure of JSON received. We receive a JSON Array and in this case we get 20 objects (as we set the limit to 20). Each object has two JSON Objects inside it (Score and Player). We get player name from Player object and score value from Score object.
For this example we are just printing the scores using Gdx log.
Source Code:
Finally the source code with all the snippets mentioned above which can be imported in eclipse workspace.
Note :- Input your Scoreoid API Key and Game ID in ScoreoidConstants.java file for the code to show some data.
When you run the example click on the trophy icon at the centre to see the scores.
If you have any query/suggestion/feeback please put it in the comments section.
Thanks
Can you post a tutorial about gwt?
Thanks for this. I will implement scoreoid with my first game.