GlobalData.ts 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. import { native, sys } from "cc";
  2. export const ConfigKeys = {
  3. GameSaveData: "CarGameSaveData", // 游戏存档
  4. }
  5. // 全局变量名
  6. export const DataKeys = {
  7. status: "status", // 存放游戏状态,start,stop,pause
  8. }
  9. export class GlobalData {
  10. private static _instance: GlobalData;
  11. static get instance() {
  12. if (this._instance) {
  13. return this._instance;
  14. }
  15. this._instance = new GlobalData();
  16. this._instance.init()
  17. return this._instance;
  18. }
  19. private _data: {[key: string]: any} = {}
  20. private get data() {
  21. return this._data
  22. }
  23. public setData(key: string, value: any){
  24. this._data[key] = value
  25. }
  26. public getData(key: string){
  27. if(this._data[key] === undefined){
  28. return null
  29. }
  30. return this._data[key]
  31. }
  32. private _configData: {[key: string]: any} = {}
  33. private get configData() {
  34. return this._configData
  35. }
  36. public setConfigData(key: string, value: any){
  37. this._configData[key] = value
  38. this.save()
  39. }
  40. public getConfigData(key: string){
  41. if(this._configData[key] === undefined){
  42. return null
  43. }
  44. return this._configData[key]
  45. }
  46. path: string = ''
  47. init(){
  48. this.path = this.getConfigPath()
  49. let content;
  50. if (sys.isNative) {
  51. var valueObject = native.fileUtils.getValueMapFromFile(this.path);
  52. content = valueObject["CarConfigData"];
  53. } else {
  54. content = sys.localStorage.getItem("CarConfigData");
  55. }
  56. if (content){
  57. this._configData = JSON.parse(content) || {}
  58. }else {
  59. this._configData = {}
  60. }
  61. }
  62. public save () {
  63. // 写入文件
  64. var str = JSON.stringify(this._configData);
  65. // // 加密代码
  66. // if (cc.game.config["encript"]) {
  67. // str = new Xxtea("upgradeHeroAbility").xxteaEncrypt(str);
  68. // }
  69. // let zipStr = '@' + Util.encrypt(str);
  70. let zipStr = str;
  71. if (!sys.isNative) {
  72. var ls = sys.localStorage;
  73. ls.setItem("CarConfigData", zipStr);
  74. return;
  75. }
  76. var valueObj: any = {};
  77. valueObj["CarConfigData"] = zipStr;
  78. //@ts-ignore
  79. native.fileUtils.writeToFile(valueObj, this.path);
  80. }
  81. getConfigPath () {
  82. var platform: any = sys.platform;
  83. var path: any = "";
  84. if (platform === sys.OS.WINDOWS) {
  85. path = "src/conf";
  86. } else if (platform === sys.OS.LINUX) {
  87. path = "./conf";
  88. } else {
  89. if (sys.isNative) {
  90. path = native.fileUtils.getWritablePath();
  91. path = path + "conf";
  92. } else {
  93. path = "src/conf";
  94. }
  95. }
  96. return path;
  97. }
  98. }