Problems understanding steamworks4j
Here is my Steam code as a SteamManager class. Maybe you can look at what I have done and customize it to your needs.
public class SteamManager extends BaseAppState implements RemoteActionListener {
private static final float TIME_BETWEEN_CALLBACKS = 0.083f; // about 12 calls per second
private static final float TIME_TO_INITIALIZE = 1f;
private SteamUtils utils;
private SteamUserStats userStats;
private SteamFriends friends;
private SteamLeaderboardHandle currentLeaderboard = null;
private SteamNetworking steamNetworking;
private boolean saveFirst;
private float currentTime = 0;
private int scoreToSave = -1;
private Map<String, Integer> statsToSave = null;
private boolean initialized = false;
private float initializeTime = 0;
private boolean statsReady = false;
private boolean overlayOpen = false;
@Override
protected void initialize(Application app) {
initializeTime = 0;
initialized = false;
statsToSave = new java.util.HashMap<>();
SignalManager.getInstance().addRemoteActionListener(this);
}
protected void initializeSteam() {
try {
SteamAPI.loadLibraries();
if (!SteamAPI.init()) {
System.out.println("))))))))))))) STEAM UNABLE TO INITIALIZE (((((((((((((");
Properties properties = new Properties();
properties.setProperty(Action.ACTION.toString(), Action.STEAM_API_ERROR.toString());
SignalManager.getInstance().sendRemoteAction(properties);
initialized = false;
initializeTime = 0;
return;
}
System.out.println("))))))))))))) STEAM SUCCESSFULLY INITIALIZED (((((((((((((");
userStats = new SteamUserStats(userStatsCallback);
friends = new SteamFriends(friendsCallback);
utils = new SteamUtils(utilsCallback);
steamNetworking = new SteamNetworking(steamNetworkingCallback);
userStats.requestCurrentStats();
Properties properties = new Properties();
properties.setProperty(Action.ACTION.toString(), Action.STEAM_API_CONNECTED.toString());
SignalManager.getInstance().sendRemoteAction(properties);
} catch (SteamException ex) {
//Handle Error here
System.out.println("))))))))))))) STEAM EXCEPTION (((((((((((((");
System.out.println("Steam exception happend: " + ex.getMessage());
Properties properties = new Properties();
properties.setProperty(Action.ACTION.toString(), Action.STEAM_API_ERROR.toString());
SignalManager.getInstance().sendRemoteAction(properties);
}
}
@Override
protected void cleanup(Application app) {
System.out.println("))))))))))))) STEAM SHUTTING DOWN (((((((((((((");
if (null != userStats) {
userStats.dispose();
userStats = null;
}
if (null != friends) {
friends.dispose();
friends = null;
}
if (null != utils) {
utils.dispose();
utils = null;
}
if (null != steamNetworking) {
steamNetworking.dispose();
steamNetworking = null;
}
SignalManager.getInstance().removeRemoteActionListener(this);
currentLeaderboard = null;
if (initialized) {
SteamAPI.shutdown();
}
}
@Override
public void update(float tpf) {
if (initialized) {
// You need to tell Steamworks to run the callbacks or you will get nothing
if (SteamAPI.isSteamRunning()) {
currentTime += tpf;
if (currentTime >= TIME_BETWEEN_CALLBACKS) {
currentTime = 0;
SteamAPI.runCallbacks();
}
}
} else {
initializeTime += tpf;
if (!initialized && initializeTime >= TIME_TO_INITIALIZE) {
initializeSteam();
initialized = true;
}
}
}
@Override
protected void onEnable() {
}
@Override
protected void onDisable() {
}
public void loadScores(String leaderboardName) {
userStats.findOrCreateLeaderboard(leaderboardName,
SteamUserStats.LeaderboardSortMethod.Descending, SteamUserStats.LeaderboardDisplayType.Numeric);
}
public void saveScores(String leaderboardName, int score) {
System.out.println("))))))))))))) STEAM SAVE LEADERBOARD (" + leaderboardName + ") SCORE: " + score + " (((((((((((((");
// This is when you want to upload the score before before getting the leaderboard
if (null != currentLeaderboard) {
userStats.uploadLeaderboardScore(currentLeaderboard, SteamUserStats.LeaderboardUploadScoreMethod.KeepBest,
score, null);
} else {
saveFirst = true;
scoreToSave = score;
userStats.findOrCreateLeaderboard(leaderboardName,
SteamUserStats.LeaderboardSortMethod.Descending, SteamUserStats.LeaderboardDisplayType.Numeric);
}
}
public void unlockAchievement(String achievementName) {
if (!statsReady) return;
if (!userStats.isAchieved(achievementName, false)) {
if (userStats.setAchievement(achievementName)) {
userStats.storeStats();
}
}
}
public void clearAchievement(String achievementName) {
if (!statsReady) return;
if (userStats == null) return;
boolean success = userStats.clearAchievement(achievementName);
if (success) {
userStats.storeStats(); //REQUIRED
}
}
public void showAchievementsUI() {
System.out.println("))))))))))))) STEAM SHOW ACHIEVEMENTS (((((((((((((");
if (friends != null) {
friends.activateGameOverlay(SteamFriends.OverlayDialog.Achievements);
}
}
public void showStatsUI() {
System.out.println("))))))))))))) STEAM SHOW STATS (((((((((((((");
if (friends != null) {
friends.activateGameOverlay(SteamFriends.OverlayDialog.Stats);
}
}
public void setStat(String statName, int value) {
if (!statsReady) {
statsToSave.put(statName, value);
return;
}
userStats.setStatI(statName, value);
userStats.storeStats();
}
public void setStat(String statName, float value) {
if (!statsReady) return;
userStats.setStatF(statName, value);
userStats.storeStats();
}
public int getStatInt(String statName) {
if (!statsReady) return 0;
return userStats.getStatI(statName, 0);
}
public float getStatFloat(String statName) {
if (!statsReady) return 0f;
return userStats.getStatF(statName, 0f);
}
public void incrementStat(String statName, int amount) {
if (!statsReady) {
if (statsToSave.containsKey(statName)) {
int current = statsToSave.get(statName);
current += amount;
statsToSave.put(statName, current);
} else {
statsToSave.put(statName, amount);
}
return;
}
int current = getStatInt(statName);
current += amount;
System.out.println(")))))))))) STEAM INCREMENT STAT (" + statName + ") NEW VALUE: " + current + " (((((((((((((");
userStats.setStatI(statName, current);
userStats.storeStats();
}
/**
* ALL CALLBACKS HAPPEN HERE
*/
private final SteamUserStatsCallback userStatsCallback = new SteamUserStatsCallback() {
@Override
public void onUserStatsReceived(long gameId, SteamID steamIDUser, SteamResult result) {
if (result == SteamResult.OK) {
System.out.println("Steam stats received successfully.");
statsReady = true;
// If we had stats to save, save them now
if (statsToSave != null) {
for (Map.Entry<String, Integer> entry : statsToSave.entrySet()) {
userStats.setStatI(entry.getKey(), entry.getValue());
System.out.println("Saving stat: " + entry.getKey() + " with value: " + entry.getValue());
}
userStats.storeStats();
statsToSave.clear();
}
} else {
System.out.println("Steam stats failed: " + result);
}
}
@Override
public void onUserStatsStored(long gameId, SteamResult result) {
if (result == SteamResult.OK) {
System.out.println("Steam stats stored successfully.");
System.out.println("))))))))))))) STEAM STAT SAVED (" + result.name() + ") (((((((((((((");
int stat = getStatInt(result.name());
Properties properties = new Properties();
properties.setProperty(Action.ACTION.toString(), Action.STATS_SUCCESS.toString());
properties.setProperty(Action.STAT_NAME.toString(), result.name());
properties.setProperty(Action.STAT_VALUE.toString(), stat + "");
SignalManager.getInstance().sendRemoteAction(properties);
} else {
System.out.println("Steam stats store failed: " + result);
Properties properties = new Properties();
properties.setProperty(Action.ACTION.toString(), Action.STATS_FAILED.toString());
properties.setProperty(Action.STAT_NAME.toString(), result.name());
SignalManager.getInstance().sendRemoteAction(properties);
}
}
@Override
public void onUserStatsUnloaded(SteamID steamIDUser) {
}
@Override
public void onUserAchievementStored(long gameId, boolean isGroupAchievement,
String achievementName, int curProgress, int maxProgress) {
System.out.println("))))))))))))) STEAM ACHIEVEMENT UNLOCKED (" + achievementName + ") (((((((((((((");
Properties properties = new Properties();
properties.setProperty(Action.ACTION.toString(), Action.ACTION_UNLOCKED_ACHIEVEMENT.toString());
properties.setProperty(Action.ACTION_ACHIEVEMENT_NAME.toString(), achievementName);
SignalManager.getInstance().sendRemoteAction(properties);
}
@Override
public void onNumberOfCurrentPlayersReceived(boolean success, int players) {
}
@Override
public void onGlobalStatsReceived(long gameId, SteamResult result) {
}
@Override
public void onLeaderboardFindResult(SteamLeaderboardHandle leaderboard, boolean found) {
if (!found) {
//<Code here when no leaderboard is found>
return;
}
currentLeaderboard = leaderboard;
if (saveFirst) {
saveFirst = false;
userStats.uploadLeaderboardScore(currentLeaderboard, SteamUserStats.LeaderboardUploadScoreMethod.KeepBest,
scoreToSave, new int[]{});
scoreToSave = -1;
} else {
performDownloadEntries(leaderboard);
}
}
@Override
public void onLeaderboardScoresDownloaded(
SteamLeaderboardHandle leaderboard,
SteamLeaderboardEntriesHandle entries,
int numEntries) {
if (numEntries <= 0) return;
int[] details = new int[16];
for (int i = 0; i < numEntries; i++) {
SteamLeaderboardEntry entry = new SteamLeaderboardEntry();
if (userStats.getDownloadedLeaderboardEntry(entries, i, entry, details)) {
String playerName = friends.getFriendPersonaName(entry.getSteamIDUser());
int score = entry.getScore();
int rank = entry.getGlobalRank();
System.out.println(rank + ". " + playerName + " - " + score);
// Send to your UI system here
}
}
}
@Override
public void onLeaderboardScoreUploaded(boolean success, SteamLeaderboardHandle leaderboard, int score,
boolean scoreChanged, int globalRankNew, int globalRankPrevious) {
// You can check for success or not if you want
performDownloadEntries(leaderboard);
}
private void performDownloadEntries(SteamLeaderboardHandle leaderboard) {
SteamUserStats.LeaderboardDataRequest request =
SteamUserStats.LeaderboardDataRequest.GlobalAroundUser;
userStats.downloadLeaderboardEntries(
leaderboard,
request,
-10, // 10 above user
10 // 10 below user
);
}
};
private final SteamFriendsCallback friendsCallback = new SteamFriendsCallback() {
@Override
public void onSetPersonaNameResponse(boolean success, boolean localSuccess, SteamResult result) {
}
@Override
public void onPersonaStateChange(SteamID steamID, SteamFriends.PersonaChange change) {
}
@Override
public void onGameOverlayActivated(boolean active) {
// Pay Close attention...
// You MUST pause the game when the overlay appears ot your app will be rejected
if (active) {
System.out.println("))))))))))))) STEAM OVERLAY ACTIVATED (((((((((((((");
overlayOpen = true;
} else {
System.out.println("))))))))))))) STEAM OVERLAY DEACTIVATED (((((((((((((");
overlayOpen = false;
}
getApplication().enqueue(() -> {
if (active) {
pauseGameForSteamOverlay();
}
});
}
private void pauseGameForSteamOverlay() {
Properties properties = new Properties();
properties.setProperty(Action.ACTION.toString(), Action.PAUSE.toString());
SignalManager.getInstance().sendRemoteAction(properties);
}
@Override
public void onGameLobbyJoinRequested(SteamID steamIDLobby, SteamID steamIDFriend) {
}
@Override
public void onAvatarImageLoaded(SteamID steamID, int image, int width, int height) {
}
@Override
public void onFriendRichPresenceUpdate(SteamID steamIDFriend, int appID) {
}
@Override
public void onGameRichPresenceJoinRequested(SteamID steamIDFriend, String connect) {
}
@Override
public void onGameServerChangeRequested(String server, String password) {
}
};
private final SteamUtilsCallback utilsCallback = new SteamUtilsCallback() {
@Override
public void onSteamShutdown() {
// Check when steam is down
System.out.println("))))))))))))) STEAM SHUTDOWN (((((((((((((");
}
};
private final SteamNetworkingCallback steamNetworkingCallback = new SteamNetworkingCallback() {
@Override
public void onP2PSessionConnectFail(SteamID steamIDRemote, SteamNetworking.P2PSessionError sessionError) {
}
@Override
public void onP2PSessionRequest(SteamID steamIDRemote) {
}
};
@Override
public String doAction(Properties properties) {
if (properties != null) {
String action = properties.getProperty(Action.ACTION.toString());
if (action != null) {
if (action.equals(Action.ACTION_ADD_SCORE.toString())) {
String scoreStr = properties.getProperty(Action.SCORE.toString());
if (scoreStr != null && !scoreStr.equals("")) {
long score = Long.parseLong(scoreStr);
String leaderboard = properties.getProperty(Action.LEADERBOARD.toString());
saveScores(leaderboard, (int) score);
}
} else if (action.equals(Action.ACTION_SAVE_STATS.toString())) {
String statStr = properties.getProperty(Action.STAT_VALUE.toString());
if (statStr != null && !statStr.equals("")) {
int val = Integer.parseInt(statStr);
String statName = properties.getProperty(Action.STAT_NAME.toString());
incrementStat(statName, val);
}
} else if (action.equals(Action.ACTION_GET_STATS.toString())) {
String name = properties.getProperty(Action.STAT_NAME.toString());
if (name != null && !name.equals("")) {
int val = getStatInt(name);
System.out.println(")))))))))))) STEAM GET STAT (" + name + ") VALUE: " + val + " (((((((((((((");
Properties p = new Properties();
p.setProperty(Action.ACTION.toString(), Action.STATS_SUCCESS.toString());
p.setProperty(Action.STAT_NAME.toString(), name);
p.setProperty(Action.STAT_VALUE.toString(), val + "");
SignalManager.getInstance().sendRemoteAction(p);
}
} else if (action.equals(Action.ACTION_CLEAR_STATS.toString())) {
String statStr = properties.getProperty(Action.STAT_NAME.toString());
if (statStr != null && !statStr.equals("")) {
setStat(statStr, 0);
}
} else if (action.equals(Action.ACTION_GET_ACHIEVEMENTS.toString())) {
showAchievementsUI();
} else if (action.equals(Action.ACTION_UNLOCK_ACHIEVEMENT.toString())) {
String achievementName = properties.getProperty(Action.ACTION_ACHIEVEMENT_NAME.toString());
unlockAchievement(achievementName);
} else if (action.equals(Action.ACTION_CLEAR_ACHIEVEMENT.toString())) {
String achievementName = properties.getProperty(Action.ACTION_ACHIEVEMENT_NAME.toString());
clearAchievement(achievementName);
}
}
}
return null;
}
}