Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Saturday, November 13, 2010

Programming: COW Interpreter - A java interface for Bovine Programmers...

In one of my lectures at Swansea University the topic of Esoteric Languages came up, mainly on this topic we discussed the languages of BrainF*** and COW.

BrainF*** is a programming language that only contains the characters:
< > + - , . [ ]

COW only contains 12 commands, each written as MOO's:
moo
mOo
moO
mOO
Moo
MOo
MoO
MOO
OOO
MMM
OOM
oom
*These are of course all case sensitive*

Upon further research into these languages I came across this site: http://www.bigzaphod.org/cow/
And with it, a worrying thing arose to me. There were no stable compilers or interpreters for this great language.

Bare in mind ("rawr"), that at this point I had yet to even write a program in COW, but none the less I was enthused by how such a simple architecture could still have a modern day application, given that COW, and BrainF*** alike are based off of the old Tape Driven computer Systems, where a Command Tape drives the position and data stored in a Data Tape.


[ A 26 line COW program that counts indefinitely in Fibonacci Numbers, or until you reach ]
[ a numerical overflow. ]


[ A 1337 line COW program that runs through 99 Bottles of Beer on the wall. ]

Monday, January 11, 2010

Programming: Java: Tutorials: Constructors, Sub-Routines, and Functions

 Certainly, I'd be glad to clarify for you.

When you have a "Sub-Routine" (pocket of code which just runs [fire and forget]) you aren't receiving anything back. You are just saying "go off and do this so I don't have to write out that code again".

A Function is like a Sub-Routine in the sense that it is a section of code that you can keep calling over and over again, accept that it also returns a value.

This can be seen in the code like so.

A sub-routine would be... (For a theoretical class called dog)

public void Bark() {
  System.out.println("Woof! Woof!!!");
}

Notice how seeing as we don't want to retrieve a value from the Bark() method we write Void in its header.

Now, lets say we wanted a Function to tell us how old the dog was... (Note "DogAge" is an integer variable)

public int getAge() {
  return DogAge;
}

Notice how because we want to retrieve an integer we place int instead of Void in the header. This makes the Function return an integer, which we give to it using the "return" command.

The difference is that if we wanted to make the dog bark we would literally type...

myDog.Bark();

and be done with it. But with a function we have to store the value it returns. Seeing as our Function in this case returns an integer, we store it like so...

int Age =  myDog.getAge();

Now we have created a new integer variable called age and given it a value from our Dog class.

But don't be fooled, a Function doesn't just have to return a pre-existing variable. Before we write...

return VAR;

at the end of the function, we can put any calculations we want.

This has been a very drawn out explanation. But don't worry it will become clear in time.

All you need to know about constructors and why I commented on them not "even" having Void in their header was that they are unique, and therefore easy to spot and manipulate.

//Beginning of the Dog Class
public class Dog() {

  //The variables to store information about the dog
  int DogAge;
  String Name;


  //Default Constructor
  public Dog() {
    DogAge = 5;
    Name = "Saxon";
  }


  //2nd Con. for if we want to specify an Age
  public Dog(int Age) {
     DogAge = Age;
     Name = "Saxon";
   }


  //3rd Con. for if we want to specify a Name
  public Dog(String name) {
     DogAge = 5;
     Name = name;
   }

  //4th Con. for if we want to specify a Name and Age
  public Dog(int Age, String name) {
     DogAge = Age;
     Name = name;
   }


  //A Sub-Routine to make the dog Bark
  public void Bark() {
    System.out.println("Woof! Woof!!!");
  }


  //A Function to retrieve the dogs Age
  public int getAge() {
    return DogAge;
  }


}

This sample class shows the fundamental differences between Constructors, Sub-Routines, and Functions.

I hope this helps.

Programming: Java: Tutorials: A Guide to Class Architecture

Java is a type of language known as OO or Object-Oriented. OO Programming differs from other types because it allows the programmer to write less code, which in turn is more efficient code.

As we know, in java a class is written in a .java file. Inside this file we denote the beginning of our class with a line similar to the one bellow.
public class Cat {
This line would create a public class named Cat. That would mean a class that any other class can access. We'll get more into that later.

Inside the class tags, if this is our main class, we have the main() method. This is the method which runs when the program starts.

public void main(String[] args) {
So, what have we done so far? We have made a .java file called Cat.java, which contains a public class name called Cat. Also we have a main method within our class.

So your thinking "So what?", that this is nothing new. Well, that may be but the class we have created has a major flaw. It's static!

Static vs. Non-Static

A Static class means class which just IS. I can't be recreated. It just runs. Values can be applied to it, and drawn from it, but you cannot make multiple instances of it.

What we need is a way to make each version of our class different. What we need is a Constructor!

Constructors

A constructor allows us to create multiple versions of our class in memory, each with different values.

The constructor is a sub-routine which is public, has no return statement (not even void), and has the same name call as the name of the class. In our case a constructor would look like this.

public Cat() {
This would be a "Default Constructor". The reason it gets this title is because it accepts no inputs from the class creating it. All it does is create a new instance of the Cat class using what ever values are already stored within it by default.

Also, like all other sub-routines we can have multiple versions of it, each with different parameters. Like so.

//Default Con.
public Cat() {
  s = 10;
  a = 5;
}

//Secondary Con.
public Cat(int Size) {
  s = size;
  a = 5;
}

//Thir-dary Con.
public Cat(String name) {
  s = 10;
  n = name;
}

//Fourth-dary Con.
public Cat(int Size, String name) {
  s = size;
  n = name;
}

See, by creating a constructor for each possible contingency we allow the Cat class to work under any circumstance.

Now from another class we could create multiple instances of the Cat Class, each with different values like so.

Cat c1 = new Cat();
Cat c2 = new Cat(5,"Dilbert");
Cat c3 = new Cat(7);
Cat c4 = new Cat("Dill");

or we could create an Array of Cat like so.

Cat[] cats = new Cat[4];
for (int i = 0; i < cats.size; i++) {
  cats[i] = new Cat((int)(i,"Cat: #" + i);
}

Sadly...

Sadly the powers that be at VHS aren't exactly "fond" of me posting how to's on my blog here so that's all I'm going to go over. This is the basics of the Class system, there isn't too much else to it accept for practice. Good luck! 

Saturday, December 5, 2009

Programming: Java: Game: Space Shooter


[ Space Shooter 2D ]

A month or two ago I started developing a Java based video game as a way to test myself. The game in its early days looked far different from how it does now, and in between then and now has gone through many radical design changes, (At one point it was a Tank Game).

However, finally I settled on the idea of a space shooter! You play as the red ship, and have to fight off on coming waves of enemy space cruisers and space tanks.

Throughout development I have given BETA versions of the game to my friends to test it and try to break the code so I can fix potential bugs. One major bug, or perhaps not a bug but a loop hole, was that if you held the fire button down after a second or two of nothing happening, a continuous stream of missiles would fire from your ship, allowing them to blow up everything in one fell swoop.

I fixed this by making it so you could only fire one rocket per button press, and further on in development I edited this so that your gun would over heat if you fired too many missiles straight after one another, (as displayed by the Weapon Temperature bar on the HUD).

A public BETA of the game can be downloaded from here:

Programming: Java: Video Tracking: Color Recognition



[ Effect of Sobel Edge Detection Shown in Yellow ]
[ and Color Detection Shown in Blue ]
Intro:
I first experimented with Video Tracking about a year ago, at the time I was programming primarily in VB.net 2008. A powerful language yes, but when it comes to graphics and "time expensive" processes, its bad side begins to shine through.

About a week ago I decided to reopen this project and give it another go, this time in Java. My reasoning? Java runs a lot faster and is much better at handling color arrays, the basis for image recognition.

Summary of technique:
There are many methods for scanning video feeds, none of them perfect. They all have there downfalls. The key of a good tracking program is to use multiple of these methods together so that one methods downfall can be picked up by another ones strong point.

After much research, the types of image recognition I chose to develop upon were:
  • Sobel Edge Detection
  • Color Recognition
  • Motion Detection



[ Effect of Color Detection Shown in Blue ]

Color Detection Algorithm:
Color Based Tracking is a method by which an image or video feed is scanned for a given color. Being the most common method of object recognition it has been interpreted in many different ways. After researching what the method actually needs to do I decided on a system by which the user clicks on the the part of the image where the color they want to track is, then the program uses this color reference in its scan.

To do this I had to write multiple systems into the program. First, a system by which to get the color when the user clicks on the image feed. Second, a system to display this color choice to the user along with the threshold for the scan. And thirdly, the SCAN!

The scan is what I'll focus on in this article. It consists of a system by which we loop through each X and Y pixel of the image and compare the GrayScale (Black and White) version of the image to the GrayScale version of the given color. We do this because it is faster than checking the Red, Green, and Blue Channels of every pixel in the image.

Once we have decided that a pixel is likely to contain the search color, we flag it by coloring it with a semi transparent blue pixel. Then we continue to scan to check if the Red Channels of the pixel and the Search Color are with the threshold of each other. If that checks out then we check the Green Channels, and finally, if that checks out we try the Blue Channels.

Once we have confirmed that the given pixel is the correct color we mark it with a solid blue mark.

Color Example Code: Java

public void Update(BufferedImage buf) {
        img = buf; //Store the image
        int w = img.getWidth(); //Image Width
        int h = img.getHeight(); //Image Height
       
        FlagMap= new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB); //Create Overlay
       
        for (int x = 0; x < img.getWidth(); x+=scan) { //Scan through each X of the image
            for (int y = 0; y < img.getHeight(); y+=scan) { //For each X scan through each Y of the image
               
                Color C = new Color(img.getRGB(x,y)); //Get the pixel color at the current position
                int GS = ((C.getRed() + C.getGreen() + C.getBlue()) /3); //Generate the GrayScale                                          
                //Color Detection
                if ((AvgT - ct) < GS && (AvgT + ct) > GS) { //Is the GrayScale is within threshold?
                    FlagMap.setRGB(x,y,FlagColor.getRGB()); //If so mark with a semi transparent blue mark
                  
                    //Is each color channel within threshold?
                    if ((TColor.getRed() - ct) < C.getRed() && (TColor.getRed() + ct) > C.getRed()) {
                        if ((TColor.getGreen() - ct) < C.getGreen() && (TColor.getGreen() + ct) > C.getGreen()) {
                            if ((TColor.getBlue() - ct) < C.getBlue() && (TColor.getBlue() + ct) > C.getBlue()) {
                                FlagMap.setRGB(x,y,DetectColor.getRGB()); //If R,G, and B Channels are with threshold mark with a solid blue mark
                            }
                        }
                    }
                }
                           
            }
        }
}

Notes on example code:
  • The variable "scan" is an integer and refers to the accuracy of the scan. eg. scan = 1 would mean that every pixel of the image would be scanned. scan = 2 would mean every other pixel would be scanned. scan = 5 would mean every fifth pixel... ect, ect...
  • The variable "ct" is an integer and refers to the Threshold for pixel comparison. This is set in the program via the Trackbar in the Top right of the Screen which allows for differences of 0 to 40.
  • The variable "TColor" is a color and refers to the color the user wants the algorithm to scan.
  • The variable "AvgT" is an integer and refers to the average of variable "TColor"'s R, G, and B Channels.
  • My program has a separate class for displaying the image to the window, it draws the actual image first then draws what are called "overlays" on top of it. In this case the overlay is the image "FlagMap" which is transparent everywhere except where an edge has been detected.
  • For best results, downsize your image to around 200x200 pixels before passing it to this algorithm and set "scan" to 1. If you want to scan a larger image you will need to set "scan" to a higher value to maintain performance.
I hope this helps anyone who is trying to do something in this field, it's a tricky one. Please subscribe, more like this is on the way!

Programming: Java: Video Tracking: Sobel Algorithm




[ Effect of Sobel Edge Detection Shown in Yellow ]
[ and Color Detection Shown in Blue ]
Intro:
I first experimented with Video Tracking about a year ago, at the time I was programming primarily in VB.net 2008. A powerful language yes, but when it comes to graphics and "time expensive" processes, its bad side begins to shine through.

About a week ago I decided to reopen this project and give it another go, this time in Java. My reasoning? Java runs a lot faster and is much better at handling color arrays, the basis for image recognition.

Summary of technique:
There are many methods for scanning video feeds, none of them perfect. They all have there downfalls. The key of a good tracking program is to use multiple of these methods together so that one methods downfall can be picked up by another ones strong point.

After much research, the types of image recognition I chose to develop upon were:
  • Sobel Edge Detection
  • Color Recognition
  • Motion Detection 

 [ Effect of Sobel Edge Detection Shown in Yellow ]

The Sobel Algorithm:
Sobel Image Analysis is a way of scanning an image and trying to detect where the edges of objects are. This can be especially important if you are scanning high resolution video feeds by first using the Sobel Algorithm to mark points of interest in the image, negating the need to scan the entire image for color or motion.

The algorithm works by looking at each pixel of the image and comparing it to the eight pixels surrounding it. If a pixel surrounding is within a given color threshold then the point is flagged (in my program edges are flagged by a yellow point).

Sobel Example Code: Java

public void Update(BufferedImage buf) {
        img = buf; //Store the image
        int w = img.getWidth(); //Image Width
        int h = img.getHeight(); //Image Height
       
        EdgeMap= new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB); //Create Overlay
       
        for (int x = 0; x < img.getWidth(); x+=scan) { //Scan through each X of the image
            for (int y = 0; y < img.getHeight(); y+=scan) { //For each X scan through each Y of the image
               
                Color C = new Color(img.getRGB(x,y)); //Get the pixel color at the current position
                int GS = ((C.getRed() + C.getGreen() + C.getBlue()) /3); //Generate the GrayScale                                          
                //Sobel Algoritham
                boolean W = false; //Switch for whether the point is an edge
                if (x > scan && x < img.getWidth()-scan) { //Check we aren't on an X edge pixel
                    if (y > scan && y < img.getHeight()-scan) { //Check we aren't on an Y edge pixel
               
                        for (int u = -scan; u <= scan; u+=scan) { //Scan the surrounding X pixels
                            for (int v = -scan; v <= scan; v+=scan) { //For each X scan the surrounding Y pixels
                           
                                if (u != 0 && v != 0) { // Make sure we aren't checking the pixel against itself
                                    Color B = new Color(img.getRGB(x + u,y + v)); //Get the current boarding color
                                    int BS = ((B.getRed() + B.getGreen() + B.getBlue()) /3); //Generate the GrayScale
                                    if (((GS-BS) < t && (GS-BS) > -t) == false) { //Are they different enough?
                                        W = true; //If so set the switch to TRUE
                                    }
                                }
                            }
                        }
               
                    }
                }
               
                if (W == true) { //Did the pixel had at least one boarding pixel that was different?
                    EdgeMap.setRGB(x,y,EdgeColor.getRGB()); //If so then draw a yellow pixel on the overlay
                }
                //End Sobel
                           
            }
        }
}

Notes on example code:
  • The variable "scan" is an integer and refers to the accuracy of the scan. eg. scan = 1 would mean that every pixel of the image would be scanned. scan = 2 would mean every other pixel would be scanned. scan = 5 would mean every fifth pixel... ect, ect...
  • The variable "t" is an integer and refers to the Threshold for pixel comparison. This is set in the program via the Trackbar in the Top right of the Screen which allows for differences of 0 to 40.
  • My program has a separate class for displaying the image to the window, it draws the actual image first then draws what are called "overlays" on top of it. In this case the overlay is the image "EdgeMap" which is transparent everywhere except where an edge has been detected.
  • For best results, downsize your image to around 200x200 pixels before passing it to this algorithm and set "scan" to 1. If you want to scan a larger image you will need to set "scan" to a higher value to maintain performance.
I hope this helps anyone who is trying to do something in this field, it's a tricky one. Please subscribe, more like this is on the way!