Skip to content

Commit

Permalink
引入用户首选项用于存储用户最高得分
Browse files Browse the repository at this point in the history
  • Loading branch information
dividez committed Jul 4, 2024
1 parent e44f113 commit 2e9e5c2
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 13 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# HarmonyOS
# HarmonyOS 游戏开发

## About
基于[华为鸿蒙](https://developer.huawei.com/consumer/cn/sdk) HarmonyOS SDK ,ArkTS 开发的小游戏,学习鸿蒙开发。

鸿蒙Next应用 、 鸿蒙4.0开发
## Install

1.[安装最新版DevEco Studio](https://developer.huawei.com/consumer/cn/download/)
Expand Down
17 changes: 9 additions & 8 deletions features/number/src/main/ets/numberability/NumberAbility.ets
Original file line number Diff line number Diff line change
Expand Up @@ -4,38 +4,39 @@ import { window } from '@kit.ArkUI';

export default class NumberAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
hilog.info(0x0000, 'numberTag', '%{public}s', 'Ability onCreate');

}

onDestroy(): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
hilog.info(0x0000, 'numberTag', '%{public}s', 'Ability onDestroy');
}

onWindowStageCreate(windowStage: window.WindowStage): void {
// Main window is created, set main page for this ability
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
hilog.info(0x0000, 'numberTag', '%{public}s', 'Ability onWindowStageCreate');

windowStage.loadContent('pages/Index', (err) => {
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
hilog.error(0x0000, 'numberTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
hilog.info(0x0000, 'numberTag', 'Succeeded in loading the content.');
});
}

onWindowStageDestroy(): void {
// Main window is destroyed, release UI related resources
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
hilog.info(0x0000, 'numberTag', '%{public}s', 'Ability onWindowStageDestroy');
}

onForeground(): void {
// Ability has brought to foreground
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
hilog.info(0x0000, 'numberTag', '%{public}s', 'Ability onForeground');
}

onBackground(): void {
// Ability has back to background
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
hilog.info(0x0000, 'numberTag', '%{public}s', 'Ability onBackground');
}
}
65 changes: 65 additions & 0 deletions features/number/src/main/ets/services/PreferencesUtil.ets
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// 导入preferences模块。
import dataPreferences from '@ohos.data.preferences';
import { BusinessError } from '@kit.BasicServicesKit';

let context = getContext(this);
const PREFERENCES_NAME = 'fruit.db';

export default class PreferencesUtil {
private preferences: dataPreferences.Preferences | undefined = undefined;

// 调用getPreferences方法读取指定首选项持久化文件,
// 将数据加载到Preferences实例,用于数据操作
async getPreferencesFromStorage() {
console.log('context', context);
await dataPreferences.getPreferences(context, PREFERENCES_NAME).then((data) => {
this.preferences = data;
console.info(`Succeeded in getting preferences`);
}).catch((err: BusinessError) => {
console.error(`Failed to get preferences, Cause:` + err.message + ' ' + err.code);
});
}

// 将用户输入的数据,保存到缓存的Preference实例中
async putPreference(key: string, data: string) {
if (this.preferences === null) {
await this.getPreferencesFromStorage();
}

await this.preferences?.put(key, data).then(() => {
console.info(`Succeeded in putting value`);
}).catch((err: BusinessError) => {
console.error(`Failed to get preferences, Cause:` + err);
});

// 将Preference实例存储到首选项持久化文件中
await this.preferences?.flush();
}

// 使用Preferences的get方法读取数据
async getPreference(key: string) {
let result: dataPreferences.ValueType = '';
if (this.preferences === null) {
await this.getPreferencesFromStorage();
}
await this.preferences?.get(key, '').then((data) => {
result = data;
console.info(`Succeeded in getting value`);
}).catch((err: BusinessError) => {
console.error(`Failed to get preferences, Cause:` + err);
});

return result;
}

// 从内存中移除指定文件对应的Preferences单实例。
// 移除Preferences单实例时,应用不允许再使用该实例进行数据操作,否则会出现数据一致性问题。
async deletePreferences() {
await dataPreferences.deletePreferences(context, PREFERENCES_NAME).then(() => {
console.info(`Succeeded in delete preferences`);
}).catch((err: BusinessError) => {
console.error(`Failed to get preferences, Cause:` + err);
});
this.preferences = undefined;
}
}
14 changes: 11 additions & 3 deletions features/number/src/main/ets/views/NumberGameComp.ets
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { HdNav } from '@mygames/basic'
import { Board, Tile } from '../services/helper'
import { HashMap } from '@kit.ArkTS'; // 导入HashMap模块
import PreferencesUtil from '../services/PreferencesUtil';

interface InfoBuilderParams {
info: string | Resource
text: string
}

const PREFERENCES_KEY = 'number_best_score';
@Component
export struct NumberGameComp {
@State won: boolean = false;
Expand All @@ -21,7 +22,7 @@ export struct NumberGameComp {
@State lastScreenX: number = 0
@State lastScreenY: number = 0
@State imageHashMap: HashMap<string, Resource> = new HashMap();

private preferencesUtil = new PreferencesUtil();
build() {
Column({ space: 16 }) {
HdNav({ title: '2048', showRightIcon: false })
Expand Down Expand Up @@ -79,11 +80,18 @@ export struct NumberGameComp {
.borderRadius(7)
}

aboutToAppear() {
async aboutToAppear() {
console.log("aboutToAppear")
this.initImageHashMap()
this.boardCellsArray = this.board.cells;
console.log(JSON.stringify(this.boardCellsArray))
// 初始化首选项
await this.preferencesUtil.getPreferencesFromStorage();

// 获取最佳得分
this.preferencesUtil.getPreference(PREFERENCES_KEY).then(resultData => {
console.log('PREFERENCES_KEY', resultData)
});
}

reset() {
Expand Down

0 comments on commit 2e9e5c2

Please sign in to comment.