DataModel.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. import { _decorator, Component, Node, game, director, sys } from 'cc';
  2. import { EventDispatcher } from '../events/EventDispatcher';
  3. import { DataModelEventType } from './DataModelEventType';
  4. const { ccclass, property } = _decorator;
  5. export class DataModel extends EventDispatcher {
  6. private propertys:Map<string,any>=new Map<string,any>();
  7. /**
  8. * 是否是新玩家
  9. */
  10. public isNewPlayer:boolean;
  11. constructor(){
  12. super();
  13. }
  14. /**
  15. * 游戏名称
  16. */
  17. public get gameName():string{
  18. return this.GetProperty("gameName");
  19. }
  20. public set gameName(value:string){
  21. this.SetProperty("gameName",value);
  22. }
  23. /**
  24. * 用户ID
  25. */
  26. public get userId():string{
  27. return this.GetProperty("userId");
  28. }
  29. public set userId(value:string){
  30. this.SetProperty("userId",value);
  31. }
  32. /**
  33. * 设置属性
  34. * @param key
  35. * @param value
  36. */
  37. public SetProperty(key:string,value:any):void{
  38. if(this.propertys.has(key)){
  39. let oldValue:any=this.propertys.get(key);
  40. if(oldValue==value){
  41. return;
  42. }
  43. }
  44. this.propertys.set(key,value);
  45. this.DispatchEvent(DataModelEventType.PROPERTY_CHANGED,key);
  46. }
  47. /**
  48. * 获取属性
  49. * @param key
  50. */
  51. public GetProperty(key:string):any{
  52. if(this.propertys.has(key)){
  53. return this.propertys.get(key);
  54. }
  55. return null;
  56. }
  57. /**
  58. * 清空游戏本地数据
  59. */
  60. ClearLocalData():void{
  61. localStorage.clear();
  62. }
  63. /**
  64. * 保存到本地
  65. */
  66. SaveToLoacl():void{
  67. console.log(JSON.stringify(this.propertys));
  68. var arr=Array.from(
  69. this.propertys.entries()
  70. )
  71. .reduce((o, [key, value]) => {
  72. o[key] = value;
  73. return o;
  74. }, {})
  75. localStorage.setItem(this.gameName+"_"+this.userId,JSON.stringify(arr));
  76. }
  77. /**
  78. * 从本地读取数据
  79. */
  80. ReadByLocal():void{
  81. let jsonStr:string=localStorage.getItem(this.gameName+"_"+this.userId);
  82. if(jsonStr==null){
  83. this.isNewPlayer=true;
  84. }else{
  85. try {
  86. let jsonData:any=JSON.parse(jsonStr);
  87. for (const key in jsonData) {
  88. if (Object.prototype.hasOwnProperty.call(jsonData, key)) {
  89. const element = jsonData[key];
  90. this.SetProperty(key,element);
  91. }
  92. }
  93. this.isNewPlayer=false;
  94. } catch (error) {
  95. console.log("读取本地数据失败")
  96. this.isNewPlayer=true;
  97. }
  98. }
  99. if(this.isNewPlayer){
  100. this.SetDefaultPropertys();
  101. }
  102. }
  103. /**
  104. * 设置默认属性
  105. */
  106. SetDefaultPropertys():void{
  107. }
  108. }