Minecraft block generator

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP












15














This script is a tool to help minecraft mod development. When you want to add a new block to the game you have to create three json files. This script generates three JSON files in specific locations. It's intended to be run in a certain directory so that the files go into the right location. Also it's for my own personal use.



The reason I didn't use the json module is simply because I didn't feel like. If it would make this script much better then I am all for switching to that although I did enjoy writing my json methods and found it educational which is another reason I'm making this, to learn a bit of python.



It's quite long and I think the functions could be taken out into a new file but then I'll need to make sure I have both files just to run this which I don't like.



I'm not concerned about efficiency or speed, just readability and maintainability, and general best practice.



import os

# Declare Functions
def jsonStart():
return "n"

def jsonEnd(indent):
return "n" + jsonIndent(indent) + ""

def jsonIndent(amount):
amount = amount * 4
return " " * amount

def jsonKeyValue(key, value, indent = 0):
return jsonIndent(indent) + jsonKey(key) + jsonValue(value)

def jsonKey(key, indent = 0):
return jsonIndent(indent) + """ + key + """ + ": "

def jsonValue(value):
return """ + value + """

def deleteCreatedFiles():
print("nSomething went wrong")
for file in createdFiles:
print("Deleting: " + file)
os.remove(file)
print("n")

def createFile(filename, data):
try:
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w+")as newFile:
newFile.write(data)
except:
deleteCreatedFiles()
raise
else:
createdFiles.append(os.path.relpath(newFile.name))
print("Created" + os.path.relpath(newFile.name))

def blockStatesFile():
data = jsonStart()
data += jsonKey("variants", 1) + jsonStart()
data += jsonKey("normal", 2) + " " + jsonKeyValue("model", modid + ":" + blockName) + ""
data += jsonEnd(1)
data += jsonEnd(0)
return data

def modelsItemFile():
data = jsonStart()
data += jsonKeyValue("parent", modid + ":block/" + blockName, 1) + ",n"
data += jsonKey("textures", 1) + jsonStart()
data += jsonKeyValue("layer0", modid + ":items/" + blockName, 2)
data += jsonEnd(1)
data += jsonEnd(0)
return data

def modelsBlockFile():
data = jsonStart()
data += jsonKeyValue("parent", "block/cube_all", 1) + ",n"
data += jsonKey("textures", 1) + jsonStart()
data += jsonKeyValue("all", modid + ":blocks/" + blockName, 2)
data += jsonEnd(1)
data += jsonEnd(0)
return data

# Run Script
createdFiles =
blockName = input("block name: ")
modid = input("modid: ")
createFile("blockstates/" + blockName + ".json", blockStatesFile())
createFile("models/item/" + blockName + ".json", modelsItemFile())
createFile("models/block/" + blockName + ".json", modelsBlockFile())









share|improve this question




























    15














    This script is a tool to help minecraft mod development. When you want to add a new block to the game you have to create three json files. This script generates three JSON files in specific locations. It's intended to be run in a certain directory so that the files go into the right location. Also it's for my own personal use.



    The reason I didn't use the json module is simply because I didn't feel like. If it would make this script much better then I am all for switching to that although I did enjoy writing my json methods and found it educational which is another reason I'm making this, to learn a bit of python.



    It's quite long and I think the functions could be taken out into a new file but then I'll need to make sure I have both files just to run this which I don't like.



    I'm not concerned about efficiency or speed, just readability and maintainability, and general best practice.



    import os

    # Declare Functions
    def jsonStart():
    return "n"

    def jsonEnd(indent):
    return "n" + jsonIndent(indent) + ""

    def jsonIndent(amount):
    amount = amount * 4
    return " " * amount

    def jsonKeyValue(key, value, indent = 0):
    return jsonIndent(indent) + jsonKey(key) + jsonValue(value)

    def jsonKey(key, indent = 0):
    return jsonIndent(indent) + """ + key + """ + ": "

    def jsonValue(value):
    return """ + value + """

    def deleteCreatedFiles():
    print("nSomething went wrong")
    for file in createdFiles:
    print("Deleting: " + file)
    os.remove(file)
    print("n")

    def createFile(filename, data):
    try:
    os.makedirs(os.path.dirname(filename), exist_ok=True)
    with open(filename, "w+")as newFile:
    newFile.write(data)
    except:
    deleteCreatedFiles()
    raise
    else:
    createdFiles.append(os.path.relpath(newFile.name))
    print("Created" + os.path.relpath(newFile.name))

    def blockStatesFile():
    data = jsonStart()
    data += jsonKey("variants", 1) + jsonStart()
    data += jsonKey("normal", 2) + " " + jsonKeyValue("model", modid + ":" + blockName) + ""
    data += jsonEnd(1)
    data += jsonEnd(0)
    return data

    def modelsItemFile():
    data = jsonStart()
    data += jsonKeyValue("parent", modid + ":block/" + blockName, 1) + ",n"
    data += jsonKey("textures", 1) + jsonStart()
    data += jsonKeyValue("layer0", modid + ":items/" + blockName, 2)
    data += jsonEnd(1)
    data += jsonEnd(0)
    return data

    def modelsBlockFile():
    data = jsonStart()
    data += jsonKeyValue("parent", "block/cube_all", 1) + ",n"
    data += jsonKey("textures", 1) + jsonStart()
    data += jsonKeyValue("all", modid + ":blocks/" + blockName, 2)
    data += jsonEnd(1)
    data += jsonEnd(0)
    return data

    # Run Script
    createdFiles =
    blockName = input("block name: ")
    modid = input("modid: ")
    createFile("blockstates/" + blockName + ".json", blockStatesFile())
    createFile("models/item/" + blockName + ".json", modelsItemFile())
    createFile("models/block/" + blockName + ".json", modelsBlockFile())









    share|improve this question


























      15












      15








      15


      2





      This script is a tool to help minecraft mod development. When you want to add a new block to the game you have to create three json files. This script generates three JSON files in specific locations. It's intended to be run in a certain directory so that the files go into the right location. Also it's for my own personal use.



      The reason I didn't use the json module is simply because I didn't feel like. If it would make this script much better then I am all for switching to that although I did enjoy writing my json methods and found it educational which is another reason I'm making this, to learn a bit of python.



      It's quite long and I think the functions could be taken out into a new file but then I'll need to make sure I have both files just to run this which I don't like.



      I'm not concerned about efficiency or speed, just readability and maintainability, and general best practice.



      import os

      # Declare Functions
      def jsonStart():
      return "n"

      def jsonEnd(indent):
      return "n" + jsonIndent(indent) + ""

      def jsonIndent(amount):
      amount = amount * 4
      return " " * amount

      def jsonKeyValue(key, value, indent = 0):
      return jsonIndent(indent) + jsonKey(key) + jsonValue(value)

      def jsonKey(key, indent = 0):
      return jsonIndent(indent) + """ + key + """ + ": "

      def jsonValue(value):
      return """ + value + """

      def deleteCreatedFiles():
      print("nSomething went wrong")
      for file in createdFiles:
      print("Deleting: " + file)
      os.remove(file)
      print("n")

      def createFile(filename, data):
      try:
      os.makedirs(os.path.dirname(filename), exist_ok=True)
      with open(filename, "w+")as newFile:
      newFile.write(data)
      except:
      deleteCreatedFiles()
      raise
      else:
      createdFiles.append(os.path.relpath(newFile.name))
      print("Created" + os.path.relpath(newFile.name))

      def blockStatesFile():
      data = jsonStart()
      data += jsonKey("variants", 1) + jsonStart()
      data += jsonKey("normal", 2) + " " + jsonKeyValue("model", modid + ":" + blockName) + ""
      data += jsonEnd(1)
      data += jsonEnd(0)
      return data

      def modelsItemFile():
      data = jsonStart()
      data += jsonKeyValue("parent", modid + ":block/" + blockName, 1) + ",n"
      data += jsonKey("textures", 1) + jsonStart()
      data += jsonKeyValue("layer0", modid + ":items/" + blockName, 2)
      data += jsonEnd(1)
      data += jsonEnd(0)
      return data

      def modelsBlockFile():
      data = jsonStart()
      data += jsonKeyValue("parent", "block/cube_all", 1) + ",n"
      data += jsonKey("textures", 1) + jsonStart()
      data += jsonKeyValue("all", modid + ":blocks/" + blockName, 2)
      data += jsonEnd(1)
      data += jsonEnd(0)
      return data

      # Run Script
      createdFiles =
      blockName = input("block name: ")
      modid = input("modid: ")
      createFile("blockstates/" + blockName + ".json", blockStatesFile())
      createFile("models/item/" + blockName + ".json", modelsItemFile())
      createFile("models/block/" + blockName + ".json", modelsBlockFile())









      share|improve this question















      This script is a tool to help minecraft mod development. When you want to add a new block to the game you have to create three json files. This script generates three JSON files in specific locations. It's intended to be run in a certain directory so that the files go into the right location. Also it's for my own personal use.



      The reason I didn't use the json module is simply because I didn't feel like. If it would make this script much better then I am all for switching to that although I did enjoy writing my json methods and found it educational which is another reason I'm making this, to learn a bit of python.



      It's quite long and I think the functions could be taken out into a new file but then I'll need to make sure I have both files just to run this which I don't like.



      I'm not concerned about efficiency or speed, just readability and maintainability, and general best practice.



      import os

      # Declare Functions
      def jsonStart():
      return "n"

      def jsonEnd(indent):
      return "n" + jsonIndent(indent) + ""

      def jsonIndent(amount):
      amount = amount * 4
      return " " * amount

      def jsonKeyValue(key, value, indent = 0):
      return jsonIndent(indent) + jsonKey(key) + jsonValue(value)

      def jsonKey(key, indent = 0):
      return jsonIndent(indent) + """ + key + """ + ": "

      def jsonValue(value):
      return """ + value + """

      def deleteCreatedFiles():
      print("nSomething went wrong")
      for file in createdFiles:
      print("Deleting: " + file)
      os.remove(file)
      print("n")

      def createFile(filename, data):
      try:
      os.makedirs(os.path.dirname(filename), exist_ok=True)
      with open(filename, "w+")as newFile:
      newFile.write(data)
      except:
      deleteCreatedFiles()
      raise
      else:
      createdFiles.append(os.path.relpath(newFile.name))
      print("Created" + os.path.relpath(newFile.name))

      def blockStatesFile():
      data = jsonStart()
      data += jsonKey("variants", 1) + jsonStart()
      data += jsonKey("normal", 2) + " " + jsonKeyValue("model", modid + ":" + blockName) + ""
      data += jsonEnd(1)
      data += jsonEnd(0)
      return data

      def modelsItemFile():
      data = jsonStart()
      data += jsonKeyValue("parent", modid + ":block/" + blockName, 1) + ",n"
      data += jsonKey("textures", 1) + jsonStart()
      data += jsonKeyValue("layer0", modid + ":items/" + blockName, 2)
      data += jsonEnd(1)
      data += jsonEnd(0)
      return data

      def modelsBlockFile():
      data = jsonStart()
      data += jsonKeyValue("parent", "block/cube_all", 1) + ",n"
      data += jsonKey("textures", 1) + jsonStart()
      data += jsonKeyValue("all", modid + ":blocks/" + blockName, 2)
      data += jsonEnd(1)
      data += jsonEnd(0)
      return data

      # Run Script
      createdFiles =
      blockName = input("block name: ")
      modid = input("modid: ")
      createFile("blockstates/" + blockName + ".json", blockStatesFile())
      createFile("models/item/" + blockName + ".json", modelsItemFile())
      createFile("models/block/" + blockName + ".json", modelsBlockFile())






      python beginner json minecraft






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 27 '18 at 15:48









      200_success

      128k15152414




      128k15152414










      asked Dec 27 '18 at 10:40









      DaltonDalton

      787




      787




















          2 Answers
          2






          active

          oldest

          votes


















          13














          I won't repeat @victor's answer, but Python is a language that comes with batteries included; meaning that a lot of behaviour has already been bundled into modules, and is maintained for correctness and performance. You should really avoid to reinvent the wheel if it is not for learning purposes.



          Python also comes with an official style guide: PEP8, which is advised to follow if you want your code to look like Python code to others.



          Your code also rely heavily on variables defined globally. This kind of code is error prone and less reusable. Instead, define arguments for your functions and pass information as parameters.



          Lastly, you should avoid keeping code at the top-level of the file, protect it with an if __name__ == '__main__' guard:



          import os
          import json


          def delete_files(files):
          for filename in files:
          os.remove(filename)


          def create_file(filename, data, created_files):
          try:
          os.makedirs(os.path.dirname(filename), exist_ok=True)
          with open(filename, "w+") as new_file:
          json.dump(data, new_file, indent=4)
          except:
          print("nSomething went wrong")
          print("Deleting:", *created_files)
          print("n")
          delete_files(created_files)
          raise
          else:
          filepath = os.path.relpath(new_file.name)
          created_files.append(filepath)
          print("Created", filepath)


          def block_states(modid, block_name):
          return
          'variants':
          'normal':
          'model': f'modid:block_name',
          ,
          ,



          def models_item(modid, block_name):
          return
          'parent': f'modid:block/block_name',
          'textures':
          'layer0': f'modid:items/block_name',
          ,



          def models_block(modid, block_name):
          return
          'parent': 'block/cube_all',
          'textures':
          'all': f'modid:blocks/block_name',
          ,



          def main(modid, block_name):
          created_files =
          create_file(
          f'blockstates/block_name.json',
          block_states(modid, block_name),
          created_files)
          create_file(
          f'models/item/block_name.json',
          models_item(modid, block_name),
          created_files)
          create_file(
          f'models/block/block_name.json',
          models_block(modid, block_name),
          created_files)


          if __name__ == '__main__':
          block_name = input("block name: ")
          modid = input("modid: ")
          main(modid, block_name)





          share|improve this answer






















          • Changed this to the accepted answer as it covers more than just using the json library and has shown me the best practice for using if name == 'main': and the official style guide updates
            – Dalton
            Dec 27 '18 at 13:50


















          10














          If all you need is just readability and maintainability, and general best practice, don't reinvent the wheel. You have the json library and it would be a sin not to use it. Firstly, you are greatly complicated the readability and extensibility. Secondly, JSON is not so simple (at least, you need to escape some special characters).



          I rewrote your code and you have the opportunity to compare them:



          import os, json

          # Declare Functions
          def deleteCreatedFiles():
          print("nSomething went wrong")
          for file in createdFiles:
          print("Deleting: " + file)
          os.remove(file)
          print("n")

          def createFile(filename, data):
          try:
          os.makedirs(os.path.dirname(filename), exist_ok=True)
          with open(filename, "w+") as newFile:
          jstr = json.dumps(data, indent=4)
          newFile.write(jstr)
          except:
          deleteCreatedFiles()
          raise
          else:
          createdFiles.append(os.path.relpath(newFile.name))
          print("Created" + os.path.relpath(newFile.name))

          def blockStatesFile():
          return
          'variants':
          'normal':
          'model': modid + ":" + blockName




          def modelsItemFile():
          return
          'parent': modid + ":block/" + blockName,
          'textures':
          'layer0': modid + ":items/" + blockName



          def modelsBlockFile():
          return
          'parent': 'block/cube_all',
          'textures':
          'all': modid + ":blocks/" + blockName



          # Run Script
          createdFiles =
          blockName = input("block name: ")
          modid = input("modid: ")
          createFile("blockstates/" + blockName + ".json", blockStatesFile())
          createFile("models/item/" + blockName + ".json", modelsItemFile())
          createFile("models/block/" + blockName + ".json", modelsBlockFile())





          share|improve this answer




















          • This is so much better! I'm surprised to see the functions that return the JSON actually work like that, that is really nice!
            – Dalton
            Dec 27 '18 at 12:01






          • 2




            With Python 3.6 and f-strings: f"modid:blockName", f"blockstates/blockName.json", ... are a bit shorter and more readable IMO.
            – Graipher
            Dec 27 '18 at 12:05










          • @Graipher I wondered if this sort of syntax was available in Python I am now using it in my script!
            – Dalton
            Dec 27 '18 at 12:34











          Your Answer





          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210414%2fminecraft-block-generator%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          13














          I won't repeat @victor's answer, but Python is a language that comes with batteries included; meaning that a lot of behaviour has already been bundled into modules, and is maintained for correctness and performance. You should really avoid to reinvent the wheel if it is not for learning purposes.



          Python also comes with an official style guide: PEP8, which is advised to follow if you want your code to look like Python code to others.



          Your code also rely heavily on variables defined globally. This kind of code is error prone and less reusable. Instead, define arguments for your functions and pass information as parameters.



          Lastly, you should avoid keeping code at the top-level of the file, protect it with an if __name__ == '__main__' guard:



          import os
          import json


          def delete_files(files):
          for filename in files:
          os.remove(filename)


          def create_file(filename, data, created_files):
          try:
          os.makedirs(os.path.dirname(filename), exist_ok=True)
          with open(filename, "w+") as new_file:
          json.dump(data, new_file, indent=4)
          except:
          print("nSomething went wrong")
          print("Deleting:", *created_files)
          print("n")
          delete_files(created_files)
          raise
          else:
          filepath = os.path.relpath(new_file.name)
          created_files.append(filepath)
          print("Created", filepath)


          def block_states(modid, block_name):
          return
          'variants':
          'normal':
          'model': f'modid:block_name',
          ,
          ,



          def models_item(modid, block_name):
          return
          'parent': f'modid:block/block_name',
          'textures':
          'layer0': f'modid:items/block_name',
          ,



          def models_block(modid, block_name):
          return
          'parent': 'block/cube_all',
          'textures':
          'all': f'modid:blocks/block_name',
          ,



          def main(modid, block_name):
          created_files =
          create_file(
          f'blockstates/block_name.json',
          block_states(modid, block_name),
          created_files)
          create_file(
          f'models/item/block_name.json',
          models_item(modid, block_name),
          created_files)
          create_file(
          f'models/block/block_name.json',
          models_block(modid, block_name),
          created_files)


          if __name__ == '__main__':
          block_name = input("block name: ")
          modid = input("modid: ")
          main(modid, block_name)





          share|improve this answer






















          • Changed this to the accepted answer as it covers more than just using the json library and has shown me the best practice for using if name == 'main': and the official style guide updates
            – Dalton
            Dec 27 '18 at 13:50















          13














          I won't repeat @victor's answer, but Python is a language that comes with batteries included; meaning that a lot of behaviour has already been bundled into modules, and is maintained for correctness and performance. You should really avoid to reinvent the wheel if it is not for learning purposes.



          Python also comes with an official style guide: PEP8, which is advised to follow if you want your code to look like Python code to others.



          Your code also rely heavily on variables defined globally. This kind of code is error prone and less reusable. Instead, define arguments for your functions and pass information as parameters.



          Lastly, you should avoid keeping code at the top-level of the file, protect it with an if __name__ == '__main__' guard:



          import os
          import json


          def delete_files(files):
          for filename in files:
          os.remove(filename)


          def create_file(filename, data, created_files):
          try:
          os.makedirs(os.path.dirname(filename), exist_ok=True)
          with open(filename, "w+") as new_file:
          json.dump(data, new_file, indent=4)
          except:
          print("nSomething went wrong")
          print("Deleting:", *created_files)
          print("n")
          delete_files(created_files)
          raise
          else:
          filepath = os.path.relpath(new_file.name)
          created_files.append(filepath)
          print("Created", filepath)


          def block_states(modid, block_name):
          return
          'variants':
          'normal':
          'model': f'modid:block_name',
          ,
          ,



          def models_item(modid, block_name):
          return
          'parent': f'modid:block/block_name',
          'textures':
          'layer0': f'modid:items/block_name',
          ,



          def models_block(modid, block_name):
          return
          'parent': 'block/cube_all',
          'textures':
          'all': f'modid:blocks/block_name',
          ,



          def main(modid, block_name):
          created_files =
          create_file(
          f'blockstates/block_name.json',
          block_states(modid, block_name),
          created_files)
          create_file(
          f'models/item/block_name.json',
          models_item(modid, block_name),
          created_files)
          create_file(
          f'models/block/block_name.json',
          models_block(modid, block_name),
          created_files)


          if __name__ == '__main__':
          block_name = input("block name: ")
          modid = input("modid: ")
          main(modid, block_name)





          share|improve this answer






















          • Changed this to the accepted answer as it covers more than just using the json library and has shown me the best practice for using if name == 'main': and the official style guide updates
            – Dalton
            Dec 27 '18 at 13:50













          13












          13








          13






          I won't repeat @victor's answer, but Python is a language that comes with batteries included; meaning that a lot of behaviour has already been bundled into modules, and is maintained for correctness and performance. You should really avoid to reinvent the wheel if it is not for learning purposes.



          Python also comes with an official style guide: PEP8, which is advised to follow if you want your code to look like Python code to others.



          Your code also rely heavily on variables defined globally. This kind of code is error prone and less reusable. Instead, define arguments for your functions and pass information as parameters.



          Lastly, you should avoid keeping code at the top-level of the file, protect it with an if __name__ == '__main__' guard:



          import os
          import json


          def delete_files(files):
          for filename in files:
          os.remove(filename)


          def create_file(filename, data, created_files):
          try:
          os.makedirs(os.path.dirname(filename), exist_ok=True)
          with open(filename, "w+") as new_file:
          json.dump(data, new_file, indent=4)
          except:
          print("nSomething went wrong")
          print("Deleting:", *created_files)
          print("n")
          delete_files(created_files)
          raise
          else:
          filepath = os.path.relpath(new_file.name)
          created_files.append(filepath)
          print("Created", filepath)


          def block_states(modid, block_name):
          return
          'variants':
          'normal':
          'model': f'modid:block_name',
          ,
          ,



          def models_item(modid, block_name):
          return
          'parent': f'modid:block/block_name',
          'textures':
          'layer0': f'modid:items/block_name',
          ,



          def models_block(modid, block_name):
          return
          'parent': 'block/cube_all',
          'textures':
          'all': f'modid:blocks/block_name',
          ,



          def main(modid, block_name):
          created_files =
          create_file(
          f'blockstates/block_name.json',
          block_states(modid, block_name),
          created_files)
          create_file(
          f'models/item/block_name.json',
          models_item(modid, block_name),
          created_files)
          create_file(
          f'models/block/block_name.json',
          models_block(modid, block_name),
          created_files)


          if __name__ == '__main__':
          block_name = input("block name: ")
          modid = input("modid: ")
          main(modid, block_name)





          share|improve this answer














          I won't repeat @victor's answer, but Python is a language that comes with batteries included; meaning that a lot of behaviour has already been bundled into modules, and is maintained for correctness and performance. You should really avoid to reinvent the wheel if it is not for learning purposes.



          Python also comes with an official style guide: PEP8, which is advised to follow if you want your code to look like Python code to others.



          Your code also rely heavily on variables defined globally. This kind of code is error prone and less reusable. Instead, define arguments for your functions and pass information as parameters.



          Lastly, you should avoid keeping code at the top-level of the file, protect it with an if __name__ == '__main__' guard:



          import os
          import json


          def delete_files(files):
          for filename in files:
          os.remove(filename)


          def create_file(filename, data, created_files):
          try:
          os.makedirs(os.path.dirname(filename), exist_ok=True)
          with open(filename, "w+") as new_file:
          json.dump(data, new_file, indent=4)
          except:
          print("nSomething went wrong")
          print("Deleting:", *created_files)
          print("n")
          delete_files(created_files)
          raise
          else:
          filepath = os.path.relpath(new_file.name)
          created_files.append(filepath)
          print("Created", filepath)


          def block_states(modid, block_name):
          return
          'variants':
          'normal':
          'model': f'modid:block_name',
          ,
          ,



          def models_item(modid, block_name):
          return
          'parent': f'modid:block/block_name',
          'textures':
          'layer0': f'modid:items/block_name',
          ,



          def models_block(modid, block_name):
          return
          'parent': 'block/cube_all',
          'textures':
          'all': f'modid:blocks/block_name',
          ,



          def main(modid, block_name):
          created_files =
          create_file(
          f'blockstates/block_name.json',
          block_states(modid, block_name),
          created_files)
          create_file(
          f'models/item/block_name.json',
          models_item(modid, block_name),
          created_files)
          create_file(
          f'models/block/block_name.json',
          models_block(modid, block_name),
          created_files)


          if __name__ == '__main__':
          block_name = input("block name: ")
          modid = input("modid: ")
          main(modid, block_name)






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Dec 27 '18 at 14:51

























          answered Dec 27 '18 at 12:59









          Mathias EttingerMathias Ettinger

          23.6k33182




          23.6k33182











          • Changed this to the accepted answer as it covers more than just using the json library and has shown me the best practice for using if name == 'main': and the official style guide updates
            – Dalton
            Dec 27 '18 at 13:50
















          • Changed this to the accepted answer as it covers more than just using the json library and has shown me the best practice for using if name == 'main': and the official style guide updates
            – Dalton
            Dec 27 '18 at 13:50















          Changed this to the accepted answer as it covers more than just using the json library and has shown me the best practice for using if name == 'main': and the official style guide updates
          – Dalton
          Dec 27 '18 at 13:50




          Changed this to the accepted answer as it covers more than just using the json library and has shown me the best practice for using if name == 'main': and the official style guide updates
          – Dalton
          Dec 27 '18 at 13:50













          10














          If all you need is just readability and maintainability, and general best practice, don't reinvent the wheel. You have the json library and it would be a sin not to use it. Firstly, you are greatly complicated the readability and extensibility. Secondly, JSON is not so simple (at least, you need to escape some special characters).



          I rewrote your code and you have the opportunity to compare them:



          import os, json

          # Declare Functions
          def deleteCreatedFiles():
          print("nSomething went wrong")
          for file in createdFiles:
          print("Deleting: " + file)
          os.remove(file)
          print("n")

          def createFile(filename, data):
          try:
          os.makedirs(os.path.dirname(filename), exist_ok=True)
          with open(filename, "w+") as newFile:
          jstr = json.dumps(data, indent=4)
          newFile.write(jstr)
          except:
          deleteCreatedFiles()
          raise
          else:
          createdFiles.append(os.path.relpath(newFile.name))
          print("Created" + os.path.relpath(newFile.name))

          def blockStatesFile():
          return
          'variants':
          'normal':
          'model': modid + ":" + blockName




          def modelsItemFile():
          return
          'parent': modid + ":block/" + blockName,
          'textures':
          'layer0': modid + ":items/" + blockName



          def modelsBlockFile():
          return
          'parent': 'block/cube_all',
          'textures':
          'all': modid + ":blocks/" + blockName



          # Run Script
          createdFiles =
          blockName = input("block name: ")
          modid = input("modid: ")
          createFile("blockstates/" + blockName + ".json", blockStatesFile())
          createFile("models/item/" + blockName + ".json", modelsItemFile())
          createFile("models/block/" + blockName + ".json", modelsBlockFile())





          share|improve this answer




















          • This is so much better! I'm surprised to see the functions that return the JSON actually work like that, that is really nice!
            – Dalton
            Dec 27 '18 at 12:01






          • 2




            With Python 3.6 and f-strings: f"modid:blockName", f"blockstates/blockName.json", ... are a bit shorter and more readable IMO.
            – Graipher
            Dec 27 '18 at 12:05










          • @Graipher I wondered if this sort of syntax was available in Python I am now using it in my script!
            – Dalton
            Dec 27 '18 at 12:34
















          10














          If all you need is just readability and maintainability, and general best practice, don't reinvent the wheel. You have the json library and it would be a sin not to use it. Firstly, you are greatly complicated the readability and extensibility. Secondly, JSON is not so simple (at least, you need to escape some special characters).



          I rewrote your code and you have the opportunity to compare them:



          import os, json

          # Declare Functions
          def deleteCreatedFiles():
          print("nSomething went wrong")
          for file in createdFiles:
          print("Deleting: " + file)
          os.remove(file)
          print("n")

          def createFile(filename, data):
          try:
          os.makedirs(os.path.dirname(filename), exist_ok=True)
          with open(filename, "w+") as newFile:
          jstr = json.dumps(data, indent=4)
          newFile.write(jstr)
          except:
          deleteCreatedFiles()
          raise
          else:
          createdFiles.append(os.path.relpath(newFile.name))
          print("Created" + os.path.relpath(newFile.name))

          def blockStatesFile():
          return
          'variants':
          'normal':
          'model': modid + ":" + blockName




          def modelsItemFile():
          return
          'parent': modid + ":block/" + blockName,
          'textures':
          'layer0': modid + ":items/" + blockName



          def modelsBlockFile():
          return
          'parent': 'block/cube_all',
          'textures':
          'all': modid + ":blocks/" + blockName



          # Run Script
          createdFiles =
          blockName = input("block name: ")
          modid = input("modid: ")
          createFile("blockstates/" + blockName + ".json", blockStatesFile())
          createFile("models/item/" + blockName + ".json", modelsItemFile())
          createFile("models/block/" + blockName + ".json", modelsBlockFile())





          share|improve this answer




















          • This is so much better! I'm surprised to see the functions that return the JSON actually work like that, that is really nice!
            – Dalton
            Dec 27 '18 at 12:01






          • 2




            With Python 3.6 and f-strings: f"modid:blockName", f"blockstates/blockName.json", ... are a bit shorter and more readable IMO.
            – Graipher
            Dec 27 '18 at 12:05










          • @Graipher I wondered if this sort of syntax was available in Python I am now using it in my script!
            – Dalton
            Dec 27 '18 at 12:34














          10












          10








          10






          If all you need is just readability and maintainability, and general best practice, don't reinvent the wheel. You have the json library and it would be a sin not to use it. Firstly, you are greatly complicated the readability and extensibility. Secondly, JSON is not so simple (at least, you need to escape some special characters).



          I rewrote your code and you have the opportunity to compare them:



          import os, json

          # Declare Functions
          def deleteCreatedFiles():
          print("nSomething went wrong")
          for file in createdFiles:
          print("Deleting: " + file)
          os.remove(file)
          print("n")

          def createFile(filename, data):
          try:
          os.makedirs(os.path.dirname(filename), exist_ok=True)
          with open(filename, "w+") as newFile:
          jstr = json.dumps(data, indent=4)
          newFile.write(jstr)
          except:
          deleteCreatedFiles()
          raise
          else:
          createdFiles.append(os.path.relpath(newFile.name))
          print("Created" + os.path.relpath(newFile.name))

          def blockStatesFile():
          return
          'variants':
          'normal':
          'model': modid + ":" + blockName




          def modelsItemFile():
          return
          'parent': modid + ":block/" + blockName,
          'textures':
          'layer0': modid + ":items/" + blockName



          def modelsBlockFile():
          return
          'parent': 'block/cube_all',
          'textures':
          'all': modid + ":blocks/" + blockName



          # Run Script
          createdFiles =
          blockName = input("block name: ")
          modid = input("modid: ")
          createFile("blockstates/" + blockName + ".json", blockStatesFile())
          createFile("models/item/" + blockName + ".json", modelsItemFile())
          createFile("models/block/" + blockName + ".json", modelsBlockFile())





          share|improve this answer












          If all you need is just readability and maintainability, and general best practice, don't reinvent the wheel. You have the json library and it would be a sin not to use it. Firstly, you are greatly complicated the readability and extensibility. Secondly, JSON is not so simple (at least, you need to escape some special characters).



          I rewrote your code and you have the opportunity to compare them:



          import os, json

          # Declare Functions
          def deleteCreatedFiles():
          print("nSomething went wrong")
          for file in createdFiles:
          print("Deleting: " + file)
          os.remove(file)
          print("n")

          def createFile(filename, data):
          try:
          os.makedirs(os.path.dirname(filename), exist_ok=True)
          with open(filename, "w+") as newFile:
          jstr = json.dumps(data, indent=4)
          newFile.write(jstr)
          except:
          deleteCreatedFiles()
          raise
          else:
          createdFiles.append(os.path.relpath(newFile.name))
          print("Created" + os.path.relpath(newFile.name))

          def blockStatesFile():
          return
          'variants':
          'normal':
          'model': modid + ":" + blockName




          def modelsItemFile():
          return
          'parent': modid + ":block/" + blockName,
          'textures':
          'layer0': modid + ":items/" + blockName



          def modelsBlockFile():
          return
          'parent': 'block/cube_all',
          'textures':
          'all': modid + ":blocks/" + blockName



          # Run Script
          createdFiles =
          blockName = input("block name: ")
          modid = input("modid: ")
          createFile("blockstates/" + blockName + ".json", blockStatesFile())
          createFile("models/item/" + blockName + ".json", modelsItemFile())
          createFile("models/block/" + blockName + ".json", modelsBlockFile())






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Dec 27 '18 at 11:52









          VictorVictor

          2776




          2776











          • This is so much better! I'm surprised to see the functions that return the JSON actually work like that, that is really nice!
            – Dalton
            Dec 27 '18 at 12:01






          • 2




            With Python 3.6 and f-strings: f"modid:blockName", f"blockstates/blockName.json", ... are a bit shorter and more readable IMO.
            – Graipher
            Dec 27 '18 at 12:05










          • @Graipher I wondered if this sort of syntax was available in Python I am now using it in my script!
            – Dalton
            Dec 27 '18 at 12:34

















          • This is so much better! I'm surprised to see the functions that return the JSON actually work like that, that is really nice!
            – Dalton
            Dec 27 '18 at 12:01






          • 2




            With Python 3.6 and f-strings: f"modid:blockName", f"blockstates/blockName.json", ... are a bit shorter and more readable IMO.
            – Graipher
            Dec 27 '18 at 12:05










          • @Graipher I wondered if this sort of syntax was available in Python I am now using it in my script!
            – Dalton
            Dec 27 '18 at 12:34
















          This is so much better! I'm surprised to see the functions that return the JSON actually work like that, that is really nice!
          – Dalton
          Dec 27 '18 at 12:01




          This is so much better! I'm surprised to see the functions that return the JSON actually work like that, that is really nice!
          – Dalton
          Dec 27 '18 at 12:01




          2




          2




          With Python 3.6 and f-strings: f"modid:blockName", f"blockstates/blockName.json", ... are a bit shorter and more readable IMO.
          – Graipher
          Dec 27 '18 at 12:05




          With Python 3.6 and f-strings: f"modid:blockName", f"blockstates/blockName.json", ... are a bit shorter and more readable IMO.
          – Graipher
          Dec 27 '18 at 12:05












          @Graipher I wondered if this sort of syntax was available in Python I am now using it in my script!
          – Dalton
          Dec 27 '18 at 12:34





          @Graipher I wondered if this sort of syntax was available in Python I am now using it in my script!
          – Dalton
          Dec 27 '18 at 12:34


















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210414%2fminecraft-block-generator%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown






          Popular posts from this blog

          How to check contact read email or not when send email to Individual?

          Displaying single band from multi-band raster using QGIS

          How many registers does an x86_64 CPU actually have?