Jump to content

Scripting for beginners.


Recommended Posts

So, this is just a topic to share your tips/tricks for scripting. If you want to post code you've edited/made, go ahead. If it is not your original code (if you edited a script such as basicrp), be sure to post both (A) what the original code is, (B) who the original author is.  I myself have been doing some scripting, mind you, I don't have a lot of knowledge, so I could definately use some improvement
Link to comment
Share on other sites

I'm currently taking a university program right now learning computer science materials. Currently learning Java, C++, PHP and Python.


Anyways I can share a few tips for you:

-Tip #1: Do "lazy coding": What I mean by this is to write helper functions in case if multiple functions uses the same lines of code over and over again. This way instead of typing the same 25 lines of code again, you can put those 25 mines of code in one function and just write out that one line in other functions (I'll show you an example later)

-Tip #2: Be careful of using global variables: It's best to use local variables in functions rather than using global variables for organization purposes.

-Tip #3: Watch for efficiency: There are so many ways to code a function to do a specific task but code it in a way so the function can efficiently do the task faster. For e.g. insertion sort uses two loops to sort elements in order in a list so the efficiency is o(n^2). Mergesort uses recursion and goes through the list once to sort the elements so the average efficiency is O(log n), faster than insertion sort. Bogosort uses a random generator to randomly generate elements until the list is sorted so that efficiency is forever!

-Tip #4: When doing Object-Orientated Programming, plan out the object classes first before coding: My professors always says: Planning and debugging takes the most amount of time. Coding is the least. If your doing OOP programming, plan ahead first. Determining all the properties of the class and methods first before coding. Not only this makes it easier to code but it also makes team development easier without having to reference other teammates code all the time.

-Tip #5: Debug, debug, debug!

-Tip #6: Comment your code: You might be able to understand your own code but there are other people who can't read your code without tracing the entire function. Adding comments can help other programmers read the code.

-Tip #7: Use variable names that's easy to understand: Variable names like 'x', 'y', 'z' arent really helpful. Like comments, people cant understand without tracing. Use more descriptive variables such as 'list_of_int' or 'counter', etc.


If I have any more tips I can update this stuff here. I will show u some of my past coding later.

Link to comment
Share on other sites

here is just a very simple script I wrote. It basically allows you to list all a resources commands

 

addCommandHandler("commands", 
  function( player, _, resourceName)
     local theResource = (resourceName and getResourceFromName(resourceName)) or resource 
     outputChatBox( "* Commands from "..getResourceName(theResource).." resource", player, 0, 255, 0 )
	
     local commands = getCommandHandlers( theResource )
     for _, command in pairs( commands ) do
        outputChatBox( "/"..command, player, 255, 255, 255 )
     end
  end
)

Link to comment
Share on other sites

Would be easier if comments and docstrings were added so I can know what the function does and what the function return type is.


I could study lua scripting when I have time. Just that uni is bombarding me with other com sci stuff right now :P

Anyways here is a big piece of code from Java when i was programming the scoreboard for a space shooter game with Greenfoot IDE (yea I should have added comments but it was two years ago when I started to program :P)

 

import greenfoot.*;
import java.util.*;
import java.awt.*;
/**
* Write a description of class Scoreboard here.
* 
* @author (your name) 
* @version (a version number or a date)
*/
public class Scoreboard extends Displays
{
    private boolean run;
    int [] topTen = new int [10];

    In in = new In ("ListOfScores.in");
    /**
     * Act - do whatever the Scoreboard wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        if (!run) {
            run = true;
            listOfScores (getScore());
        }
    }    

    public int getScore () {
        Gameplay game = (Gameplay) getWorld();
        SpaceShip ship = game.getSpaceShip();
        Score score = game.getScore();
        int currentScore = 0;
        if (ship.getIsDead()) {
            currentScore = score.getScore();
        }
        return currentScore;
    }

    public void listOfScores (int addScore) {
        ArrayList <Integer> list = new ArrayList <Integer> ();
        if (in.hasNextLine ()) {
            while (in.hasNextLine()) {
                int num = Integer.valueOf (in.readLine());
                list.add (num);
            }
        }
        else { 
            for (int i = 0; i < 10; i++) {
                list.add (0);
            }
        }
        list.add (addScore);

        int [] order = new int [list.size()];
        for (int i = 0; i < order.length; i++) {
            order [i] = list.get (i).intValue();
        }
        if (!isSorted(order)) {
            quicksort (order);
        }

        for (int i = 0; i < 10; i++) {
            topTen[i] = order [i];
        }

        Out out = new Out ("ListOfScores.in");
        for (int i = 0; i < topTen.length; i++) {
            out.println (topTen[i]);
        }
        out.close();

        GreenfootImage image = new GreenfootImage (400, 600);
        image.setColor (Color.WHITE);
        image.setFont (new Font ("Arial", Font.PLAIN, 20));
        image.drawString ("Top 10 High Scores", 400/2, 20);
        boolean red = true;
        for (int i = 0; i < 10; i++) {
            if (topTen [i] != getScore()) {
                image.setColor (Color.WHITE);
            }
            else if (topTen [i] == getScore() && red){
                image.setColor (Color.RED);
                red = false;
            }
            else if (topTen [i] == getScore() && !red){
                image.setColor (Color.WHITE);
            }

            image.drawString (i + 1 + ". " + topTen[i], 400/2, (i + 2) * 30);
        }

        setImage (image);
    }

    private void exch (int [] a, int i, int j) {
        int store = a[i];
        a[i] = a[j];
        a[j] = store;
    }

    public int partition(int[] a, int lo, int hi) {
        int i = lo; 
        int j = hi + 1;
        while (true) {
            while (a[++i] > a[lo]) {  // Find item on left to swap  
                if (i == hi) {
                    break; 
                }
            }
            while (a[--j] < a[lo]) {
                if (j == lo) {
                    break;
                }
            }
            if (i >= j) {
                break;  // Check if pointers cross 
            }
            exch(a, i, j);  // Swap
        } 
        exch(a, lo, j);  // Swap partitioning element  
        return j;  // Return index of item now know to be in place
    }

    private void quicksort(int[] a, int lo, int hi) {
        if (hi <= lo) return;
        int j = partition(a, lo, hi); 
        quicksort(a, lo, j-1); 
        quicksort(a, j+1, hi); 

    }

    public void quicksort(int[] a) {
        StdRandom.shuffle(a); 
        quicksort(a, 0, a.length - 1); 
    }
    
    public boolean isSorted (int [] a) {
        boolean sorted = false;
        for (int i = 0; i < a.length-1; i++) {
            if (a[i] > a[i+1]) {
                sorted = true;
            }
            else {
                sorted = false;
            }
        }
        return sorted;
    }

}

Link to comment
Share on other sites

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
×
×
  • Create New...