#๐Ÿ”’ JSON Saving makes no sense.

1622 messages ยท Page 2 of 2 (latest)

sharp cosmos
#

and then this entire class thing began

river void
#

But it's inherently a number

sharp cosmos
#

btw golf

inland atlas
sharp cosmos
#

ya think going down this route to eventually show him dataclasses is good ? pithink

inland atlas
#

i will apply everything that ive learnt

river void
inland atlas
sharp cosmos
inland atlas
#

one part of my code is json

#

rest is normal py

river void
#

If you want something robust you need to hook into json.load/json.save directly

inland atlas
sharp cosmos
#

part of it ig

inland atlas
#

im searching them up

sharp cosmos
inland atlas
#

yes

sharp cosmos
#

the Item class could have been a dataclass

#

as an example

#

since all its doing is holding data

inland atlas
#

.

sharp cosmos
#

!e

from dataclasses import dataclass

@dataclass
class Item:
    name: str
    count: int

class Inventory:
    def __init__(self):
        self.items = []

    def add_item(self, item, count):
        new_item = Item(item, count)
        self.items.append(new_item)
        
    def remove_item(self, name, count):
        for item in self.items:
            if item.name == name:
                item.count -= count


inv = Inventory()

inv.add_item("log", 99)
print(inv.items[0])

inv.remove_item("log", 10)
print(inv.items[0])
warm runeBOT
sharp cosmos
#

since all its doing is holding data, this is much simpler pithink

inland atlas
#

yk

#

i have additional logic for removing, adding etc..
this dosent cut it, but still, im looking into it
might need some time

sharp cosmos
#

dont rush it

inland atlas
#

i never rush thingspithink

sharp cosmos
inland atlas
sharp cosmos
#

u said this multiplayer

inland atlas
#

the whole game is player related

sharp cosmos
#

let every player instance have its own inventory

#

know a better way ? pithink

inland atlas
#

every action either removes something from p.json or adds

#

its constntly getting edited

inland atlas
#

thats why player.json is not called player.json
its called UUID.json

#

uuid replaced with the players id

#

like this

sharp cosmos
#
class Player:
    def __init__(self):
        self.UUID = ...
        self.inventory = Inventory()
    
    def gather_fish(self):
        # do fishing action here 
sharp cosmos
#

just organizes every Player related thing there so its easier and simpler

inland atlas
#

what is inventory()

sharp cosmos
#

some inventory class

#

like one i showed u as an example

#

inventory classes are very useful cause they can be a player inventory or a chest inventory or a backpack inventory

#

doesnt matter

#

its an inventory

inland atlas
#

i have coded the logic for gathering wood and stone, do you want to see them to get a better understanding of what they are and how they work?

sharp cosmos
#

if u were to gather_fish() u would add the gathered fish to self.inventory

#

simple

inland atlas
#

i havent made fish yet

sharp cosmos
#

was just an example

inland atlas
inland atlas
#
import random
from data import loadJson, loadPlayerData, saveJson
from inventory import inventoryActionHandler

gathers = loadJson("gathers.json")

def rollChance(num):
    if isinstance(num, int):
        roll = random.randint(0, 100)
    elif isinstance(num, float):
        roll = random.uniform(0, 100)
    return roll <= num

def numberRandomizer(num1, num2):
    return random.randint(num1, num2)

def weightRandomizer(dicts):
    items = list(dicts.keys())
    weights = list(dicts.values())
    selected = random.choices(items, weights)[0]
    return selected

def extractWeights(gather):
    weights = {}
    for mats, datas in gathers[gather].items():
        weight = float(datas['weight'])
        weights[mats] = weight
    return weights

def damageGather(player, gather):
    data = loadPlayerData(player)
    data2 = data["gather"][gather]
    material = list(data2.keys())[0]
    health = int(list(data2.values())[0])
    damage = 4

    while damage > 0:
        print(material)
        print(health)
        print(damage)
        if damage <= health:
            health -= damage
            damage = 0
            data["gather"][gather] = {material: str(health)}
            saveJson((f"{player}.json"), data)
        else:
            damage -= health
            health = 0
            giveDrops(player, gather, material)
            print('gave drops!')
            material, health = generateGather(gather)
    
def generateGather(gather):
    material = weightRandomizer(extractWeights(gather))
    matdata = gathers[gather][material]
    health = int(matdata["damage"])
    icon = matdata["icon"]
    return material, health

def giveDrops(player, gather, material):
    drops = gathers[gather][material]["drops"]
    for item, details in drops.items():
        if rollChance(details.get("chance")):
            quantity = numberRandomizer(details.get("min"), details.get("max"))
            inventoryActionHandler("add", player, "inventory", item, quantity)```
#

it starts at damageGather

#
{
    "foraging": {
        "deciduous": {
            "icon": "๐ŸŒณ",
            "weight": "0.6",
            "damage": "34",
            "drops": {
                "log": {
                    "min": 2,
                    "max": 3,
                    "chance": 100
                },
                "green leaves": {
                    "min": 2,
                    "max": 5,
                    "chance": 100
                }
            }
        },"palm": {
            "icon": "๐ŸŒด",
            "weight": "0.3",
            "damage": "36",
            "drops": {
                "log": {
                    "min": 3,
                    "max": 5,
                    "chance": 100
                },
                "green leaves": {
                    "min": 1,
                    "max": 3,
                    "chance": 80
                }
            }
        },"pine": {
            "icon": "๐ŸŒฒ",
            "weight": "0.1",
            "damage": "42",
            "drops": {
                "log": {
                    "min": 4,
                    "max": 6,
                    "chance": 100
                },
                "green leaves": {
                    "min": 4,
                    "max": 7,
                    "chance": 100
                }
            }
        }
    },
    "mine": {}
}

this is gathers.json mentioned in the code above

sharp cosmos
inland atlas
#

i see

sharp cosmos
#

just have a material have its own health, damage(), get_drops(), etc.

#

and inside generate_gather just make a new material using said class

sharp cosmos
#

why is ur material health named damage

#

in this json

inland atlas
sharp cosmos
#

so change it to health

inland atlas
#

i will

sharp cosmos
#

have damage be something in Player class

#

or watever

#

i need to warn u tho

inland atlas
#

dmg attribute is on item

sharp cosmos
#

damage calculations can get quite hectic

sharp cosmos
inland atlas
#

i wont use float

sharp cosmos
#

have item that player is holding on player class

#

and just reference player.held_item.dmg

#

or something

inland atlas
#

yes will do that

sharp cosmos
#

anyways u get point of using classes everywhere to simplify

#

hopefully

inland atlas
#

i did

#

im brainstorming on how to make the player class

sharp cosmos
#

put draw.io in ur browser and hit enter

inland atlas
#

i use paper

sharp cosmos
#

u can make a quick lil diagram there on how u envision it

sharp cosmos
inland atlas
#

ive learnt so much today

#

is there anything else to learn? ๐Ÿ˜„

#

i better say is there anything else you'd like to teach me?

sharp cosmos
#

i showed u a quick example dont know if u recall

inland atlas
#

what i meant was
class parent:

class child(parent):

sharp cosmos
#

if u want a quick useful example of this

inland atlas
#

yes, didnt mean to write"inside"

sharp cosmos
#

imagine u got a base item class thats just like name and count

#

now we can make a class tool that inherits from item

#

change being it now has a damage attribute too

#

cool ? pithink

inland atlas
#

yea cool

#

so in parent class the item has name, count, in child it also has dmg

sharp cosmos
#

ye

inland atlas
#

im getting the hang of it'

sharp cosmos
#

also if parent has lets say def some_method()

#

if child also implements that

#

it overrides

#

u can still call the parent's method but it would be done manually

inland atlas
#

a function inside a class is called a method, asking to make sure

sharp cosmos
#

!e

class Parent:
    def a(self):
        print(4)

class Child(Parent):
    def a(self):
        print(5)

c = Child()

c.a()
warm runeBOT
sharp cosmos
#

!e

class Parent:
    def a(self):
        print(4)

class Child(Parent):
    def a(self):
        super().a()
        print(5)

c = Child()

c.a()
warm runeBOT
sharp cosmos
#

and if Child didnt have a method it would just use the parent's which in this case is Parent

inland atlas
#

understood

#

whats super()

sharp cosmos
#

a way to dynamically access a parent class

inland atlas
#

ah, you call the a in parent with super

sharp cosmos
#

super() in this case would be Parent yes

inland atlas
#

understood

sharp cosmos
#

just fyi super is in that part of "dont worry about how it works, it works like this"

#

so let this simple usage and demonstration of super() be what u know

inland atlas
#

sure

#

one thing

sharp cosmos
#

?

inland atlas
#
def damageGather(player, gather):
    data = loadPlayerData(player)
    data2 = data["gather"][gather]
    material = list(data2.keys())[0]
    health = int(list(data2.values())[0])
    damage = 4

    while damage > 0:
        print(material)
        print(health)
        print(damage)
        if damage <= health:
            health -= damage
            damage = 0
            data["gather"][gather] = {material: str(health)}
            saveJson((f"{player}.json"), data)
        else:
            damage -= health
            health = 0
            giveDrops(player, gather, material)
            print('gave drops!')
            material, health = generateGather(gather)```
#

remember this, it created the "revert" jsonsave bug

#

because we used savejson twice

#

now, if i use my new save class that saves data

#

wont i still run into the same bug?
sure its saving one time, but its saving 2 different datas at the same time

#

one data for ["storage]["inventory]

#

one for ["gather

sharp cosmos
#

did u change save change save

#

or did u change change save

inland atlas
#

ah

#

youre refering to the order

#

change change save

sharp cosmos
#

so it shouldnt run into same bug

#

try it

inland atlas
#

alright

sharp cosmos
#

unless u assigned stuff and overwrote it that way

inland atlas
#

i was resting till now, ima go write the data class or something

#

can i get a quick tip on how to orgenise my classes

#

by that i mean, you mentioned a player and another inventory class

#

if the inventory class is for inventory stuff

#

then what is the player one for

sharp cosmos
#

for player stuff

#

if player starts fishing minigame

#

call go_fish method on that player object

inland atlas
#

good idea

sharp cosmos
#

player catches a fish during that ? great

#

now add fish to that player object inventory

inland atlas
#

great

sharp cosmos
#

fish rotted ? well shit, lets remove that fish from that player object inventory cause it stinks

#

u get idea hopefully

inland atlas
#

so, datasaving/loading class should be seprate from inventory

sharp cosmos
inland atlas
#

utility class?

sharp cosmos
#

maybe a wrapper or decorator for player/inventory to be able to more easily use it

sharp cosmos
#

in this case saving/loading to/from json

inland atlas
#

understood

#

i will go and code the data classes and all those stuff

sharp cosmos
#

in my utils of current project i just have this thing

#

def splice_byte_data(data, sizes, shift = 0):
    index = 0
    spliced = []

    for size in sizes:
        new_index = index + size

        spliced.append(data[shift + index:shift + new_index])

        index = new_index

    return spliced
#

for example

#

its just nice to have to not need to remake it everywhere ya know

inland atlas
#

i guess this is my entire player data loading and saving class

sharp cosmos
inland atlas
#

yes

#

you mean like

#

player(self.data)?

#

something like this?

#

have we passed it yet?

sharp cosmos
#

nah its like 1200

#

rn

inland atlas
#

what was the other thread like?

sharp cosmos
sharp cosmos
sharp cosmos
inland atlas
#

im struggling to find the right way of using classess, after making them.

#

#saveJson((f"{player}.json"), data)
(PlayerData((f"{player}.json"), data)).save()

#

i replaced the line above, with the one below it

sharp cosmos
#

u wanna shove the created playerdata object into a variable

#

then call .save() on that variable

sharp cosmos
inland atlas
#

im just asking if i did it right or not

sharp cosmos
#

well whats data u passing to it ?

inland atlas
#
def inventoryActionHandler(action, player, storage, item, quantity):
    data = (PlayerData(player)).load()
    path = data["storage"][storage]
    if action == 'add':
        addItem(path, item, quantity)
    elif action == 'remove':
        removeItem(path, item, quantity)
    elif action == 'craft':
        craft_item(path, item, quantity)
    data["storage"][storage] = path
    #saveJson((f"{player}.json"), data)
    (PlayerData((f"{player}.json"), data)).save()
#

i know i did the loading part wrong, ignore that

sharp cosmos
#

data = PlayerData(player)

#

this part is good

inland atlas
#

fixed it

inland atlas
sharp cosmos
#

u could have done data.load() in line right under it

inland atlas
#

ik

#

im more stuck on the saving part of things

#

loading is a breeze for me

sharp cosmos
#

saving is the same logic

#

just .save() rather than .load()

#

waht im trying to get u to understand is that we only need to create 1 object here pithink

#
def inventoryActionHandler(action, player, storage, item, quantity):
    playerdata = PlayerData(player)  #  this is good
    playerdata.load()                #  now its loaded
    path = playerdata.data["storage"][storage] # and data insdie it can be used since its loaded
    if action == 'add':
        addItem(path, item, quantity)
    elif action == 'remove':
        removeItem(path, item, quantity)
    elif action == 'craft':
        craft_item(path, item, quantity)
    data["storage"][storage] = path  # now here we would want to set data inside data variable then save
    

    #saveJson((f"{player}.json"), data)
    (PlayerData((f"{player}.json"), data)).save()
inland atlas
#

TypeError: 'PlayerData' object is not subscriptable

#

what is this

sharp cosmos
#

playerdata being the object of Playerdata class u wrote

inland atlas
#

yes i realized, but keep explaining

sharp cosmos
#

we want to do ["storage"] on actual data

#

not the object itself

#

the data should be inside the object

#

just a matter of accessing it

inland atlas
#

wait its not the same part, still tho

sharp cosmos
#

point was showcasing how first 3 lines are done

#

and pointing out how to fix 4

inland atlas
#

so

sharp cosmos
#

and completely ignoring bottom 2 for now

inland atlas
#

datas.data

sharp cosmos
inland atlas
#

okay so

#

it works, but still same revert issue as before ๐Ÿ˜„

sharp cosmos
#

so show what u did

inland atlas
#

im gonna try fixing it myself

sharp cosmos
#

also fair

inland atlas
#

because i created 2 objects and i know i shouldnt do that

<data.PlayerData object at 0x000001BAE6E53050>
The file '1129110869.json' already exists.
<data.PlayerData object at 0x000001BAE72B0D60>

#

but i dont know how to make it 1 object

#
def damageGather(player, gather):

    datas = PlayerData(player)
    datas.load()
    data2 = datas.data["gather"][gather]
    material = list(data2.keys())[0]
    health = int(list(data2.values())[0])
    damage = 4

    while damage > 0:
        print(material)
        print(health)
        print(damage)
        if damage <= health:
            health -= damage
            damage = 0
            datas.data["gather"][gather] = {material: str(health)}
            (PlayerData((f"{player}.json"), datas.data)).save()
        else:
            damage -= health
            health = 0
            giveDrops(player, gather, material)
            print('gave drops!')
            material, health = generateGather(gather)
sharp cosmos
#

this line is sole issue

#

everything else is good pithink

#

whats our playerdata object here ?

inland atlas
sharp cosmos
#

cause it should run pithink

inland atlas
#

it will run

#

it wont work

sharp cosmos
#

ye

#

cause its never saving

#

anyways

sharp cosmos
#

its very simple]

#

use that objetc u made to save

#

rather than creating a new one

inland atlas
sharp cosmos
inland atlas
#

do i need to use like the obj id that looks like this?
<data.PlayerData object at 0x000001BAE6E53050>

inland atlas
sharp cosmos
#

just use the variable like u would any other

#

datas pithink

inland atlas
#

so the var datas

inland atlas
# inland atlas ```py def damageGather(player, gather): datas = PlayerData(player) data...
def inventoryActionHandler(action, player, storage, item, quantity):
    datas = PlayerData(player)
    datas.load()
    print(datas)
    path = datas.data["storage"][storage]
    if action == 'add':
        addItem(path, item, quantity)
    elif action == 'remove':
        removeItem(path, item, quantity)
    elif action == 'craft':
        craft_item(path, item, quantity)
    datas.data["storage"][storage] = path
    #saveJson((f"{player}.json"), data)
    (PlayerData((f"{player}.json"), datas.data)).save()```

its named datas in both places, how can i make it use the same obj? cant think of any other way
sharp cosmos
#

u overcomplicating the hell out of this

#

u can just do datas.save() pithink

inland atlas
#

i think i figured, lets see

inland atlas
sharp cosmos
inland atlas
#

yes

sharp cosmos
#

what is error then ?

inland atlas
#

OSError: [WinError 6] The handle is invalid

sharp cosmos
#

k welp thats not helpful

#

can u re-send the playerdata class

inland atlas
#

heres traceback

Traceback (most recent call last):
  File "C:\Users\R\AppData\Local\Programs\Python\Python313\Lib\site-packages\telethon\client\updates.py", line 570, in _dispatch_update
    await callback(event)
  File "C:\Users\R\Desktop\New folder\main.py", line 39, in callback
    damageGather(sender, "foraging")
    ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\R\Desktop\New folder\gather.py", line 47, in damageGather
    datas.save()
    ~~~~~~~~~~^^
  File "C:\Users\R\Desktop\New folder\data.py", line 27, in save
    saveJson(self.player, self.data)
    ~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\R\Desktop\New folder\data.py", line 7, in saveJson
    with open(name, "w") as file:
         ~~~~^^^^^^^^^^^```
sharp cosmos
#

i always lose it high above

inland atlas
#
import json

def loadJson(name):
    with open(name, "r", encoding='utf-8') as file:
        return json.load(file)
def saveJson(name, data):
    with open(name, "w") as file:
        json.dump(data, file, indent=4)

class PlayerData:
    def __init__(self, player, data=None):
        self.player = player
        self.data = data
        
    def load(self):
        inv_file = f"{self.player}.json"
        preset = loadJson("inv.json")
        try:
            with open(inv_file, 'x') as file:
                json.dump(preset, file, indent=4)
                print(f"The file '{inv_file}' has been created.")
        except FileExistsError:
            print(f"The file '{inv_file}' already exists.")
        self.data = loadJson(inv_file)

    def save(self):
        saveJson(self.player, self.data)

sharp cosmos
#

ye

#

issue is in class

#

not object

sharp cosmos
#

why ?

inland atlas
#

it still saves

sharp cosmos
#

but only if u have self.player as a valid .json filename

#

which then it wont load

#

cause it would be .json.json

inland atlas
#

but it still loads

sharp cosmos
#

but only if u have just filename

#

which then it wont save

#

cause it wouldnt be .json

inland atlas
#

im getting this "but it still loads" and "it still saves" from it working, but with the revert bug

#

which means it both loads and saves

sharp cosmos
#

but change class

river void
river void
#

hi

river void
#

I'm back from doing homework lol

inland atlas
sharp cosmos
river void
#

what does self.player contain?

sharp cosmos
#

name.json or just name

sharp cosmos
inland atlas
#

name.json

sharp cosmos
river void
# inland atlas name.json

if it already contains the .json then use it directly
if it doesn't, add it with the fstring (or other methods)

inland atlas
sharp cosmos
inland atlas
#

    datas = PlayerData(player)
    datas.load()
    data2 = datas.data["gather"][gather]
    material = list(data2.keys())[0]
    health = int(list(data2.values())[0])
    damage = 4

    while damage > 0:
        print(material)
        print(health)
        print(damage)
        if damage <= health:
            health -= damage
            damage = 0
            datas.data["gather"][gather] = {material: str(health)}
            datas.save()
        else:
            damage -= health
            health = 0
            giveDrops(player, gather, material)
            print('gave drops!')
            material, health = generateGather(gather)```
warm runeBOT
#

Hey @inland atlas!

Please edit your message to use a code block

Add a py after the three backticks.

```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
inland atlas
#

inventoryAction dosent have a save, as you said.

river void
inland atlas
#

its not

#

UUID is int

sharp cosmos
#

wait why ur uuid an int i just realized

river void
#

oh, I thought you meant a UUID string

sharp cosmos
#

i jsut accepted it but like

sharp cosmos
river void
#

I mean, it's just a 128bit number

inland atlas
#

it has to be, im using another app to authorize players, and it only has int uuids + its easier for me

sharp cosmos
#

fair

river void
#

in that case I would at least convert it to a hex string

inland atlas
#

it needs to be the number it is, easier for me to edit code

river void
#

for the save file, I mean

inland atlas
#

hex uuid .json you mean?

river void
#

yeah

inland atlas
#

thats exactly why i want it to be int

river void
#

something like f"{self.player:016x}.json" off the top of my head

inland atlas
#

nah

#

useless conversation tho, i dont the type matters

#

dagger

river void
#

I'm not talking about self.player itself

inland atlas
#

let me explain why i put 1 save in invAction and one in damageGathers

river void
#

that can be an int

#

but when you save stuff to a file the filename has to be strings

inland atlas
sharp cosmos
#

can u show invaction function thats also saving

river void
#

you also need the .json file extension

inland atlas
#
def inventoryActionHandler(action, player, storage, item, quantity):
    datas = PlayerData(player)
    datas.load()
    print(datas)
    path = datas.data["storage"][storage]
    if action == 'add':
        addItem(path, item, quantity)
    elif action == 'remove':
        removeItem(path, item, quantity)
    elif action == 'craft':
        craft_item(path, item, quantity)
    datas.data["storage"][storage] = path
    #saveJson((f"{player}.json"), data)
    #(PlayerData((f"{player}.json"), datas.data)).save()```
#

invActioon

#

the invaction saves the drops you get from making a trees health down to 0

#

thats why it needs a save

sharp cosmos
#

so invaction is calling damagegather ?

inland atlas
#

and the other save in damageGather saves the players progression on how much dmg they have dealth to the current tree

inland atlas
#

dmg is calling inv

#

let me show u full code

#
def damageGather(player, gather):

    datas = PlayerData(player)
    datas.load()
    data2 = datas.data["gather"][gather]
    material = list(data2.keys())[0]
    health = int(list(data2.values())[0])
    damage = 4

    while damage > 0:
        print(material)
        print(health)
        print(damage)
        if damage <= health:
            health -= damage
            damage = 0
            datas.data["gather"][gather] = {material: str(health)}
            datas.save()
        else:
            damage -= health
            health = 0
            giveDrops(player, gather, material)
            print('gave drops!')
            material, health = generateGather(gather)
    
def generateGather(gather):
    material = weightRandomizer(extractWeights(gather))
    matdata = gathers[gather][material]
    health = int(matdata["damage"])
    icon = matdata["icon"]
    return material, health


def giveDrops(player, gather, material):
    drops = gathers[gather][material]["drops"]
    for item, details in drops.items():
        if rollChance(details.get("chance")):
            quantity = numberRandomizer(details.get("min"), details.get("max"))
            inventoryActionHandler("add", player, "inventory", item, quantity)```
#

see giveDrops

#

that calls invaction

#

givedrops is called by dmg

sharp cosmos
#

this would be so much simpler with an inventory/player class

#

uh

#

time to stare at this

inland atlas
#

its easy dont worry

inland atlas
inland atlas
#

i love how we are still on the exact topic that this thread was made for, 1400messages later.

sharp cosmos
inland atlas
#

mb ๐Ÿ˜„

#

atleast im gonna migrate to classess soon..

sharp cosmos
#

this issue should dissapear once u do it

inland atlas
#

hm

#

fine

#

i will do it

#

whats your timezone

sharp cosmos
#

gmt-3

#

i dont know whats that on utc

inland atlas
#

im gmt3:30

#

im 30 minutes ahead of u

inland atlas
#

for me, i need to minus it by 3:30 hours

#

that easy.

sharp cosmos
inland atlas
#

dagger im going to start refactoring the inventory functions to class methods, also im going to make my inventory slots turn into lists, do you have any other suggestions before i start this? i dont want to miss anything

inland atlas
sharp cosmos
#

just like in start of thread

#

.

inland atlas
#

in my game, you start with 5 inv-slots, then you get 2 sets of 5 later, will not putting numbers as keys for slots make any potential problems?(havent really worked with lists much)

sharp cosmos
#

2nd is index 1

#

etc.

#

so it just equates to what u had before

inland atlas
#

and 6 would give out of range error if im not wrong

sharp cosmos
#

if u there is nothing at that index ye

#

althought u can keep adding to lists indefinetly

#

so to make a limit of 5 u would need to keep track of how much u add in inventory class

inland atlas
# sharp cosmos <:pithink:652247559909277706>

i have some functions(like sum, findemptyslot) that are used by main functions like addItem, removeItem etc.. do you recommend i put them inside the inventory class or outside? they are only used by big functions that are inside inventory class

#

.

sharp cosmos
#

it goes inside inventory class

#

shrimple as that

inland atlas
sharp cosmos
#

ofc ye

inland atlas
sharp cosmos
#

cause u can have all sorts of them

inland atlas
#

i dont really have an image on how to use child classess

sharp cosmos
#

tools, guns, swords, etc. pithink

inland atlas
sharp cosmos
#

same old shit but 1 extra camera

inland atlas
#

they are all just "items"

sharp cosmos
#

tools have harvest damage which guns and swords might not

inland atlas
#

example of an item in items.json
{
"stone": {
"icon": "๐Ÿชจ",
"type": "1"
},

#

type determines its stackibility

inland atlas
sharp cosmos
#

like

#

imagine we just have an item class

#

all it has is icon name quantity etc.

#

now lets say we want to make a tool

#

uh oh, item class doesnt have a damage durability or anything like that

#

but its still an item

#

so we make a tool class inheriting from item

#

that adds all that stuff a tool might need

inland atlas
#

why dont we just put all of those stuff in item class

sharp cosmos
#

do all items no matter what need damage durability and watever else a tool need s?

#

do u need a leaf to be able to harvest resources ?

inland atlas
#

its like

#

{
"stone": {
"icon": "๐Ÿชจ",
"type": "1"
},
"sword": {
"icon": "๐Ÿ—ก",
"type": "0"
"dmg": "3"
},

#

stone dosent have dmg so it wont be in tools/weapons category

sharp cosmos
#

so type 1 here would be just base item class and type 0 would be a tools/weapon child class inheriting from item

inland atlas
#

type 1 stackable
type 0 unstackable

#

the only difference is that sword has a dmg attr

sharp cosmos
#

but not all items need a dmg attr do they ?

inland atlas
#

they dont

#

therefore they wont have it

#

we just loop with if hasattr("dmg")

sharp cosmos
#

or better yet

#
from dataclasses import dataclass

@dataclass
class Item:
    name: str
    quantity: int
    icon: str
    stackable: bool = True

@dataclass
class Weapon(Item):
    damage: int
    stackable: bool = False

some_stone = Item("stone", 0, ๐Ÿชจ)
a_sword = Weapon("excalibur", 1, :sword:, 3)
inland atlas
#

what is that @ thingy

sharp cosmos
#

decorators

inland atlas
#

here we go again

sharp cosmos
#

they are a whole can of worms that would go on for 500 messages

inland atlas
#

i have heard of them

sharp cosmos
#

for now just accept this how u do dataclasses which are a very clean way to do classes that hold data

inland atlas
#

they modify a function or class to do a certain thing without modifying the function or class

sharp cosmos
#

i can write it without the decorator if u want

inland atlas
#

how much improvement does decorator add

#

nvm i understood how decorators work

#

its like a wrapper

sharp cosmos
# inland atlas how much improvement does decorator add
class Item:
    def __init__(name, quantity, icon):
        self.name = name
        self.quantity = quantity
        self.icon = icon

class Weapon(Item):
    def __init__(name, quantity, icon, damage):
        super().__init__(name, quantity, icon)
        self.damage = damage
     
        

some_stone = Item("stone", 0, ๐Ÿชจ)
a_sword = Weapon("excalibur", 1, :sword:, 3)
inland atlas
#

wraps a function/class around a function/class

sharp cosmos
#

compare this to code just above

inland atlas
#

ye it dosent have innit

#

its not british

sharp cosmos
#

dataclass autogenerates init for u based on the data u wrote

#

its p cool

#

but they are a bit more advanced ye

inland atlas
#

thats cool

#

so you dont need to write innit at all

sharp cosmos
inland atlas
#

yea

sharp cosmos
#

anyways

#

hopefully u get idea behind why child classes of item is nice here

inland atlas
#

understood

#

such a hazard to rewrite

sharp cosmos
#

i never do that and just accept the eternal rewrite fate

inland atlas
#

ive seen you put data = 0 instead of just data in DataLoader class, whys that?

inland atlas
#

yes

#

and you just did that with data

sharp cosmos
#

thats so if data isnt given

#

it has a default value of 0

#

for playerdata u can use this so that data is the inv.json contents by default

#

and save a whole bunch of logic

inland atlas
#

hmmm

#

for all inventory methods

#

im passing inventory, item, quantity

#

but im not passing player

#

nvm

#

theres instances that for example, i want to add 10 different items at the same time, but running Class inventory isnt efficient, because that will be 10 loads, 10 saves

does class have this functionality to run it 10 times but make it actually run 1 time

weird question, im really unbraining rn

#

really close

sharp cosmos
#
def some_method_for_one_item(item):
    # watever here ?

# call this one with a list of 10 things u want done     
def some_method(items):
    for item in items:
        some_method_for_one_item(item)
    # save after its done looping or something idk
inland atlas
#

embrassing how easy it is
my brain really dosent work i need some rest
sorry

sharp cosmos
inland atlas
#

there is so many changes that ill have to make

#

i kinda have to re write everything

#

the whole inventory functions took my like 4-5 days ( im bad at math + i didnt know how to use json in python )

#

atleast were close to your new record on thread with most messages that you have been a part of

sharp cosmos
#

they usually suck

inland atlas
#

ive had multiple refactors before

#

but they were just vars, or if/elifs
or simple functions

#

ive never had complicated functions with classes

sharp cosmos
#

which is why this is gonna be a great learning experience

inland atlas
#

yea

inland atlas
thin lark
#

Holy fuck this posts has a lot of messages respect dagger

sharp cosmos
#

sometimes they just happen

inland atlas
#

really respect dagger

thin lark
sharp cosmos
#

not sure if guy wants more help or not after his lil break is over

inland atlas
#

i dont want to close it

sharp cosmos
#

it will close after 1h of inactivity

#

just fyi

inland atlas
#

i will code all night

#

any other tips on making the codes i write better?

thin lark
inland atlas
#

some useful tips were classes, dunders and decoratoes

inland atlas
#

tody ii may have lacked bit

thin lark
thin lark
sharp cosmos
#

well from 5h ago to now ig

thin lark
#

Ok good not gonna read that back on my Phone tho ๐Ÿคช

sharp cosmos
#

if u go on pinned messages u can warp to original post

#

and very start of thread

inland atlas
#

dagger congrats on ur new record

sharp cosmos
inland atlas
#

๐Ÿ˜„

sharp cosmos
#

ye project structure sounds correct

inland atlas
#

OOP?

sharp cosmos
#

nah not even python

#

well kinda goes into python

fallow vessel
#

It's still on?๐Ÿฅด

sharp cosmos
#

but more so how to structure ur folders and files so that its sane

sharp cosmos
inland atlas
fallow vessel
#

I think it's been ~8h

sharp cosmos
#

9h

sharp cosmos
thin lark
inland atlas
#

JSON saving really makes no sense

#

๐Ÿ˜‚๐Ÿ˜‚

#

will this chat be kept after closing?

fallow vessel
#

Nope
It will close 1h after no one speak

inland atlas
#

im talking about reviewing it later

fallow vessel
#

Oh yes

sharp cosmos
#

ye it will be there

fallow vessel
#

You can, I recommend you copy a link tho

sharp cosmos
#

u just might have to search for it

inland atlas
#

mhm

sharp cosmos
#

i recommend u use .bm rather than link copying

fallow vessel
#

Or that

inland atlas
#

!e

print('this was hell of a adventure')
warm runeBOT
sharp cosmos
#

that one is fun

inland atlas
#

i have so much brainfog that i dont even know what youre talking about

inland atlas
#

not so fun zone

sharp cosmos
#
Items
L __init__.py
L BasicItem.py
L BasicWeapon.py
#

im talking about this kind of package

thin lark
inland atlas
thin lark
inland atlas
#

we actyally have some

#

but i dont crack pot

thin lark
#

Anyway let s get back to coding

#

Any questions?

inland atlas
#

resting

#

will rest for an hour
then proceed to write class inventory

#

anyways
i dont know how to thank dagger

#

ima go rest
cya yall in 1~ hr ish

brisk blade
#

1610 messages gahdamn

fallow vessel
#

You just bump it, welp

brisk blade
#

has to be kept alive somehow

sharp cosmos
sharp cosmos
fallow vessel
#

Ye ik

sharp cosmos
thin lark
sharp cosmos
thin lark
#

But you tagged him :/

warm runeBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.