LocalStorage.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. var PREFS_FILE = "SpaceGameMultiPlayer.json";
  2. var filesystem = Atomic.getFileSystem();
  3. // Get out documents folder
  4. var documentsDir = filesystem.getUserDocumentsDir();
  5. var prefFilePath = documentsDir + PREFS_FILE;
  6. function LocalStorage() {
  7. print('In LocalStorage constructor');
  8. }
  9. function getJSONPrefData() {
  10. if (filesystem.fileExists(prefFilePath)) {
  11. var file = new Atomic.File(prefFilePath, Atomic.FILE_READ);
  12. // Read the data string and parse the JSON back to an object
  13. var fileData = file.readString();
  14. var json = JSON.parse(fileData);
  15. return json;
  16. }
  17. return {};
  18. }
  19. LocalStorage.prototype.setServerName = function(serverName) {
  20. var mydata = getJSONPrefData();
  21. mydata.server_name = serverName;
  22. var file = new Atomic.File(prefFilePath, Atomic.FILE_WRITE);
  23. // Convert the data object to a string and write it
  24. file.writeString(JSON.stringify(mydata));
  25. // close the file
  26. file.close();
  27. }
  28. LocalStorage.prototype.getServerName = function() {
  29. var json = getJSONPrefData();
  30. if (json.server_name) {
  31. return json.server_name;
  32. }
  33. return "Server";
  34. }
  35. LocalStorage.prototype.setPlayerName = function(playerName) {
  36. var mydata = getJSONPrefData();
  37. mydata.player_name = playerName;
  38. var file = new Atomic.File(prefFilePath, Atomic.FILE_WRITE);
  39. // Convert the data object to a string and write it
  40. file.writeString(JSON.stringify(mydata));
  41. // close the file
  42. file.close();
  43. }
  44. LocalStorage.prototype.getPlayerName = function() {
  45. var json = getJSONPrefData();
  46. if (json.player_name) {
  47. return json.player_name;
  48. }
  49. return "Player";
  50. }
  51. Atomic.localStorage = exports.localStorage = new LocalStorage();