Skip to content

Commit

Permalink
khanhpv - fix connect item in game
Browse files Browse the repository at this point in the history
  • Loading branch information
khanhpv5 committed May 17, 2024
1 parent 5e87fc4 commit 35594d1
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 93 deletions.
82 changes: 21 additions & 61 deletions packages/extension-koni-ui/src/Popup/Home/Games/gameSDK.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import { BookaSdk } from '@subwallet/extension-koni-ui/connector/booka/sdk';
import { Game } from '@subwallet/extension-koni-ui/connector/booka/types';
import { BuyInGameItemResponse, ErrorCode, GameError, GetLeaderboardRequest, GetLeaderboardResponse, HapticFeedbackType, InGameItem, Player, PlayResponse, SDKInitParams, Tournament, UseInGameItemResponse } from '@subwallet/extension-koni-ui/Popup/Home/Games/types';
import { BuyInGameItemResponse, ErrorCode, GameError, GetLeaderboardRequest, GetLeaderboardResponse, HapticFeedbackType, InGameItem, InGameItemList, Player, PlayResponse, SDKInitParams, Tournament, UseInGameItemResponse } from '@subwallet/extension-koni-ui/Popup/Home/Games/types';
import { camelCase } from 'lodash';
import z from 'zod';

Expand All @@ -14,71 +14,28 @@ export interface GameAppOptions {
onExit: () => void;
}

export const ITEM_MAP: Record<string, InGameItem> = {
BOOSTER: {
id: 'BOOSTER',
name: 'Increase Ball Number',
price: 100
},
MAGNET: {
id: 'MAGNET',
name: 'Magnet',
price: 100
},
CUP1: {
id: 'CUP1',
name: 'Cup lv 1',
price: 10
},
CUP2: {
id: 'CUP2',
name: 'Cup lv 2',
price: 20
},
CUP3: {
id: 'CUP3',
name: 'Cup lv 3',
price: 30
},
CUP4: {
id: 'CUP4',
name: 'Cup lv 4',
price: 40
},
CUP5: {
id: 'CUP5',
name: 'Cup lv 5',
price: 50
}
};

const InventoryQuantityMap: Record<string, number> = {
BOOSTER: 0,
MAGNET: 0,
CUP1: 0,
CUP2: 0,
CUP3: 0,
CUP4: 0,
CUP5: 0
};

export class GameApp {
private listener = this._onMessage.bind(this);
private options: GameAppOptions;
private viewport: HTMLIFrameElement;
private apiSDK: BookaSdk;
private currentGameInfo: Game;
private inventoryQuantityMap: Record<string, number> = {};
private gameItemInGame: { [key: string]: any } = {};

constructor (options: GameAppOptions) {
this.options = options;
this.viewport = options.viewport;
this.apiSDK = options.apiSDK;
this.currentGameInfo = options.currentGameInfo;
this.inventoryQuantityMap = this.apiSDK.gameInventoryItemInGameList;
this.gameItemInGame = this.apiSDK.gameItemInGameList;
}

start () {
// eslint-disable-next-line @typescript-eslint/no-misused-promises
window.addEventListener('message', this.listener);

}

stop () {
Expand All @@ -102,7 +59,7 @@ export class GameApp {
avatar: 'https://thispersondoesnotexist.com/',
level: 1,
energy: account?.attributes?.energy || 0,
inventory: Object.entries(InventoryQuantityMap)
inventory: Object.entries(this.inventoryQuantityMap)
.map(([id, quantity]) => ({
itemId: id,
quantity
Expand All @@ -117,7 +74,6 @@ export class GameApp {
onGetTournament (): Tournament {
const account = this.apiSDK.account;
const currentGame = this.currentGameInfo;

if (!account || !currentGame) {
throw newError('invalid account or game', errorCodes.SystemError);
}
Expand All @@ -142,8 +98,7 @@ export class GameApp {
}

onGetIngameItems () {
const items: InGameItem[] = Object.values(ITEM_MAP);

const items: InGameItem[] = Object.values(this.gameItemInGame);
return { items };
}

Expand Down Expand Up @@ -178,15 +133,15 @@ export class GameApp {
onBuyIngameItem (itemId: string, gameplayId?: string): BuyInGameItemResponse {
console.log('buy item', itemId, gameplayId);

if (!ITEM_MAP[itemId]) {
if (!this.gameItemInGame[itemId]) {
throw newError('invalid item id', errorCodes.InvalidRequest);
}

InventoryQuantityMap[itemId] = (InventoryQuantityMap[itemId] || 0) + 1;
this.inventoryQuantityMap[itemId] = (this.inventoryQuantityMap[itemId] || 0) + 1;

const res: BuyInGameItemResponse = {
receipt: Math.random().toString(),
item: ITEM_MAP[itemId]
item: this.gameItemInGame[itemId]
};

return res;
Expand All @@ -195,23 +150,28 @@ export class GameApp {
onUseIngameItem (req: {itemId: string, gameplayId?: string }): UseInGameItemResponse {
let success = false;
const { itemId } = req;
const remaining = InventoryQuantityMap[itemId] || 0;

console.log('use item', itemId);
const remaining = this.inventoryQuantityMap[itemId] || 0;

if (ITEM_MAP[itemId] && remaining > 0) {
// find object by itemId, return gameItemId;
const gameItemId = this.gameItemInGame[itemId].gameItemId;
if (this.gameItemInGame[itemId] && remaining > 0) {
success = true;
InventoryQuantityMap[itemId] = remaining - 1;
this.inventoryQuantityMap[itemId] = remaining - 1;
}

const res: UseInGameItemResponse = {
success,
inventory: Object.entries(InventoryQuantityMap).map(([id, quantity]) => ({
inventory: Object.entries(this.inventoryQuantityMap).map(([id, quantity]) => ({
itemId: id,
quantity
}))
};

console.log(itemId, res);

this.apiSDK.useInventoryItem(gameItemId);

return res;
}

Expand Down
4 changes: 4 additions & 0 deletions packages/extension-koni-ui/src/Popup/Home/Games/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,10 @@ export interface InGameItem {
name: string;
price: number;
}
export interface InGameItemList {
items: InGameItem[];
success: boolean;
}

export interface SDKInitParams {
/** default to latest version */
Expand Down
69 changes: 45 additions & 24 deletions packages/extension-koni-ui/src/connector/booka/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@

import { SWStorage } from '@subwallet/extension-base/storage';
import { createPromiseHandler } from '@subwallet/extension-base/utils';
import { InGameItem } from '@subwallet/extension-koni-ui/Popup/Home/Games/types';
import { BookaAccount, EnergyConfig, Game, GameInventoryItem, GameItem, GamePlay, LeaderboardPerson, ReferralRecord, Task, TaskCategory } from '@subwallet/extension-koni-ui/connector/booka/types';
import { TelegramConnector } from '@subwallet/extension-koni-ui/connector/telegram';
import { signRaw } from '@subwallet/extension-koni-ui/messaging';
import fetch from 'cross-fetch';
import { BehaviorSubject } from 'rxjs';

export const GAME_API_HOST = process.env.GAME_API_HOST || 'https://game-api-dev.koni.studio';
export const GAME_API_HOST = process.env.GAME_API_HOST || 'https://game-api.anhmtv.xyz';
export const TELEGRAM_WEBAPP_LINK = process.env.TELEGRAM_WEBAPP_LINK || 'BookaGamesBot/swbooka';
const storage = SWStorage.instance;
const telegramConnector = TelegramConnector.instance;
Expand All @@ -33,6 +34,8 @@ export class BookaSdk {
private referralListSubject = new BehaviorSubject<ReferralRecord[]>([]);
private gameItemMapSubject = new BehaviorSubject<Record<string, GameItem[]>>({});
private gameInventoryItemListSubject = new BehaviorSubject<GameInventoryItem[]>([]);
private gameInventoryItemInGame = new BehaviorSubject<GameInventoryItem['inventoryInGame']>([]);
private gameItemInGame = new BehaviorSubject<InGameItem>([]);;
private energyConfigSubject = new BehaviorSubject<EnergyConfig | undefined>(undefined);

constructor () {
Expand Down Expand Up @@ -117,10 +120,19 @@ export class BookaSdk {
return this.gameItemMapSubject.value;
}

public get gameItemInGameList() {
console.log(this.gameItemInGame.value)
return this.gameItemInGame.value;
}

public get gameInventoryItemList () {
return this.gameInventoryItemListSubject.value;
}

public get gameInventoryItemInGameList () {
return this.gameInventoryItemInGame.value;
}

public get leaderBoard () {
return this.leaderBoardSubject.value;
}
Expand Down Expand Up @@ -158,23 +170,20 @@ export class BookaSdk {
}
}

private async postRequest<T, U>(url: string, body: U): Promise<T> {
try {
const response = await fetch(url, {
method: 'POST',
headers: this.getRequestHeader(),
body: JSON.stringify(body),
});

if (response && response.status === 200 || response.status === 304) {
return await response.json();
} else {
const errorResponse = await response.json() as { error: string };
throw new Error(errorResponse.error || 'Bad request');
}
} catch (error) {
throw error;
private async postRequest<T> (url: string, body: any) {
const response = await fetch(url, {
method: 'POST',
headers: this.getRequestHeader(),
body: JSON.stringify(body)
});

if (!response || response.status !== 200) {
const errorResponse = await response.json() as { error: string };

throw new Error(errorResponse.error || 'Bad request');
}

return await response.json() as T;
}

private async reloadAccount () {
Expand Down Expand Up @@ -313,7 +322,8 @@ export class BookaSdk {
this.fetchTaskList(),
this.fetchLeaderboard(),
this.fetchGameItemMap(),
this.fetchGameInventoryItemList()
this.fetchGameInventoryItemList(),
this.fetchGameItemInGameList()
]);
} else {
throw new Error('Failed to sync account');
Expand Down Expand Up @@ -397,16 +407,19 @@ export class BookaSdk {
subscribeGameItemMap () {
return this.gameItemMapSubject;
}

async fetchGameInventoryItemList () {
async fetchGameInventoryItemList() {
await this.waitForSync;

const inventoryItemList = await this.getRequest<GameInventoryItem[]>(`${GAME_API_HOST}/api/shop/get-inventory`);

if (inventoryItemList) {

const inventoryResponse = await this.getRequest<{ success: boolean; inventory: GameInventoryItem[], inventoryInGame: GameInventoryItem['inventoryInGame'] }>(`${GAME_API_HOST}/api/shop/get-inventory`);

if (inventoryResponse && inventoryResponse.success) {
const inventoryItemList = inventoryResponse.inventory;
const gameInventoryItemInGame = inventoryResponse.inventoryInGame;
this.gameInventoryItemListSubject.next(inventoryItemList);
this.gameInventoryItemInGame.next(gameInventoryItemInGame);
}
}


subscribeGameInventoryItemList () {
return this.gameInventoryItemListSubject;
Expand Down Expand Up @@ -437,6 +450,14 @@ export class BookaSdk {

await this.reloadAccount();
}

async fetchGameItemInGameList () {
const gameItem = await this.getRequest<{ success: boolean, items:any }>(`${GAME_API_HOST}/api/shop/get-item-in-game`);
if(gameItem) {
console.log('gameItem', gameItem);
this.gameItemInGame.next(gameItem.items);
}
}
// --- shop

async fetchLeaderboard () {
Expand Down
23 changes: 15 additions & 8 deletions packages/extension-koni-ui/src/connector/booka/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,16 +38,23 @@ export enum GameInventoryItemStatus {
}

export interface GameInventoryItem {
id: number,
gameId: number,
accountId: number,
gameDataId: number,
gameItemId: number,
quantity: number,
usable: boolean,
itemId?: number | null
success: boolean,
inventory: {
id: number,
gameId: number,
accountId: number,
gameDataId: number,
gameItemId: number,
quantity: number,
usable: boolean,
itemId?: number | null
},
inventoryInGame: {
[key: string]: number;
}
}


export interface Game {
id: number;
contentId: number;
Expand Down

0 comments on commit 35594d1

Please sign in to comment.