Skip to content

Commit

Permalink
Fix bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
leaftail1880 committed Jan 8, 2025
1 parent aba64fe commit e41caf1
Show file tree
Hide file tree
Showing 9 changed files with 78,023 additions and 75,360 deletions.
153,199 changes: 77,896 additions & 75,303 deletions src/lib/assets/lang.ts

Large diffs are not rendered by default.

40 changes: 40 additions & 0 deletions src/lib/assets/texture-data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// prettier-ignore
/* eslint-disable */
// This file is autogenerated by script.
// Do not modify manually.

export const textureData = {
"lw:blueprint": "textures/items/blueprint",
"lw:cannon_shell": "textures/items/cannon_shell",
"lw:chip": "textures/items/chip",
"lw:circuit_board": "textures/items/circuit_board",
"lw:fireball": "textures/items/fireball",
"lw:key": "textures/blocks/trip_wire_source",
"lw:menu": "textures/items/totem",
"lw:money": "textures/items/money",
"we:brush": "textures/items/compass_item",
"we:dash": "textures/items/compass_item",
"we:debugstick": "textures/items/stick",
"we:randomizer": "textures/items/name_tag",
"we:shovel": "textures/items/shovel",
"we:tool": "textures/items/chain",
"we:wand": "textures/items/axe"
}

export const enchantData: Record<string, boolean | undefined> = {
"lw:blueprint": false,
"lw:cannon_shell": false,
"lw:chip": false,
"lw:circuit_board": false,
"lw:fireball": false,
"lw:key": true,
"lw:menu": true,
"lw:money": false,
"we:brush": true,
"we:dash": true,
"we:debugstick": true,
"we:randomizer": true,
"we:shovel": true,
"we:tool": true,
"we:wand": true
}
5 changes: 4 additions & 1 deletion src/lib/form/chest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ import { BlockPermutation, Player, RawText } from '@minecraft/server'

import { ActionFormData, ActionFormResponse } from '@minecraft/server-ui'
import { Items, totalCustomItems } from 'lib/assets/custom-items'
import { textureData } from 'lib/assets/texture-data'
import { nmspc } from 'lib/game-utils'
import { MaybeRawText, t } from 'lib/text'
import { inspect, util, wrapLore } from 'lib/util'
import { inspect, isKeyof, util, wrapLore } from 'lib/util'
import { typeIdToReadable } from 'lib/utils/lang'
import { typeIdToDataId, typeIdToID } from '../assets/chest-ui-type-ids'
import { BUTTON, showForm } from './utils'
Expand All @@ -14,6 +15,8 @@ const NUMBER_OF_1_16_100_ITEMS = totalCustomItems
const customItemsReverted: Record<string, string> = Object.map(Items, (k, v) => [v, k])
export function getAuxOrTexture(textureOrTypeId: string, enchanted = false) {
if (textureOrTypeId.startsWith('textures')) return textureOrTypeId
if (isKeyof(textureOrTypeId, textureData)) return textureData[textureOrTypeId]

if (
customItemsReverted[textureOrTypeId] ||
(textureOrTypeId.startsWith('lw:') && textureOrTypeId.includes('_spawn_egg'))
Expand Down
4 changes: 3 additions & 1 deletion src/lib/form/select-item.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Container, ContainerSlot, ItemStack, Player } from '@minecraft/server'
import { enchantData } from 'lib/assets/texture-data'
import { ChestForm } from 'lib/form/chest'
import { BUTTON } from 'lib/form/utils'
import { MaybeRawText, t } from 'lib/text'
Expand Down Expand Up @@ -45,7 +46,8 @@ function addItem(
select: OnSelect,
container: Container,
) {
const enchanted = !!item.enchantable?.getEnchantments().length
// Enchant data does not applies for the custom items becuase they don't use aux ids
const enchanted = enchantData[item.typeId] ?? !!item.enchantable?.getEnchantments().length
const nameTagPrefix = enchanted ? '§b' : ''
const lore = [...enchantmentsToLore(item, player), ...item.getLore(), ...addItemDurabilityToLore(item)]

Expand Down
72 changes: 43 additions & 29 deletions src/lib/shop/buttons/sellable-item.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { MinecraftItemTypes } from '@minecraft/vanilla-data'
import { shopFormula } from 'lib/assets/shop'
import { getAuxOrTexture } from 'lib/form/chest'
import { BUTTON } from 'lib/form/utils'
import { is } from 'lib/roles'
import { t } from 'lib/text'
import { ItemCost, MoneyCost, MultiCost } from '../cost'
import { ErrorCost, FreeCost } from '../cost/cost'
Expand All @@ -18,6 +19,8 @@ export function createSellableItem({
maxCount,
minPrice,
k,
player,
inventory,
}: {
shop: Shop
form: ShopForm
Expand All @@ -26,25 +29,33 @@ export function createSellableItem({
maxCount: number
minPrice: number
k: number
player: Player
inventory: Map<string, number>
}) {
const aux = getAuxOrTexture(type)
const db = ShopForm.database[shop.id]
const body = () =>
t.raw`Товара на складе: ${t`${db[type] ?? 0}/${maxCount}`}, ${t`${(((db[type] ?? 0) / maxCount) * 100).toFixed(2)}%%`}`
const getCount = () => Math.max(1, db[type] ?? defaultCount)
const getBuy = (count = getCount()) => {
return Math.max(1, shopFormula.formula(maxCount, count, minPrice, k))
const getCount = () => Math.max(0, db[type] ?? defaultCount)
const getBuy = (count = getCount()) => Math.max(1, shopFormula.formula(maxCount, count, minPrice, k))
const body = () => {
const storageAmount = t`${getCount()}/${maxCount}`
const filledPercent = t`${((getCount() / maxCount) * 100).toFixed(2)}%%`
return t.raw`Товара на складе: ${storageAmount}, ${filledPercent}`
}
const adminBody = () => {
return t.raw`${body()}\n\nAdmin info below\n${t`DB count: ${db[type]}\nDefault count: ${defaultCount}`}`
}
const amount = inventory.get(type) ?? 0

form.section(
itemDescription({ typeId: type, amount: 0 }),
itemDescription({ typeId: type, amount }),
(form, player) => {
form.body = body
const bodyFn = is(player.id, 'techAdmin') ? adminBody : body
form.body = bodyFn
form.section(
'§3Продать',
form => {
form.body = body
const addSell = createSell(getCount(), getBuy, type, form, db, maxCount, aux)
form.body = bodyFn
const addSell = createSell(getCount, getBuy, type, form, db, maxCount, aux)
addSell(1)
addSell(16)
addSell(32)
Expand All @@ -55,7 +66,7 @@ export function createSellableItem({
BUTTON['+'],
)

const addBuy = createBuy(getCount(), getBuy, form, type, db, aux)
const addBuy = createBuy(getCount, getBuy, form, type, db, aux)
addBuy(1)
addBuy(16)
addBuy(32)
Expand Down Expand Up @@ -86,65 +97,68 @@ export const ImpossibleBuyCost = ErrorCost(t.error`Покупка невозмо
export const ImpossibleSellCost = ErrorCost(t.error`Продажа невозможна`)

function createBuy(
dbCount: number,
getCount: () => number,
getBuy: (n: number) => number,
form: ShopFormSection,
type: MinecraftItemTypes,
db: Record<string, number | undefined>,
aux: string,
) {
return (count = 1) => {
const total = getTotal(count, i => getBuy(dbCount - i))
const cost = total <= 0 ? ImpossibleBuyCost : dbCount - count < 0 ? NoItemsToSell : new MoneyCost(total)
const dbCount = getCount()
return (buyCount = 1) => {
const finalCost = getFinalCost(buyCount, i => getBuy(dbCount - i))
const cost = finalCost <= 0 ? ImpossibleBuyCost : dbCount - buyCount < 0 ? NoItemsToSell : new MoneyCost(finalCost)

form
.product()
.name(itemDescription({ typeId: type, amount: count }))
.name(itemDescription({ typeId: type, amount: buyCount }))
.cost(cost)
.onBuy(player => {
if (!player.container) return

cost.take(player)
db[type] = Math.max(0, (db[type] ?? count) - count)
player.runCommand(`give @s ${type} ${count}`)
console.log({ count: getCount(), buyCount, a: getCount() - buyCount, db: Math.max(0, getCount() - buyCount) })
db[type] = Math.max(0, getCount() - buyCount)
player.runCommand(`give @s ${type} ${buyCount}`)
})
.setTexture(aux)
.setTakeCost(true)
.setTakeCost(false)
}
}

function createSell(
dbCount: number,
getSell: (n: number) => number,
getCount: () => number,
getBuy: (n: number) => number,
type: MinecraftItemTypes,
form: ShopFormSection,
db: Record<string, number | undefined>,
maxCount: number,
aux: string,
) {
return (count = 1) => {
const total = getTotal(count, n => getSell(dbCount + n) / 2)
const dbCount = getCount()
return (sellCount = 1) => {
const finalCost = getFinalCost(sellCount, n => getBuy(dbCount + n) / 2)
const cost = new MultiCost(
total <= 0 ? ImpossibleSellCost : count + dbCount > maxCount ? TooMuchItems : FreeCost,
new ItemCost(type, count),
finalCost <= 0 ? ImpossibleSellCost : sellCount + dbCount > maxCount ? TooMuchItems : FreeCost,
new ItemCost(type, sellCount),
)

form
.product()
.name(new MoneyCost(total).toString())
.name(new MoneyCost(finalCost).toString())
.cost(cost)
.onBuy(player => {
db[type] = Math.min(maxCount, (db[type] ?? 0) + count)
player.scores.money += total
db[type] = Math.min(maxCount, getCount() + sellCount)
player.scores.money += finalCost
})
.setTexture(aux)
.setSell(true)
}
}

function getTotal(addCount: number, adder: (n: number) => number) {
function getFinalCost(addCost: number, calculateCost: (n: number) => number) {
let total = 0
for (let i = 0; i < addCount; i++) total += adder(i)
for (let i = 0; i < addCost; i++) total += calculateCost(i)
return ~~total
}

Expand Down
22 changes: 21 additions & 1 deletion src/lib/shop/form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,8 @@ export class ShopForm {
return this
}

protected inventory?: Map<string, number>

dynamicCostItem(typeId: keyof (typeof shopFormula)['shop']): ShopForm

dynamicCostItem(typeId: MinecraftItemTypes, template: ValueOf<(typeof shopFormula)['shop']>): ShopForm
Expand All @@ -122,7 +124,25 @@ export class ShopForm {
if (isKeyof(typeId, shopFormula.shop)) template ??= shopFormula.shop[typeId]
if (!template) throw new Error('No template was provided for typeId ' + typeId)

createSellableItem({ form: this, shop: this.shop, type: typeId, ...template })
this.inventory ??= this.player.container
? [...this.player.container.entries()].reduce((acc, [, item]) => {
if (item) {
const amount = acc.get(item.typeId) ?? 0
acc.set(item.typeId, amount + item.amount)
}

return acc
}, new Map<string, number>())
: new Map<string, number>()

createSellableItem({
player: this.player,
form: this,
shop: this.shop,
inventory: this.inventory,
type: typeId,
...template,
})
return this as ShopForm
}

Expand Down
8 changes: 1 addition & 7 deletions src/lib/utils/lang.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,7 @@ export function langToken(item: { typeId: string } | string) {
* another translated RawMessage
*/
export function translateEnchantment(e: MinecraftEnchantmentTypes | Enchantment): RawText {
const rawtext: RawMessage[] = [
{
translate: langToken({
typeId: typeof e === 'string' ? e.replace('minecraft:', '') : e.type.id.replace('minecraft:', ''),
}),
},
]
const rawtext: RawMessage[] = [{ translate: langToken({ typeId: typeof e === 'string' ? e : e.type.id }) }]
if (typeof e === 'object') {
rawtext.push(
{ text: ' ' },
Expand Down
29 changes: 13 additions & 16 deletions src/modules/places/mineshaft/algo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,13 @@ export function placeOre(brokenLocation: Block, brokenTypeId: string, dimension:
if (!block || block.isAir) continue
if (!MineshaftRegion.getAt(block)) continue

const nearAir = getEdgeBlocksOf(block).some(e => {
const key = Vector.string(e)
if (!(key in airCache)) {
const block = dimension.getBlock(e)
if (block) {
airCache[key] = { block, air: !block.isSolid }
} else return true
}
const nearAir = getEdgeBlocksOf(block).some(location => {
const key = Vector.string(location)
if (key in airCache) return airCache[key].air

return airCache[key].air
const block = dimension.getBlock(location)
if (block) return (airCache[key] = { block, air: !block.isSolid }).air
else return true
})

if (nearAir) continue
Expand All @@ -57,19 +54,19 @@ export function placeOre(brokenLocation: Block, brokenTypeId: string, dimension:
const isDeepslate =
brokenOre?.isDeepslate ?? (brokenTypeId === MinecraftBlockTypes.Deepslate || brokenLocation.y < -3)

const place = (block: Block, oreTypeId: string) => {
if (block.isValid() && !block.isAir && oreTypeId) {
block.setType(oreTypeId)
return true
} else return false
}

for (const [action] of EventSignal.sortSubscribers(OrePlace)) {
const placed = action({ player, isDeepslate, brokenOre: brokenOre?.ore, possibleBlocks, place, brokenLocation })
if (placed) return
}
}

function place(block: Block, oreTypeId: string) {
if (block.isValid() && !block.isAir && oreTypeId) {
block.setType(oreTypeId)
return true
} else return false
}

interface OrePlaceEvent {
player: Player
isDeepslate: boolean
Expand Down
4 changes: 2 additions & 2 deletions src/modules/quests/learning/learning.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ class Learning {
})
})

q.item(6Вернитесь к верстаку и сделайте каменную кирку')
q.item(6Сделайте каменную кирку')
.description('Вернитесь к верстаку и улучшите свой инструмент.')
.isItem(item => item.typeId === MinecraftItemTypes.StonePickaxe)
.place(crafting)
Expand All @@ -168,7 +168,7 @@ class Learning {
ctx.subscribe(
OrePlace,
({ player, isDeepslate, possibleBlocks, place }) => {
if (player.id !== player.id) return false
if (player.id !== ctx.player.id) return false

ctx.db ??= { count: ctx.value }
;(ctx.db as { iron?: number }).iron ??= 0
Expand Down

0 comments on commit e41caf1

Please sign in to comment.