1. This forum is obsolete and read-only. Feel free to contact us at support.keenswh.com

Programming Code Example: Explained

Discussion in 'Programming Guides and Tools' started by Textor, Dec 30, 2014.

Thread Status:
This last post in this thread was made more than 31 days old.
  1. Textor

    Textor Junior Engineer

    Messages:
    775
    Since a lot of people aren't familiar with C#, I thought I'd run through the example code posted in the screen shot to try to make it less scary for those who aren't programming-inclined, but might be willing to give it a shot when the code block is implemented. This is meant to be simple. This will not teach you how to code in C#, only how to read the code we have seen. I CAN go into a lot more advanced topics, but the intent is to make C# not as intimidating, so I might slightly "fudge" information or use different terminology for ease of understanding. If I end up doing a proper C# tutorial when the code block is released, I'll be a lot more strict with the information I'm imparting since it is important to do so. Keep in mind that we have seen about 20 lines out of almost 50 in the code, so don't read into things overly much.

    I'll start with what I can intuit from the UI:

    [​IMG]

    1. Line - This indicates the Current Line/Total Lines In The Code
    2. Check Code: This ensures that you have a properly formatted code and should indicate errors with the language syntax. Typically this is used in conjunction with the line numbers to help programmers figure out where an error is (error on line 11, etc.)

    Now, onto the "scary" bits:

    C# is Case Sensitive - A variable named "name" is NOT the same as a variable named "Name" or a variable named "nAme". You should not abuse this, however, because if your variables are all "variable" "vAriable" "vaRiable" etc. you will soon get confused and unable to figure out what the hell your code is doing.

    Semicolon ( ; ) - Used to terminate a line. Basically tells C# that "I'm done here." This is important to note, because until a ; is reached, the compiler ignores (most) whitespace.

    Basically:

    Code:
    int i=1;
    is the same as:
    Code:
    int i = 1;
    is the same as:
    Code:
    int i
    =
    1;
    
    Variable - a "typed" (narrowly-defined) word that contains information.

    Type - the "definition" of what a variable can contain. For instance, an "int" is an "integer" or a "whole number" -- 1, 2, 3, etc. NOT 1.01, 3.14 (these are not whole numbers).

    Types (as seen in the code example. This is not an exhaustive list of types in the C# language.):

    string - a string is basically what you are seeing now, in terms of programming. It contains "text" (which can either be human readable or not human readable.)

    bool - boolean, basically true/false.

    List - makes a "list" of another type of variable. If you have integer variables var1, var2, var3 and want to "group" them, you can make a list<int> to make a list of "integer" variables.

    int - integer variable. Contains whole numbers.

    void - no type assigned. This is not used for variables, but for methods (explained a bit later).

    For instance:

    Code:
    string hello = "Hello, World";
    is a string variable named "hello" that contains "Hello, World" (without the quotes).

    Code:
    int four = 4;
    is an integer variable named "four" containing the number 4.

    Class - An user-defined variable type that contains other types within it, along with methods and properties.

    Method - A set of instructions that can be easily re-executed by calling on its name. It must have a return "type" (same list as variables, though can be class names, too). You may use the "void" return type to not be required to return a result from a method.

    Code:
    int AddNumbers(int num1, int num2)
    {     
         int total = 0;
         
         total = num1 + num2;
    
         return total;
    }
    
    This would let you call the method AddNumbers, and tell it what two numbers you wanted to add together. It would return the answer:

    Code:
    int total = 0;
    total = AddNumbers(1,2);
    PrintToScreen(total);
    
    would print out the number "3" on the screen.

    Square Brackets ([]) - These are used for things called arrays. Basically, it is a variable that contains a bunch of values instead of a single one. The square brackets let you access the different values contained within.

    Curly Brace ({}) - These are used to denote code blocks within the code, so C# knows when you are done doing something associated with the code block.

    Ok, so on to the actual code in the shot:

    Code:
    string actionNameBase = "OnOff";
    string actionName = "OnOff_On";
    
    This is assigning two "string" type variables, actionNameBase and actionName.

    actionNameBase is "OnOff"

    and

    actionName = "OnOff_On"

    Code:
    Random rnd = new Random();
    
    Random is a pre-defined class in C# for handling "random" numbers. So, the line is saying:

    New variable named "rnd". It should be a class of type "Random". It should be a new initialization of the "Random" class (not a previously used "random" class variable).

    Code:
    List<IMyTerminalBlock> blocks = new List<IMyTerminalBlock>[];
    Make a new "List" class of the class type "IMyTerminalBlock" named "blocks". Make this a new initialization of the list class. This is an array. (Hence the [] at the end.)

    Code:
    void Main()
    Every C# program has a Main() method. It MUST have a capital M, and it MUST be a "void" type.

    Code:
    blocks.Clear()
    
    This is a method defined by the "List" class that "clears" (empties) the entire list out.

    Code:
    GridTerminalSystem.GetBlocksOfType<IMyLightingBlock>(blocks);
    
    This is where we go into foggy territory-- this isn't a "C#" standard function, but using Common Sense® we can figure out what it does. So let's break it down:

    GridTerminalSystem - Accesses the grid the terminal is located on?
    GetBlocksOfType<IMyLightingBlock>(blocks) - look for lights on the grid, then add them to the block list you defined.

    Code:
    bool allOn = true;
    bool allOff = false;
    

    Define booleans named allOn and allOff. Set their default states (allOn is true, allOff is false).

    Code:
    for(int i = 0; i < blocks.Count; i++)
    
    This is a loop. It can look intimidating, but it is easy to break down into parts to say what it is doing:

    you have a variable named "i" that is set to 0.

    While "i" is less than the amount of blocks listed in your list (aka, how many lights you have), increment i by one number (i++ is the same as i = i+1) after the loop executes. Where the "++" lands tells C# when to increment the variable. Because it is i++, it is done AFTER each loop (it comes AFTER the variable? Get it?)

    While the loop is running:
    Code:
    allOff |= (blocks[i] as IMyFunctionalBlock).Enabled;
    allOn &= (blocks[i] as IMyFunctionalBlock).Enabled;
    Ok, this looks really intimidating, but again, let's break it down:

    allOff variable has the |= assignment operator used. This can be a bit confusing, so I'll rewrite the code to do the same thing differently:

    Code:
    allOff = allOff | (blocks[i] as IMyFunctionalBlock).Enabled;
    
    OK, so that doesn't seem to look better... but it is more easily explained. The "|" operator means "or" in C#. That means, what it is actually doing is:

    is allOff true and the current block on? allOff is true.
    is allOff false and the current block on? allOff is true.
    is allOff true and the current block off? allOff is true.
    is allOff false and the current block off? allOff is false.

    The next point to note is the presence of the "as" keyword. Basically, it is telling the code to treat the "block" as the class IMyFunctionalBlock. This gives that block the same methods and properties (such as the Enabled property we see here.)

    Let's do the same with the next line. & is the logical "AND" operator, so:

    Code:
    allOn = allOn & (blocks[i] as IMyFunctionalBlock).Enabled;
    
    is allOn true and the current block on? allOn is true.
    is allOn false and the current block on? allOn is false.
    is allOn true and the current block off? allOn is false.
    is allOn false and the current block false? allOn is false.

    Code:
    if(!allOff)
    
    if is a logical evaluator. If the statement within is true, then it executes its code block. If it is false, it does not execute its code block. The exclamation point (!) operator means "not" in C#. so this code is:

    IF NOT ALL OFF.

    so, allOff is false, then the evaluation is true. Confused? Basically, think of it this way.

    1+1 = 2.
    I say 1+1 = 3.
    Am I wrong?

    If(I am wrong)
    Execute code block.

    So:

    if(NOT TRUE (1+1 = 3))
    Do stuff.

    Anyhow:
    Code:
    actionName = actionNameBase+"_On";
    
    so, IF allOff is false, actionName is now: "OnOff_On". How did I get that? If you "add" a string, it appends it to the end. The variable "actionNameBase" is "OnOff" and it says to add _On to the end of it. So:

    actionName is assigned the value "OnOff" (actionNameBase) with _On appended to it.

    Code:
    if(allOn)
    
    is allOn true? Then execute:

    Code:
    actionName = actionNameBase + "_Off";
    
    Same as before, only we append "Off" to the end. So actionName is now "OnOff_Off"

    Code:
    for(int i = 0; i <blocks.Count; ++i)
    
    So, last bit left. We broke this down earlier, so let's do it again:

    variable i is set to 0.
    while i is less than the amount of blocks in our list,
    increment i before the loop executes. (++ comes first, so do it first!)

    Ok, so that's all the code we saw, and hopefully it is a little less intimidating for those who look at it and just see a wall of text.

    The conclusion I have come to as to what this code example does is that it will randomly turn the lights on and off on a ship.


    Edit: So, here's a rundown of WHAT the code does.
     
    Last edited by a moderator: Dec 30, 2014
  2. Skeloton

    Skeloton Master Engineer

    Messages:
    4,069
    Congrats, you well and truly confused the ***** outta me.

    On the upside I know what bool(Boolean) means now.
     
    • Funny Funny x 1
  3. Textor

    Textor Junior Engineer

    Messages:
    775
    Is there any particular part that confused you, or perhaps suggestions of what needs more clarity?
     
  4. Skeloton

    Skeloton Master Engineer

    Messages:
    4,069
    I have to say, all of that confused me except the explanation of Boolean in programming speak.

    I don't know if you can add anymore clarity. Maybe KSH will have a full example script and you can make a guide that tears it apart and explains it piece by piece. In an organised fashion, might just be me but this forum doesn't work well with organisation of this kind.

    Or its just me being progammically challenged.
     
  5. Textor

    Textor Junior Engineer

    Messages:
    775
    In that case, I'd suggest taking it slow and just absorbing things a little at a time. Computers execute code one line at a time, so focus on one line at a time. If you have any questions, feel free to ask and I can explain in different terms or more detail.
     
  6. a2457

    a2457 Senior Engineer

    Messages:
    1,366
    Your efforth is excellent.
    but the code You try to explain is not begginer level.

    sadly the screenshot does not absolutely hint out enough to show a few pretty simple scripts that may be perfectly used once it gets implented in SE.

    maybe a simple turn a light on kindof script would do.
    thisone , in the screenshot is more of a showcase of some advanced functions.


    but never forget, the thing is like a pyramid. stuff is built on other stuff.
    once you can grasp a simple code, an advanced one will be easy too.
    can't just jump in the middle.
     
    • Agree Agree x 1
  7. Textor

    Textor Junior Engineer

    Messages:
    775
    Thanks, it's good to hear.

    Agreed. The logical assignment operators (|=, &=) are things I actually don't encounter often in the code I deal with, so it took me a minute to even remember how they work.

    Based on the screenshot, I actually believe this is their example script from the weekly update video. Hopefully they'll have multiple scripts. If not, I'll probably make some tutorials ramping up the difficultly and complexity so that beginners can start playing with the code blocks.

    I agree-- this example is definitely not the thing I'd use to teach an introduction to programming blocks. However, I'm hoping that my explanation will at least make the code a little less mystical for some people.
     
  8. a2457

    a2457 Senior Engineer

    Messages:
    1,366
    You forgot the important stuff.
    what the code does.
    read all light in a loop on the grid, and yadada.

    i'd bet most peeps would be intrested in what it does first.
    like the loop iterating over the lights.
     
  9. Textor

    Textor Junior Engineer

    Messages:
    775
    Ah, yeah, I see how I was a bit ambiguous there. I'll add a summary of "what it does" at the bottom.
     
  10. FallingWhale

    FallingWhale Apprentice Engineer

    Messages:
    202
    Good, someone else that knows 46 isn't the line limit.
     
  11. Textor

    Textor Junior Engineer

    Messages:
    775
    Seriously, could you imagine everyone writing their code on a single line just to bypass an arbitrary limit like that? Plus, 46 isn't even a proper limit number! At least do 42 because of its meaning, otherwise stick to powers of two stuff... 64 or 32 would at least make sense as a limit (though would still be stupidly low.)
     
    Last edited by a moderator: Dec 31, 2014
  12. TheQuixote

    TheQuixote Apprentice Engineer

    Messages:
    119
    With that example I don't see any indication that you can define a class ( or method other than Main )

    Do you think that will be the case?

    I'm guessing this executes in the context of a particular ship with access limited to just the same block settings that you would see in a timer block?
     
  13. wajsters

    wajsters Trainee Engineer

    Messages:
    7
    Thanks for the basic explanation, I know my way around programming slightly but this is a great reference to keep me on track :)
     
  14. Textor

    Textor Junior Engineer

    Messages:
    775
    I can't imagine they'd restrict the ability for you to make methods. Methods are extremely basic and very important. Classes... maybe. Don't know til we see more.

    I'd be interested to see if they implement the override keyword.

    I also think they need to implement a monospaced font, though I don't want to stick that in the suggestion box until they actually release the block. Jumping the gun on a picture seems stupid.
     
  15. OldGamer67

    OldGamer67 Apprentice Engineer

    Messages:
    181
    Code:
    10 LET I = 0
    20 IF I <> 0 THEN GOTO 50
    30 PRINT "I'M LOST."
    40 GOTO 20
    50 PRINT "I UNDERSTAND!"
    60 END
    
    Props for attempting to explain. Once upon a time I liked to program. Alas, I think those days are behind me. Now I just want to place blocks and kill things.
     
  16. Textor

    Textor Junior Engineer

    Messages:
    775
    Hm, if we had a nonzero assignment to "I" we could actually reach understanding...
     
  17. Thedevistator

    Thedevistator Senior Engineer

    Messages:
    1,942
    This is great I have only read half of it even though it is a bit difficult I understand it a bit good job.
     
  18. galacticon

    galacticon Apprentice Engineer

    Messages:
    440
    Excellent explanation! This is a very exciting development. I do hope Keen will offer some tutorials or documentation on what this new feature can do. Kudos to them. :)

    everyone should check out CodeCademy for basic turotiruals. They don't have C#, but they cover all the fundamentals will translate and at least get you started in a step-by-step, incremental learning program. And it's free!
     
  19. Tarenty

    Tarenty Trainee Engineer

    Messages:
    12
    I think C#, while it may have been chosen due to the limitations of the engine, wasn't the best choice for in game coding; the C family is a little complex for beginners. That being said, thanks a lot (in advance) for making some tutorials. I'll probably use them myself even though I'm good with C++ so I can get the differences down.
     
  20. Forgemasterhd

    Forgemasterhd Junior Engineer

    Messages:
    612
    So, I'm going to assume you are well-versed in the realm of C# based o this very, very intuitive look at the code behind the...uh...code. *Cough*

    I'd like to ask you a question, I'm studying python for our schools Computer Science and Engineering course, (By studying I mean being forced to use). How similar in coding is Python to C#? I will be taking C++ this upcoming semester, but I feel I won't be able to use those skills for a long while. Should I get a leap on coding in the C family now, or will my basic understanding of Python allow me to work on small code from day 1?
     
  21. AceNepets

    AceNepets Apprentice Engineer

    Messages:
    121
    Here is my take on the screenshot, Pythonic-style:

    Code:
    actionNameBase = "OnOff"
    actionName = "OnOff_On"
    import random
    blocks = []
    def Main:
      del blocks[:]
      blocks = GridTerminalSystem.GetBlocksOfType(IMyLightingBlock) # Questionable line
      
      allOn = True
      allOff = False
      for block in range(len(blocks)):
        allOff = offOff or blocks[i].Enabled
        allOn = allOn and blocks[i].Enabled
      
      if(not allOff):
        actionName = actionNameBase+"_On"
      if(allOn):
        actionName = actionNameBase+"_Off"
        
      for block in range(len(blocks)):
    
    You see there are lots of similarities, and a few differences. Once you learn how to code, it will be familiar. Sort of like learning to play computer games, right? All computer games have familiar constructs, and cross over. Age of Empires and other Real-Time strategy games teach resource management; Minecraft, obvious; any first-person-shooter with physics, etc. Lots of kinds of programing languages, but many are similar.

    Hope this helps.
     
    Last edited by a moderator: Dec 31, 2014
  22. Textor

    Textor Junior Engineer

    Messages:
    775
    I suppose the best way to compare python and C# is to show you their "Hello, World" programs:

    C#:

    Code:
    using System;
    
    public class Hello
    {
         public static void Main()
         {
              Console.WriteLine("Hello, World!");
         }
    }
    
    Python:

    Code:
    print "Hello, World!"
    
    Just for fun, here's C:

    Code:
    #include <stdio.h>
    
    int main()
    {
         printf("Hello, World!");
    
         return 0;
    }
    
    and C++:

    Code:
    #include <iostream>
    
    int main()
    {
         std::cout << "Hello, World!" << std::endl;
         return 0;
    }
    
    You'll notice that C/C++/C# seem pretty similar-- this is intentional. since C++ is an extension of C that made it an object-oriented programming language. C# is a full object-oriented programming language.

    Honestly, I've programmed in C, C++, and C#, and I personally prefer C# over the other two. I don't have much experience in python, but it does seem easy to use, though using whitespace to
     
  23. a2457

    a2457 Senior Engineer

    Messages:
    1,366
    :) i favour php for some reason.
    and dreadfully.. realy a bad practice i do compile php with BAMBALAM to an executable file.
    supposedly it was made to do web oriented stuff but regardless of that i..sortha do pretty much anything with it.
    i dislike OOP for a number of reasons.
    while php can be used in OOP style.. i prefer to not do that.

    this..makes me a hell of a bad programmer :(


    anyways i'm perfectly sure the ingame scripting language (i prefer to not call it c#. no evidence it has anything to do with it other than syntax compatibility)
    will be quite limited. I'm sure creating classes will be out of reach. not sure even driven stuff will be available. like if a rotor is turning, do something when it reaches a certain angle.
     
  24. TheQuixote

    TheQuixote Apprentice Engineer

    Messages:
    119
    I imagine override might be an issue. I would assume these will be run as interpreted scripts while the rest of the program has been compiled at some point. ( IIRC managed .net compiles to byte code which then just in time compiles to the platform it's on ) Probably technically possible to allow it, but my guess is that they would need to create proxies for anything they wanted to allow us to override.

    Another thing I'm curious about is working with antennas and control blocks. GridTerminalSystem.GetBlocksOfType would imply that the script is executing in the context of a single ship. If through antennas you could have access to anything on the antenna network that could be pretty powerful. Especially if the position information of blocks and ships is exposed. Thinking fleet controls, auto docking programs, etc. If that were the case than being able to define classes becomes little more of an issue, if for no other reason than to have convenient way to make mixed type data structures.
     
  25. Krutchen

    Krutchen Apprentice Engineer

    Messages:
    159
    I was just thinking about fleet controls, Quixote. If we have access to customizable hud elements like what was talked about on Marek's dev blog, Hopefully we can go pretty far indepth. I for one would LOVE to control a fleet of automated corvettes and such through a homeworld-esque command display. My hype is real.


    For the love of god let the next update be scripting, I seriously cannot wait. I'll straight up make entire packs of Script-AI controlled hostiles on day one, a velocity tracking Navball HUD on day two, and fleet AI & a way to give orders on day three.
     
    Last edited by a moderator: Dec 31, 2014
  26. Forgemasterhd

    Forgemasterhd Junior Engineer

    Messages:
    612
    I can still see what is going on, so while I don't think it will be immensely difficult to adapt, it may take some time.

    Thanks!
     
  27. semple

    semple Trainee Engineer

    Messages:
    83
    Good thing I develop with C# and .Net for a living :v
     
  28. Textor

    Textor Junior Engineer

    Messages:
    775
    I don't see the problem, necessarily. Since this is C#, each ship is an object. You can just pass the ship in as a parameter to your method, and it will do what you want for remote ships.

    I'd assume that they'd have a prerequisite that there is some sort of programming block available on the other ship, and there is ownership or at least a "allow remote code execution" checkbox, otherwise I could imagine "virus" ships causing insane actions across entire fleets because they reached antenna range.
     
  29. Thunderbolt

    Thunderbolt Trainee Engineer

    Messages:
    62
    For someone that only knows some Bascom (Pretty much Basic adapted for microcontrollers) this was pretty confusing, though not impossible to understand if you give it enough time, I'm sure they'll release much simpler code examples alongside the update for everyone to modify and figure them out for themselves.
     
    Last edited by a moderator: Dec 31, 2014
  30. TheQuixote

    TheQuixote Apprentice Engineer

    Messages:
    119
    Not that I think about it more, there's a few other questions I have.

    How often and what triggers these scripts?
    Persistence of the script. ( Does it remember the value of myVar from call to call )
    Will there be a way to register and respond to events?

    It may be that we're really inflating expectations and this will just be a very robust macro scripting environment.
     
Thread Status:
This last post in this thread was made more than 31 days old.