Author Topic: Python Learning Resources and Assistance  (Read 9549 times)

Offline dep88y

  • Posts: 51
  • Cookies: 0
Re: Python Learning Resources and Assistance
« Reply #20 on: January 01, 2009, 09:14:19 AM »
Thankyou. I do have a background in math and logic. I guess I have to ask anyway for fear and curiosity. Are you referring to the thought patterns in math and logic?
 Anyway, so I know what to do later, is there a program used to extract the scripts from BC?

Offline Voyager16

  • Modding is improving.
  • Posts: 310
  • Cookies: 9
  • KM - Mod Team Member
Re: Python Learning Resources and Assistance
« Reply #21 on: January 01, 2009, 09:53:30 AM »
I have a question 2.
I'd like to try this, but my math is really my weakest part.
So do you need it badly or can you manage without math knowledge?

Offline MLeo

  • Retired Staff
  • Posts: 3636
  • Cookies: 833
  • Software Simian
    • the Programming Pantheon
Re: Python Learning Resources and Assistance
« Reply #22 on: January 01, 2009, 11:33:37 AM »
Mathematics, Logic and Set Theory are at the basis of all programming. Yet not always directly. One could say most programming languages abstract them.


The main thing that you need is the ability to think logically, and to see (through) abstractions (and create them).

@Voyager16, read the tutorial, read it once through, and then start trying stuff in the (Python) command line. I would advise the Python command line, and not the BC console, it has some limitations.
I still can't read peoples minds, nor can I read peoples computers, even worse, I can't combine the two to read what is going wrong with your BC install...

"It was filed under 'B' for blackmail." - Morse, Inspector Morse - The dead of Jericho.

Offline Voyager16

  • Modding is improving.
  • Posts: 310
  • Cookies: 9
  • KM - Mod Team Member
Re: Python Learning Resources and Assistance
« Reply #23 on: January 01, 2009, 11:52:00 AM »
Thanks will try it.

Offline ACES_HIGH

  • BCC Roleplay Game Narrator
  • Moderator
  • Posts: 1678
  • Cookies: 54
  • while(!(succeed=try()));
    • BCC Roleplay Games
Re: Python Learning Resources and Assistance
« Reply #24 on: January 01, 2009, 03:09:31 PM »
Thankyou. I do have a background in math and logic. I guess I have to ask anyway for fear and curiosity. Are you referring to the thought patterns in math and logic?
 Anyway, so I know what to do later, is there a program used to extract the scripts from BC?
if you mean the .pyc files, no, they cannot be decompiled, but the Software Developer's Kit, or SDK, contains all of the stock scripts in an uncompiled form, as .py, these can be read in any text editor such as notepad, or with the python utility http://www.python.org/download/releases/3.0/

Offline MLeo

  • Retired Staff
  • Posts: 3636
  • Cookies: 833
  • Software Simian
    • the Programming Pantheon
Re: Python Learning Resources and Assistance
« Reply #25 on: January 01, 2009, 05:09:25 PM »
Actually, the py files contained in BC can't be read by the Python utility in Python 3.0, since it's a major release it contains breaking changes with previous versions (this is intentional, since they want to improve the language).
I still can't read peoples minds, nor can I read peoples computers, even worse, I can't combine the two to read what is going wrong with your BC install...

"It was filed under 'B' for blackmail." - Morse, Inspector Morse - The dead of Jericho.

Offline dep88y

  • Posts: 51
  • Cookies: 0
Re: Python Learning Resources and Assistance
« Reply #26 on: January 01, 2009, 07:06:26 PM »
Here's where my ignorance comes in. Which Python 3.0 should I download? Bzipped, Gzipped, ( I really don't know the difference from those and a standard zip), windows x86. I don't have an AMD 64 processor. Thanks

Offline dep88y

  • Posts: 51
  • Cookies: 0
Re: Python Learning Resources and Assistance
« Reply #27 on: January 01, 2009, 07:09:38 PM »
 I forgot one more thing. I can't find SDK. Where could I find it, please?

Offline MLeo

  • Retired Staff
  • Posts: 3636
  • Cookies: 833
  • Software Simian
    • the Programming Pantheon
Re: Python Learning Resources and Assistance
« Reply #28 on: January 01, 2009, 07:10:26 PM »
I think easiest would be to first download the 32 bit installer exe/msi (can't remember of the top of my head which).


The SDK can be found on BC files.
I still can't read peoples minds, nor can I read peoples computers, even worse, I can't combine the two to read what is going wrong with your BC install...

"It was filed under 'B' for blackmail." - Morse, Inspector Morse - The dead of Jericho.

Offline dep88y

  • Posts: 51
  • Cookies: 0
Re: Python Learning Resources and Assistance
« Reply #29 on: January 02, 2009, 10:23:16 AM »
I would really like to thank all of you for your help. I downloaded python and I'm sure I could learn it; it reminds me of math quite a bit. However, I downloaded the SDK and browsed through it. There are symbols in there that aren't on my key board and some tools won't open. I didn't try anything; I like to look at things so it's not a culture shock later. Anyway, I realized that I am no where near ready for such things. Using a program is one thing but knowing how it works is a much different thing. I wish I had grown-up with computers because I really enjoy using them. I don't have the foundation of knowledge to begin. I honestly don't know where to start because the classes I have found, even the basic ones, start with the assumption that I would know of things like DOS. I don't know what that is. I feel like I need to go back to the beginning but I can't find the beginning. Bottom line is; I QUIT. I'll just enjoy your work in the game. Thank you again.

Offline MLeo

  • Retired Staff
  • Posts: 3636
  • Cookies: 833
  • Software Simian
    • the Programming Pantheon
Re: Python Learning Resources and Assistance
« Reply #30 on: January 02, 2009, 11:20:58 AM »
The py files are just plain text (ASCII). It should not contain any text that you can't express with your keyboard.
Unless you are on a Kana/Kanji keyboard.
But then how you are writing this?
I still can't read peoples minds, nor can I read peoples computers, even worse, I can't combine the two to read what is going wrong with your BC install...

"It was filed under 'B' for blackmail." - Morse, Inspector Morse - The dead of Jericho.

Offline dep88y

  • Posts: 51
  • Cookies: 0
Re: Python Learning Resources and Assistance
« Reply #31 on: January 02, 2009, 12:42:31 PM »
I guess it might be more accurate to say that I could learn Python, but, I still wouldn't know what I was doing. I would need someone to walk me through it in person because I lack an overall understanding of the process. I would need someone to tell me what I was changing ( a phaser,a torpedo, shields and then what I was changing like yield strength, speed, color). I looked at a hardpoint file and saw the different subjects like torpedos, shields, hull and phasers, but each line I wouldn't understand even knowing Python. It's like learning a foreign language. You may know the words and punctuation, but, unless you know how to form a sentence or conjugate a verb; your speaking jibberish.
I guess I feel I'm missing an understanding of the finished product. Like, what makes the ship look the way it does. You see I don't know how any of it is done. I am a visual learner, and my experience in life is that doing something is far easier than it sounds; at least for me it was. I know everybody is not the same. The most difficult thing for me is trying to answer the questions I have on my own because I don't know the computer lingo. I have been trying to find resources to try to learn but the lingo makes my search impossible. The search engine can only find the words I put in, sooo, if I don't use the correct words, the computer can't help me. This is all clear as mud for you to read; I apologize for that. I don't express my thoughts very well at all.

Offline MLeo

  • Retired Staff
  • Posts: 3636
  • Cookies: 833
  • Software Simian
    • the Programming Pantheon
Re: Python Learning Resources and Assistance
« Reply #32 on: January 02, 2009, 03:19:27 PM »
Well, the tutorial is also part of the learning the "grammar".

The BC specific things aren't really part of the language, they are a "library" of "words".


In this case, it would be best to just try.

One good and usefull thing is the reload() command, if you import, say, a torpedo, in the console. And then call reload on it. Then BC will also reload the torpedo, so the next time you fire it, it will show the differences.

In programming, you have a problem you want/need to solve. And you use the language to express what you want it to do. Using 1 or more libraries.
I still can't read peoples minds, nor can I read peoples computers, even worse, I can't combine the two to read what is going wrong with your BC install...

"It was filed under 'B' for blackmail." - Morse, Inspector Morse - The dead of Jericho.

Offline teleguy

  • Posts: 363
  • Cookies: 53
Re: Python Learning Resources and Assistance
« Reply #33 on: June 24, 2009, 09:20:42 AM »
I just saw this and thought I'd post that here, so that we don't lose it when BCU dies.
Quote from: Sim Rex
OK, here we go with the first lesson on our Mission Scripting for Beginners course.

My e-mail and MSN address is simrex@hotmail.com - please feel free to use it or this board's PM system to ask for further clarification/explanation as necessary. You could also ask in this thread.

Now, let's cut to the chase... BC's scripting language is Python. Python is a language in its own right, just as complex and flexible as any other programming language. Books have been written about it. Obviously, I am not going to be able to go into that kind of depth as part of this course! I do, however, think it is important that you grasp a few basic concepts before we even start looking at a mission script.

Those of you who are conversant in Python already, or who have worked through the Instant Python tutorial I suggested may want to skip Section 1.

Section 1 - Basic Python

First step - this will be made a lot easier if you get hold of the right tools. If you're a Windows user, I strongly recommend that you download the PythonWin IDE distributed by ActiveState here. It is FREE and has lots of useful features. For non-windows users, go here and choose the appropriate Python download.

If, for some reason, you are unable to download any version of Python, you will still be able to code in Notepad, but you will not be able to actually run your code until we start working on BC-specific Python.

Now, assuming that you have the PythonWin IDE (or IDLE for non-Windows users) I suggest you open the program now. You should see something like the image below:



The actual words in the blue text may differ, but don't worry about that. The Interactive Window allows you to type code directly into the Python interpreter after the >>>. To some of you, this may be familiar - the BC TestMode Console is a version of this.

So, now we have our interpreter ready and waiting - so let's see what we can do! It's traditional in these circumstances to make a little program to say "Hello World". In Python, that's really very easy to do. The code to type in is:

Code: [Select]
print "Hello World!"
Nice and easy. The print command is well worth remembering - we will be using it a lot later!

Now, let's make things a bit more complicated! Press enter at the end of each line.

Code: [Select]
greeting = "Hello World!"
print greeting

This code will produce exactly the same output as the first snippet. The only difference is, we created a variable, greeting, to store the information we wanted to print to the screen. There are a large number of things a variable can refer to, called data types, but we will cover these as we come across them.

"Hello World!" is in speech marks. This tells Python that Hello World! is what programmers call a string. If you remove the speech marks, the interpreter will raise an error. However, try the following:

Code: [Select]
greeting = 5
print greeting

There are no speech marks, but there is also no error. That is because numbers are a different sort of information than strings. I will cover other data types as they become necessary.

Another more complicated way of saying "Hello World!" is the following code:

Code: [Select]
def SayHello():
   print "Hello World!"
SayHello()


Note the indentation! Your interpreter should automatically indent the second line. It will try to indent the third line, as well, so press enter twice after "Hello World!".

What we did with those first two lines is the following:

1. Inform Python that when we type SayHello(), it should do something special.
2. Told it what to do in that case.

SayHello() is what programmers call a function. It is simply a set of instructions. Missions normally have a lot of these.

You can pass information into functions by using what programmers call arguments. An example of that is below:

Code: [Select]
def SayWord(ThingToSay):
   print ThingToSay
SayWord("Hello World!")


Note that just typing SayWord() will not work anymore. That is because we have told Python to expect something in the brackets. You can have as many arguments as you like in a function, but the more you add, the greater the possibility of confusion.

Now, there is one last thing I want to do to round off this brief introduction to Python.

Data types can have functions. That possibly sounds confusing, so let's look at an example.

Code: [Select]
greeting = "Hello World!"
greeting.count("l")


What we did here is used greeting's count function to count how many "l"'s there are in "Hello World!". The functions available depend on the data type. We may look at this in depth at a later stage, but for now it is enough to just recognise that is what's happening.

One last quick point - when you are coding in a .py file, it is common practice to put comments in to remind yourself and others what it was your code is supposed to do. In Python, you start a comment by typing #. Nothing on the rest line will be read by the interpreter.

So, that's a brief briefing in Python! Now you're fully equipped for section 2!

Section 2 - A Mission Template


We're going to start off fairly slowly with actual mission coding, because some people have just trawled through a very long, fairly dry Introduction to Python.

There should be a zip file attached to this post. Please extract this to your BC/Scripts/Custom directory. If it is going to overwrite something, please DON'T LET IT! I will happily make a revised, safe version.

Now, using your Python IDE or text editor of choice, open up BC/Scripts/Custom/Testing/Episode/Template/Template.py.

Template.py contains the absolute bare minimum for a mission to load up properly in Bridge Commander. We're going to go through this file, and I'll explain what it is doing at each stage.

First of all:

Code: [Select]
import App
import loadspacehelper
import MissionLib

These lines each import a module. This provides us with access to functions within those modules using the syntax that I introduced at the end of Section 1, e.g. App.FunctionName()

Code: [Select]
def PreLoadAssets(pMission):
   # Pre-create one Galaxy.
   loadspacehelper.PreloadShip("Galaxy", 1)

The PreLoadAssets function is called automatically by the game. As the comment in the file says, this preloads the ships to keep game performance smooth. The syntax is fairly straightforward - to preload five warbirds, you would add a line so that it would read:

Code: [Select]
def PreLoadAssets(pMission):
   # Pre-create one Galaxy.
   loadspacehelper.PreloadShip("Galaxy", 1)
   loadspacehelper.PreloadShip("Warbird", 5)

Moving on,

Code: [Select]
def Initialize(pMission):
   # Specify (and load if necessary) the player's bridge. This is only
   # necessary for the first mission in the game, unless you're switching
   # bridges.
   import LoadBridge
   LoadBridge.Load("GalaxyBridge")

   # Create the regions for this mission
   CreateRegions()
   
   # Create the starting objects
   CreateStartingObjects(pMission)

Initialize is also called automatically by the game. As you can see, in this section the bridge is loaded (you could replace "GalaxyBridge" with "SovereignBridge" if you wanted) and two other functions are called - CreateRegions and CreateStartingObjects. Those are defined below.

Code: [Select]
def CreateRegions():
   # Biranu 1
   import Systems.Biranu.Biranu
   pBiranuMenu      = Systems.Biranu.Biranu.CreateMenus()
   pBiranu1Set = MissionLib.SetupSpaceSet("Systems.Biranu.Biranu1")

This code sets up the planetary systems you want to have available for the player to fly to. Note, you have to add each planet set specifically - although the menu will have been created to allow you to warp to any planet in the Biranu system (although there are only two), you won't be able to use the Biranu2 set properly unless you have set it up here.

I will come back to look at this code more closely in a later session.

Code: [Select]
def CreateStartingObjects(pMission):
   # get the sets we need
   pBiranu1Set      = App.g_kSetManager.GetSet("Biranu1")
   
   # Create the ships that exist at mission start
   pPlayer         = MissionLib.CreatePlayerShip("Galaxy", pBiranu1Set, "player", "Player Start")

This function would normally be used to create all of the ships that are present at the start of the mission. In this instance, that is only the player. I will also come back to scrutinise this code more closely in a later lesson. For now, I will just tell you that to change the player's ship class, you would replace "Galaxy" with whatever other ship class you wanted.

Code: [Select]
def Terminate(pMission):
   # Clear out all the systems in the set course menu.
   App.SortedRegionMenu_ClearSetCourseMenu()

Finally, we have the Terminate function. At the end of a mission, this is called automatically to unload some of the things that we have loaded. I will refer to this as and when it is necessary.

So, that's a basic mission template, and that's the end of my first lesson. If you have any questions about the material, or any comments that would help me to write a better lesson next time, as I said at the start, my e-mail/MSN address is simrex@hotmail.com.

Before the next session, a suggested exercise would be the following:

Edit Template.py to do the following:
1) Preload three Sovereign class ships.
2) Change the loaded bridge to Sovereign
3) Change the player ship to being a Sovereign
4) Create a function that will display "Hello World" on the console (search the forums for help on TestMode if you're not sure how to show the console).
5) Call that function in the Initialize section of the mission script, then load up the mission to check you've done it right!

I will gladly accept Template.py files for checking, at the same e-mail address as above. Although some of these tasks may seem trivial, it is important to get a thorough understanding of the basics, otherwise when we move on to more complicated subjects, you will have difficulty!

The next lesson will be posted when I think the group as a whole has finished Lesson 1. Thanks for your time, and good luck

-----------------------------
Quote
Might also be worth mentioning that when you load up ships, sets etc that everything quotes is case senstive.

Quote:
Code: [Select]
# Create the ships that exist at mission start
pPlayer = MissionLib.CreatePlayerShip("Galaxy", pBiranu1Set, "player", "Player Start")


'Galaxy' can also be 'galaxy' depending on the case of the ship py(c) for example.


Quoted from here.

Offline teleguy

  • Posts: 363
  • Cookies: 53
Re: Python Learning Resources and Assistance
« Reply #34 on: June 24, 2009, 09:21:45 AM »
Quote from: Sim Rex


Okay, this is lesson two of my mission-scripting tutorial! I'm going to start by picking up where we left off in the mission script last time, looking at how to load up the ships we preloaded in the last session. After that, we'll look at adding more planetary sets into our mission. Then finally, we'll take a brief look at using the in-game editor to add ship placements.

Section 1 - Loading Ships

As a quick refresher to get you back into what we were doing last time, open up Template.py and set the game to preload the following ships:

1 Galaxy, 1 Ambassador, 1 Nebula, 1 Vorcha, 3 Birds Of Prey

Remember, you have to use the name of the ship's .py file in Scripts/Ships here, and it is case sensitive!

Once you've done that, scroll down to the CreateStartingObjects function. Reset the player ship to Galaxy if it is still on Sovereign from last time.

Now, we want to add the ships we just preloaded, so that they will appear ingame along with the player ship. An example of how to do this is shown below:

Code:
Code: [Select]
  pUSSZhukov  = loadspacehelper.CreateShip("Ambassador", pBiranu1Set, "USS Zhukov", "USS ZhukovStart")

pUSSZhukov is a variable. The data type it stores is the game's representation of a ship. The arguments for the CreateShip function are Ship Class, Planet to start at, Ship Name, Placement point to start at.

Add the line of code above to your Template.py file, and then try to do the same for all of the other ships that we preloaded. Give each ship a Placement point named like the example above - we will be creating these points later in the ingame editor!

Now, the game needs the ships to be assigned to groups for the AI. At some point later in this course, we will look at creating our own AI. For now, we will just put them into the groups. Let's do the Friendly group first:

Code:
Code: [Select]
  pFriendlies = pMission.GetFriendlyGroup()
   pFriendlies.AddName("player")
   pFriendlies.AddName("USS Zhukov")

The code here is fairly self-explanatory. The first line creates a variable, pFriendlies, which stores the current mission's Friendly ship group. Then, using the AddName function of pFriendlies, we add the friendly (in this case, Federation) ships to the group. You will have to add the Nebula-class ship yourself, because I didn't specify the name you should give it.

To access the mission's Enemy group, the code is very similar. Try using the GetEnemyGroup function of pMission to add all of the Klingon ships to the Enemy group.

If there were any Neutral ships, you would add those in exactly the same way, using the GetNeutralGroup function of pMission.

Section 2 - Adding more Systems

So far in our mission, we have only loaded up one single planetary set. Clearly, any good mission is going to be set across several different systems, so let's look at how to add more.

Find the CreateRegions function in Template.py. It should look like this:

Code:
Code: [Select]
def CreateRegions():
   # Biranu 1
   import Systems.Biranu.Biranu
   pBiranuMenu      = Systems.Biranu.Biranu.CreateMenus()
   pBiranu1Set = MissionLib.SetupSpaceSet("Systems.Biranu.Biranu1")


We'll start by adding the Biranu2 set. That is the only other planet in the Biranu system. Doing this is actually very simple - just copy the last line, paste it in below, and replace Biranu1 with Biranu2 in the new line. All of the code to actually set up the system is in the file Scripts/Systems/Biranu/Biranu2.py. You have just told MissionLib to load up that file, which Python sees as "Systems.Biranu.Biranu2".

Now we've added the whole of the Biranu system - let's add a different system as well. Open the Scripts/Systems directory and choose which one you would like to add. I would advise against any of the Multi systems, DeepSpace, DryDock or Starbase12 for now, because they are exceptions to the System naming conventions.

Open the directory of the system you want to add, and check how many planets it has - you wouldn't want to load planets that don't exist! Now, to tell the mission to load up that system, you should just be able to copy and paste the Biranu loading section and replace Biranu with the system name of your choice. Now, I'll talk through the code line by line to explain what that actually does...

The first line, import Systems.SystemName.SystemName, tells Python to load the file Systems/SystemName/SystemName.py (or .pyc). Take a look in the BC SDK to find the .py version of the file, and open it in your IDE. You should see a fairly empty file with a CreateMenus function in it, and very little else. Don't worry about the actual code here - we will look at system creation at some point later in the course.

The second line create a variable, pSystemNameMenu, which will store information on the system menu you create. Note that the function used here is the CreateMenus function from the file we just opened. The more adveturous among you who want to use the non-standard systems would have to look in the SDK to find the file which contains CreateMenus for those systems.

Finally, we add the planets as discussed above.

Section 3 - Placements

To set the starting positions of ships (and later, other important positions such as waypoints), you could try to do it create the file by hand in your Python IDE, but I would recommend against this unless you have an outstanding ability to imagine 3-dimensional points in your head. Fortunately we have another, more graphical, option - the ingame placements editor.

NOTE - The following section of the tutorial is based heavily on a tutorial I previously released dealing with this subject.

First of all, open BC using -TestMode. Then, load up your mission ingame. Now, you'll see that all of the non-player ships are clumped together, one on top of the other.

To open the Ingame Editor, bring down the console and enter Edit().

Immediately, the screen layout will change - there will be a blue menu to the left of the screen with lots of options on it. At this stage, I will not be covering the more advanced features - I'll explain them as we need to use them.

The first thing you need to get to grips with is navigation within the Editor. You can move your camera viepoint using the arrow keys. Left and Right will cause you to strafe, Up and Down will move you forward and backwards. You can change the direction the camera is looking by holding down the mouse button and dragging the mouse.

Now, let's get going on Placements. First of all, click the Toggle Placements button in the blue menu. Now, to place a point, position your camera in the place and direction you want the ship to be facing, and click "Insert Object" from the menu to the left. There will be a big red object in your view - that is the placement. It should currently be selected. Now click "Edit Name", and type in a new name for your point - "USS ZhukovStart", for example. Now just work through and add all of the start points that you named in Template.py.

If you put a placement in the wrong place and want to move it, click the "Select Next" button until the placement is highlighted in red. You can then either click Obj to Camera to move the placement to the new position of your camera, or you can click Move Object and use the arrow keys and mouse to move it around in the same way as the camera. Remember to press Move Object again when you're finished so that you take control of the camera!

For future reference, if you want to add placements in a different system, you need to click "Switch Sets" and type in the name of the system you want to change to, e.g. Biranu2

Once you've positioned all your ships, click "Save" in the menu to the left, then enter a new MISSION PLACEMENTS filename (the lower of the two options, NOT the top one). In this instance, the placement should be called Biranu1_P.py.

When this is done, click save, and leave BC. The placements file will be in your Bridge Commander root directory. Move it to Custom\Testing\Episode\Template.

Now let's go back into Template.py and tell the mission to use the placements file.

Find the line in CreateRegions where you loaded the Biranu1 system and assigned it to pBiranu1Set. At the end of that line, press Enter and add the following:

Code:
Code: [Select]
  import Biranu1_P
   Biranu1_P.LoadPlacements(pBiranu1Set.GetName())


The first line loads up the placements file that we just placed in the mission's directory. Note that we didn't have to say import Custom.Testing.Episode.Template.Biranu1_P. That's because Python is clever enough to look in the directory your current file is in for any other files you tell it to import.

The second line calls the LoadPlacements function in the file.

And that's all for this lesson! There were quite a few new concepts covered, so it would be well worth getting some more practice. Probably the best thing to try out right now would be to add some more ships, including some neutral ships, and put some of them in systems other than Biranu1. I know I haven't talked through adding ships in different systems, but you should be able to extrapolate how from what we have already done. If you have any problems, I will be on MSN Messenger or you can e-mail me at simrex@hotmail.com. As always there is also this thread to respond in. Note, for people who subscribed to this course at the beginning, if my MSN status is Busy, I will still be willing to answer your questions. If my status is Away, you can try asking, but be prepared to wait.

I'm also open to any feedback you have - certainly while writing it, I felt that this lesson had a slightly different style than the last one, because I'm trying to make you work out what to put rather than telling you directly. Let me know if that's a good or a bad thing!

http://bridgecommander.3dactionplanet.gamespy.com/phpBB/viewtopic.php?t=16532

Offline teleguy

  • Posts: 363
  • Cookies: 53
Re: Python Learning Resources and Assistance
« Reply #35 on: June 24, 2009, 09:22:11 AM »
Quote from: Sim Rex
The next few lessons deal with creating AI. jwattsjr, BCU's resident BC AI expert, wrote these lessons.

Hi folks. First off, I?d like to thank Sim Rex for inviting me to write this tutorial. I?m honored to play a small part in what is shaping up to be an invaluable tool for increasing the longevity of BC. You?ll have to bear with me, since this is the first tutorial I?ve written in a long time. If I?m unclear about something, don?t hesitate to ask, either in this thread, via PM, or you can add me to msn or email me at jwattsjr@hotmail.com. (Be sure to put something in the subject line that?ll get my attention? ?AI Tutorial Question?, for example.) Just as Sim Rex said, if my msn status is ?Busy? you can still contact me, but if it?s set to ?Away?, be prepared to wait a while for a reply. Now that that?s out of the way, let?s take a look at what?s needed to create an AI?


Section 1: Requirements
Here?s a list of what required.
The BC SDK
An installation of Python
Python MegaWidgets

The SDK contains, among other things, the editor required to create/edit AI scripts. It?s called AIEditor.py, and will be in the Tools subdirectory of the SDK. If you don?t already have the SDK, you can download it from bcfiles (http://bc.filefront.com/file.info?ID=2455f). The AIEditor is a python script, so it will require that python be installed on your system (which isn?t a problem in this case), but it also has two other requirements. The first is that the SDK must be installed to C:\Utopia. AIEditor expects the scripts to be in C:\Utopia\Current\Build\Scripts. The way I did it was to install the SDK in one of my BC installs, and then copied the SDK Scripts directory to the proper location. That way, I have a back up of the SDK scripts. Wink
The second requirement is the Python MegaWidgets (http://pmw.sourceforge.net/). You?ll need an archive utility capable of handling .gz files to install PMW. Both winzip and winrar (http://www.winzip.com/ or http://www.rarlabs.com/) will do the job. Installation of PMW is straightforward and instructions are available at the link listed above. This leads us to?


Section 2: The AIEditor and Our First AI
Now the fun begins. Browse to your SDK Tools/AIEditor subdirectory. You should see the icon for AIEditor.py. at this point, I?d recommend creating a shortcut to it for easy access. I put mine on the desktop. Anyway, click on it, and you should get a window something like this:



Maximize the window to increase the workspace. It?s not required at this point, but complicated AI?s won?t fit if you don?t. Now, let?s create a simple AI that moves a ship forward through space. Click the ?Create AI? box, and then ?Scripted (Plain)? from the dropdown menu. You should now have a box like this:



Left-clicking and holding down the button on the ?Scripted? box will allow you to drag the box to a different location on the screen. (This will be needed soon.). Right-click on the ?Scripted? box, and a new window will pop up:



The first item, ?Name?, is actually a variable assigned within the script that will be generated when the AI we?re building is saved. Because of that, the normal rules about variables in python apply (no special characters, no spaces, etc.). You?ll want to name it something more informative than ?Scripted?, though. I?d recommend something that resembles what the component is for, but doesn?t run the risk of conflicting with other module or function names. I chose ?FlyForward?, and the reason will become apparent momentarily.

The next item is the ?Interruptable? checkbox. Most of the time, you?ll want to leave this checked. It determines whether or not other events, conditions, etc. can interrupt this part of the AI. Next is the list of script modules. For ?Scripted (Plain)? modules, this is a list of AI modules found in C:\Utopia\current\Build\scripts\AI\PlainAI (and why I chose a different name for the component). For this part of the tutorial, we want the ship to fly forward, so click the ?GoForward? radio button. This will cause options to appear in the next item, ?Available setup functions":



You?ll notice that ?SetImpulse? is red, and this means that this function must be used. (It?s also the only one in this case). Once you click the checkbox, you?ll notice that ?fImpulse? is no longer grayed out. ?fImpulse? is the actual variable used by GoForward.py, and needs to be replaced with a numerical value between ?1.0 and 1.0 (full reverse and full impulse, respectively). For now, set it to 1.0, and click the ?Ok? button. The window will close, and you?ll notice that the box now says ?FlyForwad? instead of ?Scripted?. We?re almost ready to save our first AI, but before we do, there?s some things I want you to take a look at, and some things to consider. First, we?re going to take a quick look at the ?Advanced? menu? Click on the ?Advanced? box, followed by ?Edit Pre-AI save text?. This will open a simple editor that can be used to edit any of the script before the actual AI code. There should be two lines of code:
Code:

Code: [Select]
import App

def CreateAI(pShip):

As you can see, the code defines a function that requires one variable to be passed to it. In this case, it?s just a variable for a ship this AI will be assigned to. For now, that?s all we need to know. Later on, there will be other variables, and they may need to be edited. Click ?Ok? or the ?X? to close the window. Just a side note, but I prefer to do all my editing using the IDE, since AIEditor?s window doesn?t have auto-indentation, color-coding, etc.


Section 3: Saving the AI
Before we save the file, there?s some things I want and need to go over. I don?t particularly care for the open/save box written for the AIEditor. Its biggest shortcoming is that there is no provision to switch to a different drive. In other words, if your BC install is not on drive C:, you?ll have to manually type in the full pathname to open or save a file. Also, the default directory for the editor?s open/save dialogs is C:\Utopia\current\Build\scripts. Because of this, and the fact that I prefer to keep my AI?s as modular as possible, I save my AI?s in a subdirectory that?s easy to navigate to:
C:\Utopia\current\Build\scripts\Mine.
This has the added benefit of not cluttering up the SDK. Once the file is saved, I simply copy it to the appropriate subdirectory. For us, that currently means BC_DIR/Scripts/Custom/Testing/Episode/Template/. It?s up to you to decide whether or not you want to save directly to the mission directory. Regardless of which method you choose, I?ll help in any way I can should you have problems.

So, without further delay, let?s save the file. Click on ?File?, then ?Save AI?. Use the dialog box to browse to the appropriate directory, then enter ?GoingNowhereAI.py? in the ?Enter filename? box. Finally, click on the ?Save? button. That?s it! You?ve successfully created your first AI! Grin

Section 4: Adding the AI to the Mission
Open Template.py for editing. The first step is to create a new function called SetupAI(). The logical place to add it is immediately after CreateStartingObjects() since the next step after creating and grouping the ships is to give them AI. There are several steps to this function, and they are:
Importing the AI(s)
Getting the system(s) the ship(s) is/are in
Getting the ship(s)
Assigning the AI to the ship(s)

Let?s take a look at the code:
Code:

Code: [Select]
#######################################################################
#   SetupAI()
#
#   Assigns AI to objects created in CreateStartingObjects()
#######################################################################
def SetupAI():
   import GoingNowhereAI

   # Get the necessary Set(s)
   pBiranu1Set = App.g_kSetManager.GetSet("Biranu1")

   # Get the Ship(s)
   pUSSZhukov = App.ShipClass_GetObject(pBiranu1Set, "USS Zhukov")

   # Assign the AI
   pUSSZhukov.SetAI(GoingNowhereAI.CreateAI(pUSSZhukov))

First, you?ll notice that no variables are passed into the function. Next, the AI module is imported. The line that gets the system defines a variable that calls the GetSet function in App.py. GetSet() requires the system name to be in it?s filename format. For example, if we wanted to get Tevron 2, we?d use Tevron2 since the filename for that system is Tevron2.py.
The next line assigns a variable to represent the ship. Again, by calling a function in App.py. It requires two things to be passed to it. The system variable we just created, and the actual name of the ship.
Finally, we assign the AI. The code is in the form of:
Code:
Code: [Select]
variable.SetAI(Module.Function(variable))
In the next lesson, we?ll be adding more variables, aka ships, planets, etc. For now it?s just important to know that the first variable (the only one in this case) passed is the ship we?re assigning the AI to. You may have also noticed that I used variables that have already been used in other functions. While some programming languages don?t allow this, python does since the variable is isolated within a function and isn?t a global variable..

The final step is edit add a line of code to Initialize() to call the SetupAI() function. The position the code is added is important. It must be placed after CreateStartingRegions() and CreateStartingObjects() or exception errors will be raised Here?s an example:
Code:

Code: [Select]
def Initialize(pMission):
   # Specify (and load if necessary) the player's bridge. This is only
   # necessary for the first mission in the game, unless you're switching
   # bridges.
   import LoadBridge
   LoadBridge.Load("GalaxyBridge")

   # Create the regions for this mission
   CreateRegions()
  
   # Create the starting objects
   CreateStartingObjects(pMission)

   # Assign AI's
   SetupAI()
That?s it. Save the changes, and test the mission. Once in game, you should find that the Zhukov immediately accelerates to full impulse. For practice, assign the AI to at least two other ships. If you want to see exactly how unintelligent this artificial ?intelligence? is, use the placement editor to position two ships in the same plane, facing each other with about 30km separation. They?ll crash into each other, since there?s no collision avoidance component in the AI. We?ll cover that, and more by creating more useful AI?s in the next lesson.
-Jeff
http://bridgecommander.3dactionplanet.gamespy.com/phpBB/viewtopic.php?t=16589