pythongame-development

access the .json file in a folder. i have tried a lot of way. but it all get error


I am making a simple game that can run through the Terminal (PYTHON) I am coding it in Linux Ubuntu it was so easy to access the .json file. and everything seem to go really well.

There will be a lot of monster in the game so I make a folder MobData in the same folder as the main.py

the problem occurred inside "class Mob:"

Here is my code and screenshots of folder $HOME/scripts and $HOME/scripts/MobData

import json
import random
import os
from colorama import Fore, Back, Style

thisFileDir = os.path.dirname(os.path.realpath(__file__))
cwd = os.getcwd()

def clear():
    os.system("clear")

#first scene. asking for data choice.
clear()
print("---SIMPLE GAME---\n\n\t1.Newgame\n\t2.Continue")

#1.start with new data 2.continue with current data
UserInput = int(input("Player: "))
match UserInput:
    case 1:
        UserInput = int(input("Are you sure? 1.yes 2.no ")) #make sure about consideraion
        match UserInput:
            case 1:
                clear()
                print("---Newgame---")
                PlayerName = str(input("Player's Name (atleast 3 digit. if less than that, set to John): "))
                with open('default.json') as json_file: #take the default data
                    Default = json.load(json_file)
                    json_file.close()
                if len(PlayerName) >= 3: #if the given name is shorter than 3 characters, set the name to default
                    Default["PlayerName"] = PlayerName
                with open('data.json', 'w') as json_file: #set the data to default
                    json.dump(Default, json_file, indent=4)
                    json_file.close()
            case _:
                clear()
                exit()
    case 2:
        clear()
        print("---Continue---")
    case _:
        clear()
        print("---Closed---")
        exit()

#show player infomation
clear()
with open('data.json') as json_file:
    Data = json.load(json_file)
    json_file.close

class Mob:
    def __init__(self, Name):
        fileName = Name+(".json")
        fileDest = cwd+"/"+fileName
        with open(fileDest) as json_file:
            mobData = json.load(json_file)
            json_file.close()
        self.Name = Name
        self.HP = mobData[Health]
        self.BATK = mobData[BaseATK]
        self.BEXP = mobData[BaseEXP]
        self.Loot = mobData[Loot]

    def showInfo(self):
        print(Back.RED + Fore.WHITE + ">> % <<" %(self.Name))

def showPlayerInfo():
    print(Back.WHITE + Fore.BLACK + ">>> %s <<<" % (Data["PlayerName"]))
    print("Level: ", Data["Level"])
    print("Exp: ", Data["Exp"], "/", Data["CurrentMaxExp"])
    print(Back.GREEN + "HP: ", Data["HealthPoint"])
    print(Back.BLUE + "Energy: ", Data["Energy"])
    print(Back.YELLOW + "Hunger: ", Data["Hunger"])
    print(Back.WHITE + "Coins: ", Data["Coins"])
    print("Status: ", Data["Attributes"])
    print(Back.RED + Fore.WHITE + "Weapon: ", Data["Weapon"])
    print(Fore.RESET + Back.RESET)

def showInventory():
    print(Back.LIGHTYELLOW_EX + Fore.BLACK + "Inventory")
    print(Data["Inventory"])
    print(Fore.RESET + Back.RESET)

def updatePlayerLevel():
    cme = Data["CurrentMaxExp"]
    ce = Data["Exp"]
    level = Data["Level"]
    cme = 100+((level-1)*20)
    if ce >= cme:
        ce-=cme
        level+=1

def showCurrentPlace():
    print(Back.LIGHTRED_EX + Fore.BLACK + "You are at: ", Data["CurrentPlace"])
    print("You can go: ")

showPlayerInfo()
showInventory()
Bat = Mob("bat")
Bat.showInfo()

I tried to reach the files

open("/MobData/bat.json") <----doesn't work

open("full destination") <----doesn't work either

all give an error such as no such a file or destination

I'm totally stuck now.

(any tips for my project? it's my first time making something this big.)


Solution

  • Here's a very stripped-down version of the parts you're having trouble with, with additional logging and error handling. I'm using pathlib.Path for file management for convenience here.

    import json
    from pathlib import Path
    
    mobs_directory = Path("./mobs").resolve()
    print("Looking for mobs in", mobs_directory)
    if not mobs_directory.is_dir():
        raise FileNotFoundError(f"mobs directory {mobs_directory!r} not found")
    
    
    class Mob:
        def __init__(self, name):
            self.name = name
            data = json.loads((mobs_directory / f"{name}.json").read_text())
            self.HP = data["Health"]
            self.BATK = data["BaseATK"]
            self.BEXP = data["BaseEXP"]
            self.Loot = data["Loot"]
    
        def describe(self):
            print(
                f"{self.name} has {self.HP} HP, "
                f"{self.BATK} BaseATK, {self.BEXP} BaseEXP, "
                f"and drops {self.Loot}"
            )
    
    
    Bat = Mob("bat")
    Bat.describe()
    

    Now, if with a file called mobs/bat.json in place next to the program:

    {
      "Health": 123,
      "BaseATK": 123,
      "BaseEXP": 456,
      "Loot": "absolutely"
    }
    

    and I run the program, I get:

    $ python so77344720.py
    Looking for mobs in /Users/akx/build/so-misc/mobs
    bat has 123 HP, 123 BaseATK, 456 BaseEXP, and drops absolutely
    

    Now, mobs_directory is relative to the current working directory (./), not the program's directory.

    If you want to make it always relative to the program's directory, you could do e.g.

    program_directory = Path(__file__).parent.resolve()
    mobs_directory = program_directory / "mobs"