0 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

The Sims 4 Modern Python Modding: Part 1 — Setup

Содержание

The Sims 4 Modern Python Modding: Part 1 — Setup

The Sims 4 Modern Python Modding: Part 1 — Setup

Why I’m writing this article

I’ve been programming for many, many years but I’m very new to Sims 4 modding and was ashamed and baffled by the state of tutorials. Most tutorials are from 2014–2018 and are terribly written and put together using bad teaching practices and are very much out of date. Explanations were also very lacking. You can’t just be told what to do, you obviously want to be a great modder and to do that you have to understand what you’re doing.

The tutorials are so bad that for the past 6 years all people have been talking about are how bad the tutorials are and how very few their are. I’m going to be hopefully writing better articles over a span of time, I know programming pretty well, I just have to figure out Sims 4 modding without much help online. My goal is to document what I’ve learned into tutorials with good explanations so you can stand on your own and take it further.

What you need before starting

I’m helping you learn how to make scripting mods for the Sims 4 written in Python, something that’s very lacking on the internet for the past 6 or so years. This means you need to know python at least a little. I’m new to python as well so you don’t need to know a whole lot to get started but I’m not going to take up article space explaining how to program and what programming tools you should use. I assume you know at least the very basics because if you don’t there’s a plethora of tools and resources out there to get you on your feet.

If you’re curious, the tool I use is the free version of PyCharm because it offers great code support and hints and works well with different Python versions. I encourage you to use whatever you want. Everybody has their preferences and I want you to stand on your own. Other great tools are VisualStudio Code, Notepad++, Sublime, etc…

I also use Windows, I use Mac a long time ago but I don’t have a mac anymore so I don’t know how to translate these steps to Mac OSX. Hopefully though it’s not that difficult to follow if you’re on a mac.

The python version is extremely important

I’m just going to come out and say this, EA could make this all a billion times easier and it actually angers me they don’t. You can’t claim to support the modding community and make it so easy to mod the game yet offer no help whatsoever to the modding process.

With that said, as of this writing, it’s vital you get the latest version of Python 3.7. I’m using 3.7.9. It can’t be 3.8 or any later version and it can’t be 3.6 or any earlier version. It has to be exactly 3.7. This is very important. This also assumes they haven’t upgraded the python version. In the future this could be out of date but just know that if it changes in the future it has to be the exact version it changes to.

You can find all the current latest python versions from here and as of this writing you need to download the latest 3.7 one. I have multiple python versions installed so I just download it to C:Python37 and chose not to add it to the system path because I hate dealing with multiple versions on the system path.

The Sims 4 python library

Remember when I said this angers me that EA says one thing and acts a different way to the modding community. Well, this is what I’m talking about.

In order to write python scripts for The Sims 4, you need to know how to interact with the game. To do that you need to know what code is available inside the game for you to work with. Normally EA would provide you with a specially licensed zip folder containing the files for you to look at and use for development purposes. Much like how Android, Bukkit, Skyrim, and a whole slew of other companies and projects do. It’s fairly standard practice that EA hasn’t gotten the memo on in over 6 years. This is not intuitive at all nor is it easy yet it’s highly critical so it’s the first thing we need to do and I’m sorry EA makes this so difficult.

Step 1: Create a development folder to house everything

I created mine at “DocumentsSims 4 Projects” and inside that I have the “Tuning” files which is outside the scope of this article along with the python files. You don’t have to, it just keeps everything nice and organized.

Step 2: Copy the python libraries to a working area

If you’re copying me you can create a folder inside your main folder, I named mine “python”. You can find these files in your Sims 4 installation, on Windows typically located at

C:Program Files (x86)Origin GamesThe Sims 4DataSimulationGameplay

But if you have a different installation they may be in a different location then. Copy the 3 zip files you see base.zip, core.zip, and simulation.zip. In the future if they’re are any more I’d copy them as well.

Inside these folders are “pyc” files. This means they are compiled python files and that means you can’t look at any of the contents inside them. If you can’t see inside them, then you can’t make python mods and without any help from EA we’re left to open them ourselves which is very error prone to warn you ahead of time.

Step 3: Unzip them

Unzip the files in the working directory, after doing so you can delete the copied zip files but I chose to stash them away in a folder called “__originals”. It’s up to you.

Step 4: Convert them back to python that you can look at

This process is actually not suppose to happen, it’s not normal or natural to decompile a python file. It’s buggy and error prone and takes a very long time. On my machine it took up to an hour. Many python files will not be able to be decompiled successfully. For every file that cannot be decompiled, it means that’s 1 less file you can use in the game in mods which is upsetting because to create amazing mods you want to know all the potential features you can use, not just the ones you were able to decompile.

Over the many years there have been all sorts of attempts are making a decompiler. The ones listed in tutorials online are often out of date and often use a homemade decompiler which isn’t as good and often has a ton of issues if it even runs at all. You need to use the latest decompiler which has the highest success rate for each file.

As of this writing, that decompiler is uncompyle6 and is easily installed through pip.

Because I’m not using the system path, this is how I installed it

C:python37python.exe -m pip install uncompyle6

It’s very important to install this to the python 3.7

Now you need to start decompiling, THIS WILL TAKE A VERY LONG TIME and several files will not decompile! The program has the ability to traverse all the python files and decompile them bit it’s very buggy and often crashes so I highly recommend to use Windows Powershell to do this instead.

Open a powershell inside the python folder and execute the following command, the following comamnd is specific to powershell (Blue Background) not Command Prompt. It will not work in Comamnd Prompt (which is older and has a black background most people are familiar with).

After an eternity, you’ll have the compiled files ending in “.pyc” next to the decompiled files which end in “.py”.

The next important step we need to do is fix the file naming. Run this also in the same PowerShell. This renames all files from something like “__init__.pyc.py” to “__init__.py” which is important for python tools to offer proper help.

You should have something that looks like this

Congratulations, you’re now done with the most difficult and longest part and you never need to do this again until they do a big update.

Step 5: Setup your editor

This can be something as simple as Notepad++ or Sublime up to something as big as PyCharm. Perhaps a middle ground like Visual Studio Code.

I can’t write help for every editor so I’m going to cover PyCharm. It’s completely free and the download link is above when I first mentioned it. Don’t just copy me though, use the editor you feel most comfortable using. many people prefer something simple like Sublime or Notepad++.

for PyCharm, anytime you create a new project, you need to select Python 3.7. Normally for the first time it’s not going to know where that is, you can skip this part if yours is already pointing to 3.7.

Click the 3 dots as shown in the image above to bring up another window. Click System Interpreter and the 3 dots again.

just select “python.exe” from the Python 3.7

Now we need to add the python libraries we decompiled, you will have to do this once on every new project. Open settings

and go to project structure. Click on “Add Content Root”

You need to add “base/lib”, “core”, and “simulation”. You can hold the ctrl key down and select multiple to do it all in one shot.

Make sure you select the “lib” folder inside of “base” as the image above shows. The “base” folder is a bit different. Now mark the 3 folders as source folders.

And you’re ready to start coding python

I know this was a very long tutorial

EA has made this so difficult to get started and some documentation and proper zip files would have been so much easier. We make do with what we have though and unfortunately this is how it has to be done currently.

I appreciate you taking the time to go through this initial tutorial. It’s lays out important groundwork and I tried my best to explain things so that you understand why we’re doing these things. The “why” helps you stand on your own and understand how to make your own decisions and not rely on stuff other people make which may be badly done and often breaks.

I hope you follow me into the later upcoming tutorials which hopefully won’t be near as bad and long as this one.

What’s the purpose of the 3 different folders?

  • base — contains low-level code. In plain English it means you won’t use this very often. Imagine asking you’re friend to hand you an apple. You have all the different steps to that like communication and gestures but in reality you don’t care about all the little steps to getting the apple, you just want the apple. That’s what “base” is. It contains all the hundreds or thousands of little steps to make different things happen and most of the time you’re concerned about the bigger picture. The only time you’ll go in here is when you’re making a mod that does some of the little steps a bit differently so you’ll need to borrow some of the pre-existing steps and make others on your own (such as asking your friend for a green apple in Spanish both of which may not be in “base” but still may share some of the same steps)….. Again this won’t normally be the case.
  • core — This is like base but groups little steps from “base” into generic tasks. You’ll be using this folder more often. Would you rather write down the 50 steps needed to ask your friend for an apple (base) or just one step (core).
  • simulation — This is the biggest folder you’ll use a whole lot! It contains all sorts of coding to control and manipulate most every aspect of the game. While “core” is for more generic code, “simulation” is for the actual gameplay and interface.
Читать еще:  The Sims 4: City Living

See you in Part 2

Next we’ll make a Hello World Program, I hope to see you then. Click here for part 2.

Getting Started with Python Scripting

  • « Prev
  • 1
  • 2
  • 3
  • 4

andrew
Tech Lead

Post by andrew on Oct 28, 2018 22:13:20 GMT -5

This tutorial will show you how to install the required tools, extract EA python scripts, edit custom python scripts, and compile them to share as a mod. You will be using a free program called PyCharm to edit the python files. Please note, this tutorial assumes some familiarity with python and is not meant as a substitute for lessons/tutorials in python coding. It will show the Sims 4-specific steps of making a script mod. This tutorial requires your game to at minimum be patched with the 11/13/2018 game patch.

There is a Russian translation of this tutorial by Lamare available HERE.

You will not need Sims 4 Studio at all to complete this tutorial.

The programs used are also available on Mac OS, but I have never tried them on a Mac, so there will be differences.

What you will need:

Getting Started:

1. Install Python 3.7 from the link above.

2. Install PyCharm from the link above. The Community edition is 100% free. Note: You no longer need to use an old version of PyCharm since The Sims 4 now uses a modern version of Python.

3. Download and unzip the PyCharm starter project in your project folder.

4. Start PyCharm

5. Click Open and browse to your project folder where you unzipped the starter project.

6. When you first open the starter project, it will have the settings.py folder opened for you. Here, you will need to set your creator name, the location of your game, and the location of your mods folder. It will already be set to the default location for your game and mods folder, so set your creator name as shown below. Then click Configure Python interpreter in the upper right corner.

Click the small gear in the right corner. A box will pop up — choose Add Local:

Select System Interpreter on the left. Make sure that the Interpreter on the right is in your Python37 folder. If you have other versions of Python installed, it may default to another one. Click OK.

7. After setting your creator name and adding your Python interpreter, expand the project folder on the left. You will see some folders and a few python files in the main folder.

  • EA — this is where the extracted game scripts will be stored. When you first open this project, the sub-folders will be empty.
  • My Script Mods — this is where you can keep the python source files for the mods that you will make.
  • Utilities — this folder contains python scripts included in the starter project to help automate things for you. You will not need to edit these files at all.
  • decompile_all.py is a script file that will extract the in-game python scripts and decompile them so that you can use them.
  • settings.py — is the settings file that you edited in step 6. If you ever need to change your creator name or game path, edit it here.

8. Before trying to create a script of your own, it is best to first extract the ones from the game. Not only can you look to them for examples, but also having them extracted will allow PyCharm to assist you while creating your own scripts. To extract the game scripts, right-click the decompile_all.py and select «Run ‘decompile_all'». You will see a log at the bottom of the screen written for each decompiled file. Wait until it has finished before continuing to the next step.

9. You will now see that the EA sub-folders are full of more sub-folders with the extracted game scripts. Your PyCharm project is now fully set up to make a script mod. PyCharm has many features that will assist you with writing your scripts and detect errors in them, but to do so, it will need to have the game’s script files available. The startup project provided configures PyCharm to look in the EA sub-folder and assist you when working with EA scripts.

Note: after each patch, you should run the decompile_all script again to keep your EA scripts up to date with the current patch.

Your first script mod:

1. Expand the subfolders of the «My Script Mods» folder. In this folder, will be a subfolder for each script mod that you make. Right now it will only have one mod that is called «Example Mod». Each mod folder will have a subfolder called «Scripts» that will contain all of your .py files for the mod. Open the example_mod.py file in the Scripts sub-folder of the example mod by double-clicking it.


2. In this script file is an in-game cheat code mod. This type is the simplest python mod that can be made.

@sims4.commands.Command(‘myfirstscript’, command_type=sims4.commands.CommandType.Live)
def myfirstscript(_connection=None):
output = sims4.commands.CheatOutput(_connection)
output(«This is my first script mod»)

  • The first line loads the sims4.commands module from EA’s game scripts. This step is required to use the sims4.commands.Command in the next line.
  • The next line defines the cheat code command. The first item passed to the cheat code is the name of the cheat code that will be typed into the in-game cheat console. The second part specifies that this cheat code will be used in Live mode in the game. After the sims4.commands.Command decorator (a python term), is a function that will run when the cheat code is called from the game. The first line of the cheat code function acquires a reference to the cheat UI’s output window.
  • The last line simply writes some text to the output window. In the game, you should see whatever you write in the script instead of «This is my first script mod».

Change this text in the last line to words of your choice. Click File> Save All or the Ctrl+S keyboard shortcut to save your changes.

3. Now that you have modified the example script, it is time to get it into the game. You should have a file called compile.py in your Example Mod folder. Running this python file will compile all of the .py files in your Scripts sub-folder into a .ts4script and copy it into your mods folder. It will be called [Your Creator Name]_[The folder name of your mod].ts4script. Right-click the compile.py and select «Run ‘compile'». You should now have a script file in your mods folder. In my case, it is called andrew_Example Mod.ts4script.

4. Start your game and make sure that script mods are enabled. Create a new game or load a save game. Once in Live mode, press ctrl+shift+c to open the cheat console. Type the word «myfirstscript» (without quotes) and press enter. You should see the text that you entered in step 3.

Creating your own mod:

Now that you have setup your tools, edited a python script, and compiled it for your game, it is time to get started with your own python scripts.

1. Right-click the example mod folder.

3. Right-click the «My Script Mods» folder and click paste.

4. Enter the new name for your mod.

5. In the scripts folder of your new mod folder, rename the .py file to a name of your choice.

6. Add or edit the .py files in the new Scripts folder.

7. Right-click the compile.py and run it to compile the scripts and load them in your mods folder.

Further Reading:

Now that you have learned how to get a python script into the game, if you aren’t already familiar, you should read up on how to work with python scripts. You may also want to read up on the documentation for PyCharm.

The unpyc3 script included in the project folder is from the open source project unpyc37

tedw
Member

Post by tedw on Nov 13, 2018 17:07:26 GMT -5

Thanks for the tutorial! Not sure if this is a change Maxis made (I don’t recall ever doing it) but the path to my game files is actually Origin Games > The Sims 4 > The Sims 4. Had to update the path in the settings for the decompile to accurately find all the game files.

Just a heads-up in case anyone else finds the same thing.

britalit
New Member

The Sims 4 Modern Python Modding: Ultimate Loading Guide

Oct 9, 2020 · 4 min read

This is the ultimate loading guide to how the game loads your script files. I sat down and tested numerous different combinations of trial and error in figuring out the loader. Here’s what I discovered:

Folder Structure

The top-level mods folder is meant only for packaged mods that end in ts4script or zip . If any folders are in this they are presumed to be a mod folder for extra organization, if any files are in this they are completely ignored.

The special Scripts fo l der mentioned below is treated like normal mod folder here. Thus Scripts/Scripts would still work but Scripts would not.

/Mods/Name of Mod

The folder directly underneath /Mods/ is presumed to to a mod folder for extra organization. This folder is given a special perk though. Like /Mods/ only ts4script or zip files are loaded and all files are ignored but unlike /Mods/ 1 additional folder is allowed in here and that is the Scripts folder.

Any other folders inside this are entirely ignored meaning extra organization can only go as deep as this one folder and no sub-folders.

/Mods/Name of Mod/Scripts

This is a special folder only allowed in the mod folder and intended to be for development only, files inside the Scripts folder can be nested many levels deep (only tested to 3 levels). The folder is recursively scanned for py files and, when found, are automatically loaded.

Any other files of any kind such as pyc , ts4script , or zip are completely ignored as they don’t belong in the special Scripts folder.

Another development benefit of this folder is you can re-load files from it anytime within a script while the game is running.

Packaged script files

The game loads only zip files, this includes zip files renamed to ts4script .

Only .py files

If you only have .py files in your zip folder then the game will not load them and will instead treat your mod as an empty mod.

Only .pyc files

If you only have .pyc files they are loaded as normal by the game.

Each version of python has a different code for .pyc this means if the games python version changes then your script will be attempted to load. Testing on incorrect python compilations revealed the game actually loaded the wrong compilation version sometimes successfully and strangely enough it has a higher success chance of loading the wrong compiled version if it’s in the /Mods/ folder and not a /Mods/Mod Folder sub-folder.

Most of the time, though, if your pyc file is compiled with the wrong version the game won’t be able to load it in which case it defaults to loading the py files. Since there are no py files in this case your mod will crash.

.py and .pyc files

If you have both .py and .pyc files then your mod is highly flexible but larger as it now contains duplicate code for every file (a compiled file and a source file).

This follows the same rules as above except the game will always load the py file. The pyc file will first be imported and then promptly deleted in memory followed by the compilation of the py file to a pyc file which will be imported to memory.

  1. Game imports pyc to memory
  2. Game deletes pyc from memory
  3. Game compiles py to pyc internally
  4. Game imports internally compiled pyc to memory

Since this is doing loading and deleting followed by compiling and loading and given the py file is going to be used anyways you might try and create an empty pyc file, especially since we already know the game will default to py if it can’t load the pyc . Unfortunately, an empty pyc file in this case results in a bigger crash and instead of the py file loading, your entire mod crashes. It defaults to py only if the pyc is a valid compiled file but the wrong compilation version.

.py and .pyo files

This is, strangely, your best option. When the game encounters a pyo file, even if it’s a phony/empty pyo file, the game solidly ignores it. It doesn’t try to import pyo , it skips it and jumps straight to importing the py file because it assumes it’s there.

  1. Game sees pyo
  2. Game compiles py to pyc internally
  3. Game imports internally compiled pyc to memory

This means you can add your py source files along with an empty pyo file next to each one and the game will jump straight to loading the py files. It means your mod is flexible, is much smaller (no source and compiled files together), loads faster (compiled is not uselessly loaded first and then deleted and then compilation and loading of py files.), and survives game python updates.

In fact the only issue you’d run into with this situation is this depends on the pyo backwards compatibility so in the future if they remove the pyo loading backwards compatibility because it’s too out-of-date then your mod will not load.

Take this into consideration, the normal procedure is to add pyc files and py files to a mod even though the pyc files are never used. This is what EA expects going forward so take caution if you take advantage of a backwards compatibility feature to have smaller mods as eventually the code for it will be dropped, the pyo files will eventually be ignored, and your mod will stop loading.

.pyd files

The game completely ignores and doesn’t look for pyd files.

I hope this helps

I felt there was some confusion or too much vague information out there so I wanted to do many tests of my own to figure this out. I hope this helps you decide what to do.

The Sims 4 Modern Python Modding: Part 1 — Setup

Why I’m writing this article

I’ve been programming for many years but I’m very new to Sims 4 modding and was ashamed and baffled by the state of Sims 4 scripting tutorials online. Most tutorials are from 2014–2018 and are terribly written and put together using bad teaching practices and are very much out of date. Explanations were also very lacking. You can’t just be told what to do, you obviously want to be a great modder and to do that you have to understand what you’re doing.

The tutorials are so bad that for the past 6 years all people have been talking about are how bad the tutorials are and how very few their are. I’m going to be hopefully writing better articles over a span of time, I know programming pretty well, I just have to figure out Sims 4 modding without much help online. My goal is to document what I’ve learned into tutorials with good explanations so you can stand on your own and take it further.

What you need before starting

I’m helping you learn how to make scripting mods for the Sims 4 written in Python, something that’s very lacking on the internet for the past 6 or so years. This means you need to know python at least a little. I’m new to python as well so you don’t need to know a whole lot to get started but I’m not going to take up article space explaining how to program and what programming tools you should use. I assume you know at least the very basics because if you don’t there’s a plethora of tools and resources out there to get you on your feet.

If you’re curious, the tool I use is the free version of PyCharm because it offers great code support and hints and works well with different Python versions. I encourage you to use whatever you want. Everybody has their preferences and I want you to stand on your own. Other great tools are VisualStudio Code , Notepad++ , Sublime , etc…

I also use Windows, I used Mac a long time ago but I don’t have a mac anymore so I don’t know how to translate these steps to Mac OSX. Hopefully though it’s not that difficult to follow if you’re on a mac.

The python version is extremely important

I’m just going to come out and say this, EA could make this all a billion times easier and it actually angers me they don’t.

You can’t claim to support the modding community and make it so easy to mod the game yet offer no help whatsoever to the modding process you created.

With that said, as of this writing, it’s vital you get the latest version of Python 3.7. I’m using 3.7.9. It can’t be 3.8 or any later version and it can’t be 3.6 or any earlier version. It has to be exactly 3.7. This is very important. This also assumes EA hasn’t haven’t upgraded the python version the Sims 4 uses (which they sometimes do). In the future this could be out of date but just know that if it EA changes it in the future it has to be the exact version they change it to.

You can find all the current latest python versions from here and as of this writing you need to download the latest 3.7 one. I have multiple python versions installed so I just download it to C:Python37 and chose not to add it to the system path because I hate dealing with multiple versions on the system path.

Normally I recommend for you to not to just blatantly copy me as this helps you to learn better instead of copying/pasting/replicating each step. However for Python, I do suggest installing it to C:Python37 or any path that doesn’t have spaces in it. If you can’t download it to C:Python37 you may can download it to C:UsersPython37 , C:UsersYourNamePython37 (If you don’t have a space in your name), or C:UsersPublicPython37 . There’s a step we’re going to do below that won’t work if you have a space anywhere in the path.

The Sims 4 python library

Remember when I said this angers me that EA says one thing and acts a different way to the modding community. Well, this is what I’m talking about.

In order to write python scripts for The Sims 4, you need to know how to interact with the game. To do that you need to know what code is available inside the game for you to work with. Normally EA would provide you with a specially licensed zip folder containing the files for you to look at and use for development purposes. Much like how Android, Bukkit, Skyrim, and a whole slew of other companies and projects do. It’s fairly standard practice that EA hasn’t gotten the memo on in over 6 years. This is not intuitive at all nor is it easy yet it’s highly critical so it’s the first thing we need to do and I’m sorry EA makes this so difficult.

Imagine someone gives you the recipe for a particular meal, but they actually just hand you the meal itself and expect you to figure out the recipe on your own. You need the recipe to make or modify it but your left with a very slow, bad, and error prone way to figuring it out on your own. This is exactly what we’re having to do in the next step.

Option 1: Automatic Setup

This is something new I rolled out very recently. I created a boilerplate/template project where you just download it, do some quick setup, drop script files in and it takes care of things for you like decompiling libraries and compiling/packaging your mod.

I recommend reading through to the end of the tutorial though, preferably parts 1 and 2 but at least part 1. The idea is to not have you become dependent on a template someone else made before you even know the ins and outs of what you’re doing.

If you’d rather skip to the automatic template anyways you can view the tutorial here, be sure to come back after your done to finish this tutorial and skip to step 5.

Option 2: Manual Setup

This teaches you how to form your own project so that you don’t rely on templates everytime, I recommend to start here so that you can understand what’s going on first and then can move to the template project.

Step 1: Create a development folder to house everything

I created mine at DocumentsSims 4 Projects and inside that I have the Tuning files which is outside the scope of this article along with the python files. You don’t have to, it just keeps everything nice and organized.

Step 2: Copy the python libraries to a working area

If you’re copying me you can create a folder inside your main folder, I named mine python . You can find these files in your Sims 4 installation, on Windows typically located at

C:Program Files (x86)Origin GamesThe Sims 4DataSimulationGameplay

But if you have a different installation they may be in a different location then. Copy the 3 zip files you see base.zip, core.zip, and simulation.zip. In the future if they’re are any more I’d copy them as well.

Inside these folders are pyc files. This means they are compiled python files and that means you can’t look at any of the contents inside them. If you can’t see inside them, then you can’t make python mods and without any help from EA we’re left to open them ourselves which is very error prone to warn you ahead of time.

Step 3: Unzip them

Unzip the files in the working directory, after doing so you can delete the copied zip files but I chose to stash them away in a folder called __originals . It’s up to you.

Step 4: Convert them back to python that you can look at

This process is actually not suppose to happen, it’s not normal or natural to decompile a python file. It’s buggy and error prone and takes a very long time. On my machine it took up to an hour. Many python files will not be able to be decompiled successfully. For every file that cannot be decompiled, it means that’s 1 less file you can use in the game in mods which is upsetting because to create amazing mods you want to know all the potential features you can use, not just the ones you were able to decompile.

Over the many years there have been all sorts of attempts are making a decompiler. The ones listed in tutorials online are often out of date and often use a homemade decompiler which isn’t as good and often has a ton of issues if it even runs at all. You need to use the latest decompiler which has the highest success rate for each file.

As of this writing, that decompiler is uncompyle6 and is easily installed through pip.

pip install uncompyle6

Because I’m not using the system path, this is how I installed it

C:python37python.exe -m pip install uncompyle6

It’s very important to install this to the python 3.7

Now you need to start decompiling, THIS WILL TAKE A VERY LONG TIME and several files will not decompile! The program has the ability to traverse all the python files and decompile them but it’s very buggy and often crashes so I highly recommend to use Windows Powershell to do this instead.

Open a powershell inside the python folder and execute the following command, the following comamnd is specific to powershell (Blue Background) not Command Prompt. It will not work in Comamnd Prompt (which is older and has a black background most people are familiar with).

What this big complicated command does is this:

  • dir -recurse -include *.pyc tells PowerShell to recurse through all the folders and files and look for files ending in .pyc
  • The next part is what PowerShell runs on every file that’s found, in our case we want to run uncompyle6 which is what we just installed above. It runs uncompyle6 and passes the pyc file and tells it to decompile it to the same filename but with a py added at the end meaning we’ll have a py file next to every pyc file.

After an eternity it finally finishes

The next important step we need to do is fix the file naming. Run this also in the same PowerShell. This renames all files from something like __init__.pyc.py to __init__.py which is important for python tools to offer proper help.

  • Get-ChildItem -File -Recurse loops through the folders and files again but all files. Instead of just running a command on each file it also passes additional about the file and path which we need to rename it
  • The other part tells PowerShell to rename .pyc.py to .py if the file ends with that.

You should have something that looks like this

Congratulations, you’re now done with the most difficult and longest part and you never need to do this again until they do a big update.

Step 5: Setup your editor

This can be something as simple as Notepad++ or Sublime up to something as big as PyCharm. Perhaps a middle ground like Visual Studio Code.

I can’t write help for every editor so I’m going to cover PyCharm. It’s completely free and the download link is above when I first mentioned it. Don’t just copy me though, use the editor you feel most comfortable using. many people prefer something simple like Sublime or Notepad++.

for PyCharm, anytime you create a new project, you need to select Python 3.7. Normally for the first time it’s not going to know where that is, you can skip this part if yours is already pointing to 3.7.

Click the 3 dots as shown in the image above to bring up another window. Click System Interpreter and the 3 dots again.

just select “python.exe” from the Python 3.7

Now we need to add the python libraries we decompiled, you will have to do this once on every new project. Open settings

and go to project structure. Click on “Add Content Root”

You need to add base/lib , core , and simulation . You can hold the ctrl key down and select multiple to do it all in one shot.

Make sure you select the lib folder inside of base as the image above shows. The base folder is a bit different. Now mark the 3 folders as source folders.

And you’re ready to start coding python

I know this was a very long tutorial

EA has made this so difficult to get started and some documentation and proper zip files would have been so much easier. We make do with what we have though and unfortunately this is how it has to be done currently.

I appreciate you taking the time to go through this initial tutorial. It’s lays out important groundwork and I tried my best to explain things so that you understand why we’re doing these things. The “why” helps you stand on your own and understand how to make your own decisions and not rely on stuff other people make which may be badly done and often breaks.

I hope you follow me into the later upcoming tutorials which hopefully won’t be near as bad and long as this one.

What’s the purpose of the 3 different folders?

  • base — contains low-level code. In plain English it means you won’t use this very often. Imagine asking you’re friend to hand you an apple. You have all the different steps to that like communication and gestures but in reality you don’t care about all the little steps to getting the apple, you just want the apple. That’s what “base” is. It contains all the hundreds or thousands of little steps to make different things happen and most of the time you’re concerned about the bigger picture. The only time you’ll go in here is when you’re making a mod that does some of the little steps a bit differently so you’ll need to borrow some of the pre-existing steps and make others on your own (such as asking your friend for a green apple in Spanish both of which may not be in “base” but still may share some of the same steps)….. Again this won’t normally be the case.
  • core — This is like base but groups little steps from “base” into generic tasks. You’ll be using this folder more often. Would you rather write down the 50 steps needed to ask your friend for an apple (base) or just one step (core).
  • simulation — This is the biggest folder you’ll use a whole lot! It contains all sorts of coding to control and manipulate most every aspect of the game. While “core” is for more generic code, “simulation” is for the actual gameplay and interface.

See you in Part 2

Next we’ll make a Hello World Program, I hope to see you then. Click here for part 2.

Python Scripting

The Sims 4 uses XML Tuning to store game data, and Python to interpret that data. Modders can use Python as a basis to create their own XML Tuning (for example, module tuning or test sets), to run a command from the game’s console, to store settings, to avoid overriding files, and more. The vast majority of mods can be made without scripting, but scripting is a required element for more advanced mods.

Contents

  • 1 Getting Started
  • 2 Types of Scripts
    • 2.1 Commands
    • 2.2 Injection
    • 2.3 Custom Tuning
    • 2.4 Settings
  • 3 Scripting Tutorials/Guides

Getting Started

To get started with Python scripting, visit this website (S4S Forum Post) to download and install Andrew’s starter project for scripting. This tutorial will cover the installation of Python 3.7.0 and PyCharm Community Edition.

Once the starter project is set up, you should mark all folders containing Python code as a sources root, so that PyCharm can help you write code correctly. This includes the base , core , generated , and simulation subfolders in the EA folder, as well as each Scripts folder in your projects. You can mark a directory as a sources root by right-clicking on it and using Mark Directory As > Sources Root. You will know that you’ve correctly marked the directory when the folder icon turns blue and you no longer see red lines under import statements.

Types of Scripts

There are many different kinds of scripts that one may need to write depending on the task at hand. This is not a comprehensive list, but it covers the most common uses for scripts.

Commands

Commands are scripts that can either be triggered by the do_command of interaction tuning or the game’s cheat console. This includes custom cheat codes.

Injection

Injection is an incredibly powerful form of script modding that is used to edit tuning at runtime. Injection may also be used to refer to the act of appending a custom function onto an existing class method, which triggers the modder’s script every time the class method is called.

Custom Tuning

Custom tuning files can be created with scripts, such as creating custom test sets that can parse original test syntax. This also includes custom module tuning, which can be used to store settings and tuning references for ease of use in other scripts and especially injections.

Settings

If a mod requires its own settings, it may do so with a JSON or CFG file which must be parsed with a script.

Scripting Tutorials/Guides

Scripting tutorials are the next step to creating a script for The Sims 4. Many of these tutorials aren’t easy to find as they are written in forums or on a blog post. This list will link to the various tutorials.

For loose leaf Scripting examples, please look here.

Моддинг The Sims 4 – способ столкнуться лицом к лицу со своими фобиями

Я считаю себя довольно уравновешенным человеком. У меня нет серьезных фобий, кроме боязни публичных выступлений. Мне не кажется, что у меня много личных проблем, и обычно я считаю себя (ну или, по крайней мере, представляю себя) человеком спокойным и расслабленным. В целом, я вполне доволен собой.

Но когда я просматривал моды для The Sims 4, я понял, что у меня не всё так радужно. Даже наоборот. Моды для The Sims 4 обычно состоят из небольших дополнений, а не из полных изменений, и просмотр этих модов сделал меня беспокойным, сомневающимся и гневливым. Странно! Оказывается, я не так-то и доволен собой.

Вечеринка окончена

Возьмите мод под названием «Less Waving Goodbye». В описании говорится: «Этот мод изменяет настройки, которые требуют, чтобы все Симы прощались со всеми кто покидает дом». Мод делает так, что только Симы в определенном радиусе должны будут попрощаться, когда другой персонаж покидает вечеринку. Все просто и понятно, но это заставило меня почувствовать тревожность.

Посиделки и вечеринки часто вызывают у меня чувство стресса. Однако, увидев этот мод, который делает так, что Симы не должны обращать внимание, когда кто либо покидает вечеринку, у меня появилось осознание того, что уход с вечеринки может быть более сложным, чем участие в ней. Когда наступает время покинуть вечеринку, вы чувствуете облегчение, которое, однако, быстро омрачается стрессом от ухода. Вы продержались на вечеринке, вы выжили, свобода близка, и скоро вы будете в безопасности, дома под одеялом, обновляя твиттер и просматривая подборку видео на YouTube.

Но сначала вы должны объявить, что уезжаете (задаваясь вопросом, нормальный ли вы человек, раз уходите раньше всех). Вы должны обойти всю вечеринку, чтобы попрощаться с каждым, либо прерывая их диалог, либо дожидаясь паузы. И всегда вас ожидает долгая беседа перед дверьми прежде, чем вы уйдете, несмотря на то, что вы проговорили всю ночь (о чем еще можно разговаривать?).

Плюс ко всему, что мне делать: обнять, пожать руку, поцеловать в щеку? Что мы делали в прошлый раз? Если раньше мы не обнимались, а сейчас обнимемся, то придется делать это каждый раз в будущем? Кроме того, существует вероятность, что здесь придется составлять планы на будущее («Что вы делаете в эти выходные?»), а это опять же новый стресс.

Возможность ускользнуть, попрощавшись только с человеком поблизости, что и позволяет сделать этот мод – вот как все должно быть и в The Sims, и в жизни.

Бомбочка для ванн

Этот мод под названием «Nap in Bath» кажется очень хорошим, ведь с его помощью Сим может вздремнуть в ванной. Учитывая то, сколько времени ему нужно, чтобы поспать и принять ванну, кажется очень полезным, что можно убить двух зайцев одним ударом.

И все же я сразу и безоговорочно отказался от использования этого мода. Сначала я подумал, что это связано с тем, что я больше люблю душ, чем ванну. Но все же это не объясняет то мгновенное отвращение, которое я испытал. После недолгих размышлений, я понял, что это связано с моим отвращением к людям, которые проводят слишком много времени в ванной, и все это связано с тем парнем из «Шоу Трумэна».

Когда я думаю о том, чтобы поспать в ванной, у меня получается только представлять парня из «Шоу Трумэна», который смотрел все шоу, не выбираясь из своей ванной. Это все, о чем я мог думать во время фильма. Кто-то смотрел его в баре, кто-то – сидя на диване, а этот парень смотрел его в ванной. Вот же черт. И он также спал в ванной. Зачем? Почему ты так долго там сидишь? Вода уже, скорее всего, грязная и комнатной температуры. Выбирайся оттуда! Ты ведешь себя странно, отвратительно, и пугаешь меня.

Самый ужасный страх

Несколько лет назад я мыл посуду, потом закончил, вышел из комнаты, но сразу вернулся, потому что оставил термометр для мяса сушиться на кухонном столе. Термометр был направлен вверх, прямо как штырь, и мне в голову пришла мысль, что если мой кот прыгнет на кухонный стол и ляжет, то этот термометр сможет проткнуть его насквозь.

Стоит упомянуть две вещи: во-первых, мой кот никогда за всю свою жизнь не прыгал на кухонный стол (по крайней мере, я этого никогда не видел). Во-вторых, если бы именно в этот день он решил бы прыгнуть на этот стол, ему пришлось бы лечь прямо на термометр всем своим весом, чтобы проткнуть себя. Этот страх так неожиданно поглотил всего меня, что я вернулся на кухню и положил термометр на бок (хоть я его не вытер и не убрал: я же не супер герой).

Как бы то ни было, я считаю, что мод под названием «Pets Do Not Have Fears» очень плох. Он позволяет домашним питомцам не бояться таких мест, как камин, микроволновка, печка, вакуум, туалеты и прочее. Это ужасно, потому что домашние животные должны испытывать страх, ведь я не могу остаться единственным, кто боится за их жизнь. Я не могу держать все эти страхи в себе.

Сущий кошмар

Этот мод называется «Sleepless Trait», и вот каково его описание:

Мне было достаточно прочитать только это, чтобы ощутить холодное и неприятное ощущение внизу живота. У меня было много проблем со сном на протяжении многих лет, начиная с многомесячных приступов бессонницы, парасомнии, слуховых галлюцинаций, синдрома беспокойных ног, тревожных снов, – все, что называется «синдромом взрывающейся головы». Меня мучило практически все, кроме лунатизма и убийств людей во сне.

В дополнение к тому, что я недостаточно спал и чувствовал себя, как зомби в течение всего дня, а иногда и месяцев, время отправления ко сну становилось сущей пыткой. Когда у вас уже есть проблемы со сном, вы боитесь идти в кровать, даже если хотите спать.

Поэтому, увидев этот мод, где вы можете наслать на своего Сима проблемы со сном, мне стало плохо. Не поймите меня неправильно: я делал со своим Симом ужасные вещи. Я даже делал ужасные вещи с домашними питомцами в The Sims. Но в моем сознании все это тускнеет рядом с проблемами со сном. Пусть у них будет хоть какая-то передышка от смоделированной жизни! Дайте им поспать.

Слишком много поваров

Я думаю, что очень приятно чувствовать себя с друзьями комфортно. Если у моего друга кончилась выпивка, было бы хорошо, если бы он, не спрашивая меня ни о чем, просто пошел и взял еще (в основном это связано с тем, что мне неохота вставать с дивана). Если ему нужно воспользоваться туалетом, очевидно, что ему не обязательно спрашивать моего разрешения. Но готовить еду? Он просто решил приготовить еду на плите? Или смотрел со мной телевизор, а потом пошел принять ванную?

Это кажется немного странным.

Этот мод навязывает, что для близких друзей и семьи – нет неуместного поведения. И семья – это не только супруги и дети, это также братья и сестры, бабушки и дедушки, двоюродные братья и сестры, дяди и тети. Вы можете ходить рядом, когда они голые (и наоборот). Вы можете быть недалеко, когда они пользуются туалетом или принимают душ. Этот мод делает всё, чтобы подобные вещи не заставляли смущаться.

Но нет, нет же, это не правильно. Если я увижу, как мой кузен сидит на толчке, это будет поводом для смущения. Это ненормально, если моя племянница войдет, когда я принимаю душ. И если мой хороший друг зайдет и сразу отправится к плите готовить, я воскликну: «Чувак, какого черта ты делаешь?»

Этот старый зануда

Увидев этот мод с ковром-пандой, шторами-пандой, стульями-пандой, куклами-пандой и покрывалами-пандой, я стал негодовать, но я сразу понял, почему: это все моя ненависть к ремонту. Это не имеет ничего общего с пандами. Я люблю панд! (Особенно красных, которые на самом деле не панды).

Я помню один из таких ремонтов, когда семья полностью изменила свой дом. У них был маленький ребенок, которого они спрашивали, что он любит, и ответом были динозавры или пираты, или что-то подобное. А потом они превращали детскую комнату в сцену из «Юрского периода» или делали ее аналогом пиратского корабля.

Конечно, для ребенка это было здорово, до тех пор, пока он не вырос и ему не стали нравиться Рейнджеры или покемоны. Нет никакой гарантии, что ребенок, которому нравятся динозавры, будет любить динозавров всегда. Кроме того, в какой-то момент родители могут захотеть продать дом, а скажите, скольким покупателям нужны три спальни и две ванных комнаты, где одна из спален – чертов пиратский корабль? Это бесит меня и как хозяина дома, и как ребенка, которому неделю назад нравились динозавры, а сейчас он без ума от Людей Икс.

Так вот, что мы имеем. Я не могу спать и ненавижу покидать вечеринки даже больше, чем принимать в них участие. Не спите в ванной и не готовьте еду у меня дома. Я не хочу, чтобы кто-то чувствовал себя комфортно, видя, как я испражняюсь, а ремонты и вовсе должны быть стерты с лица Земли.

Теперь я не чувствую себя уравновешенным. Я чувствую, будто я в аду. Спасибо вам, моддеры!

Источники:

http://laptrinhx.com/the-sims-4-modern-python-modding-part-1-setup-3529129242/

http://sims4studio.com/thread/15145/started-python-scripting

http://medium.com/@junebug12851/the-sims-4-modern-python-modding-ultimate-loading-guide-77ce1b68f1e7

http://levelup.gitconnected.com/the-sims-4-modern-python-modding-part-1-setup-83d1a100c5f6

http://sims-4-modding.fandom.com/wiki/Python_Scripting

http://genapilot.ru/modding-the-sims-4

Ссылка на основную публикацию
Статьи c упоминанием слов:
Adblock
detector