Bay 12 Games Forum

Please login or register.

Login with username, password and session length
Advanced search  
Pages: [1] 2

Author Topic: Your best code  (Read 4407 times)

dragnar

  • Bay Watcher
  • [Glub]
    • View Profile
Your best code
« on: December 22, 2009, 11:50:34 pm »

There seem to be a pretty large number of programmers on this forum, so I was wondering: What is your favorite/most impressive bit of code you have written?

Mine's a mask-based collision detection algorithm I wrote in python for a game I'm working on.
Logged
From this thread, I learned that video cameras have a dangerosity of 60 kiloswords per second.  Thanks again, Mad Max.

Outcast Orange

  • Bay Watcher
  • [SOMETIMES_SQUID]
    • View Profile
    • The Outcast Orange
Re: Your best code
« Reply #1 on: December 23, 2009, 12:00:29 am »

Here ya go. Took forever to perfect.
It still needs some editing.

Code: [Select]
void world::template_waterplate(){
    //prepare for loop
    int currentx = 1;
    int currenty = 1;
    int currentz = 1;
    int var6 = 0;
    int progressx = 0;
    bool loop = true;
    while(loop==true){
        if(basictile[currentx][currenty][currentz].gettype()==7){
            int waterstemy = currenty - 1;
            bool waterstemgo = true;
            while(waterstemgo==true){
                if(basictile[currentx][waterstemy][currentz].gettype()==0){
                    //start waterplate
                    bool waterplatego = true;
                    int testx = currentx - 1;
                    int testy = waterstemy;
                    int testz = currentz - 1;
                    bool testing = true;
                    while(testing==true){
                        //if a test point is occupied
                        if(basictile[testx][testy][testz].gettype()!=0){
                            //cancel waterplate
                            bool waterplatego = false;
                        }
                        //roll through test points
                        testx++;
                        //modification to roll:
                        //if test point is located at previous stem growth
                        if(testx==currentx&&testy==waterstemy+1&&testz==currentz){
                            //skip test point
                            testx++;
                        }
                        if(testx>currentx+1){
                            testx = currentx - 1;
                            testz++;}
                        if(testz>currentz+1){
                            testx = currentx - 1;
                            testz = currentz - 1;
                            testy++;}
                        if(testy>waterstemy+1){
                            testing = 0;}
                    }
                    //if waterplate is possible
                    if(waterplatego==true){
                        //cancel stem growth
                        waterstemgo = false;
                        //prepare for plate
                        testx = currentx - 1;
                        testy = waterstemy;
                        testz = currentz - 1;
                        testing = true;
                        //start adding plate
                        while(testing==true){
                            //add plate at current position
                            basictile[testx][testy][testz].settype(9);
                            basictile[testx][testy][testz].setstuck(true);
                            //roll through plate positions
                            testx++;
                            if(testx>currentx+1){
                            testx = currentx - 1;
                            testz++;}
                            if(testz>currentz+1){testing = false;}
                        }
                    }
                    //if waterstem is still going
                    if(waterstemgo==true){
                        //add stem
                        basictile[currentx][waterstemy][currentz].settype(8);
                        basictile[currentx][waterstemy][currentz].setstuck(true);
                        //move up a tile
                        waterstemy = waterstemy - 1;}
                }
                //if waterstem reaches top of universe, cancel growth (should never happen)
                if(waterstemy<1){waterstemgo = false;}
                //if waterstem is blocked, cancel growth
                if(basictile[currentx][waterstemy][currentz].gettype()!=0){waterstemgo = false;}
            }
        }
        currentx++;
if(currentx>dim){
currentx = 1;
currentz++;}
if(currentz>dim){
currentx = 1;
currentz = 1;
currenty++;
        }
if(currenty>dim){
loop = false;}
    }
}

Not super impressive, but I'm proud of it.
Of course, the local map Waterplates will be much more intense.
Logged
[7:53:55 PM] Armok, why did you demand that I don't eat you?
[7:54:34 PM] [Armok]: woooooo

Burried Houses - Platform Explorer Demo H - Cloud Scream

EagleV

  • Bay Watcher
  • Oblivisci tempta quod didicisti
    • View Profile
Re: Your best code
« Reply #2 on: December 23, 2009, 01:59:06 am »

I wrote a code in Java that will change, on a png, all magenta colors to a color given as argument (with pure magenta resulting in that color, and darker and lighter shades in darker and lighter colors.) It was for a game featuring maybe a hundred materials, and I didn't want to make a hundred pictures for each weapon...

I'll try to find the code.
Logged
Quote from: Robert Donoghue and Fred Hicks
There are three things you must learn if you wish to defeat me, my young pupil. First, you must look within yourself and find your core of strength. Second, your mind and body must be in perfect unison. Third...
*WHACK*
Third, stop listening when you should be fighting.

Armok

  • Bay Watcher
  • God of Blood
    • View Profile
Re: Your best code
« Reply #3 on: December 23, 2009, 07:32:35 am »

Most of the things I'm the most proud of are really ones that are in the interface between different modules, and can't really be understood by reading any single function, or data structures rather than the code itself.
Logged
So says Armok, God of blood.
Sszsszssoo...
Sszsszssaaayysss...
III...

Bricks

  • Bay Watcher
  • Because you never need one brick.
    • View Profile
Re: Your best code
« Reply #4 on: December 23, 2009, 01:50:55 pm »

Long ago, I wrote a simulation in Game Maker.  In one day and seven versions, I had this crazy boids-like sim that pitched two swarming groups against each other.  It was beautiful to watch, even though some of the code was a little ridiculous.  To this day, it's something I hope to recreate with some degree of rationalization behind the equations I used.

It's a little unrelated to coding, but I also created a simulation of a ring of equal mass points connected by ideal springs with a length of zero.  When set loose, they would trace out bizarre geometric figures and surfaces.  I was eventually able to derive equations for their motion using a set of linear differential equations and their eigenvalues/vectors, and demonstrated that they (as t->∞) spacefill a region.  The type of area filled depended on the number masses/springs.  Large numbers of masses (>7) would spacefill volumes, and even larger regions (>9) seemed to have no pattern, which I suspect was a limitation of working in three dimensions.  Pretty cool to know that you are looking at projections of higher dimensions.

I also wrote a bubble-sort algorithm that worked on the first run.  Silly, but I was pretty happy with myself.
Logged
EMPATHY - being able to feel other peoples' stuff.

Errol

  • Bay Watcher
  • Heaven or Hell, Duel 1 -- Let's Rock!
    • View Profile
Re: Your best code
« Reply #5 on: December 23, 2009, 02:37:36 pm »

Hacking around on a Touhou script engine thingy brought me immense satisfaction when I perfected an aiming code that was needlessly complex, at least three times as complex as the optimal solution, but still working. Fun times.
Logged
Girls are currently preparing signature, please wait warmly until it is ready.

dragnar

  • Bay Watcher
  • [Glub]
    • View Profile
Re: Your best code
« Reply #6 on: December 23, 2009, 02:45:38 pm »

Here ya go. Took forever to perfect.
It still needs some editing.

Code: [Select]
gibberish

Not super impressive, but I'm proud of it.
Of course, the local map Waterplates will be much more intense.
So what exactly does this do? I don't know any C++ yet, though I'll be learning it next semester for my programming class.
Logged
From this thread, I learned that video cameras have a dangerosity of 60 kiloswords per second.  Thanks again, Mad Max.

EagleV

  • Bay Watcher
  • Oblivisci tempta quod didicisti
    • View Profile
Re: Your best code
« Reply #7 on: December 23, 2009, 03:00:11 pm »

Found it. Behold, the texturemixer.

Code: [Select]
package conversion;

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.MemoryImageSource;
import java.awt.image.PixelGrabber;

public abstract class TextureMixer {

private static short baseR, baseG, baseB;
private static PixelGrabber grabber;
private static Image texture;
private static int[] pixelList;
private static int[][] pixelArrayR, pixelArrayG, pixelArrayB, pixelArrayA;
private static int width, height;

public static Image mixTexture(String filename, int lightR, int lightG, int lightB, int darkR, int darkG, int darkB){

// Testcode
// long m1 = System.currentTimeMillis();

width = 16;
height = 16;

texture = Toolkit.getDefaultToolkit().getImage("src/textures/" + filename + ".png");;

pixelList = new int[width * height];

pixelArrayA = new int[width][height];
pixelArrayR = new int[width][height];
pixelArrayG = new int[width][height];
pixelArrayB = new int[width][height];

// Magenta = 255,0,255.
baseR = 255;
baseG = 0;
baseB = 255;

grabber = new PixelGrabber(texture, 0, 0, width, height, pixelList, 0, width);
grabber.startGrabbing();

// Puts all pixels from the texture in a list
try {
grabber.startGrabbing();
while(!grabber.grabPixels()){
}
} catch (InterruptedException e) {
System.out.println("src/worldModel/TerrainType/convertImage: " + e);
}

// Converts the hex list to 4 'readable' lists (RGB and alpha)
for(int i = 0; i < width; i++){
for(int j = 0; j < height; j++){
int pixel = pixelList[i + (j*width)];

pixelArrayA[i][j] = (pixel >> 24) & 0xFF;

pixelArrayR[i][j] = (pixel >> 16) & 0xFF;

pixelArrayG[i][j] = (pixel >> 8) & 0xFF;

pixelArrayB[i][j] = (pixel) & 0xFF;

// Converts every pixel with the correct RGB (magenta) to the 'light color'
if(pixelArrayR[i][j] == baseR && pixelArrayG[i][j] == baseG && pixelArrayB[i][j] == baseB){
pixelArrayR[i][j] = lightR;
pixelArrayG[i][j] = lightG;
pixelArrayB[i][j] = lightB;

/*
* Converts every shade of gray to the 'dark color' multiplied by the intensitie of the grayness.
* In other words, black stays black, white becomes the dark color, and everything inbetween
* becomes a darker shade of the 'dark' color.
*/
} else if(pixelArrayR[i][j] == pixelArrayG[i][j] && pixelArrayR[i][j] == pixelArrayB[i][j]) {
pixelArrayR[i][j] = Math.round(darkR * pixelArrayR[i][j]/255);
pixelArrayG[i][j] = Math.round(darkG * pixelArrayR[i][j]/255);
pixelArrayB[i][j] = Math.round(darkB * pixelArrayR[i][j]/255);
}
}
}

// Converts the 4 human-readable lists (notice the alpha hasn't changed) back to the hex list
int[] pixelList = new int[width * height];

for(int i = 0;i < width; i++){
for(int j = 0;j < height; j++){
    pixelList[i + (j*width)] = ((pixelArrayA[i][j] << 24)& 0xFF000000)
    |   ((pixelArrayR[i][j] << 16) & 0x00FF0000)
                                | ((pixelArrayG[i][j] << 8) & 0x0000FF00)
                                | ((pixelArrayB[i][j]) & 0x000000FF);
    }
}

// Testcode
// long m2 = System.currentTimeMillis();
// System.out.println("Duration: " + (m2 - m1));

return Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(width, height, pixelList, 0, width));
}

}
Logged
Quote from: Robert Donoghue and Fred Hicks
There are three things you must learn if you wish to defeat me, my young pupil. First, you must look within yourself and find your core of strength. Second, your mind and body must be in perfect unison. Third...
*WHACK*
Third, stop listening when you should be fighting.

Outcast Orange

  • Bay Watcher
  • [SOMETIMES_SQUID]
    • View Profile
    • The Outcast Orange
Re: Your best code
« Reply #8 on: December 23, 2009, 03:33:06 pm »

So what exactly does this do? I don't know any C++ yet, though I'll be learning it next semester for my programming class.

Sorry, I thought it was kind of self evident from the function name.
It's the geometry for my world map Waterplates,
 the small blue features that form near the top of my universe.

It is pretty pathetic,
 but at the time I had no idea how to make semi-complex geometries out of tiles.
It was sort of a break through,
 so now I can very easily create features of a somewhat higher complexity.

The best examples are sort of a hidden feature of my game, or I'd post a picture.

Ah, never mind, they have a ~30% chance of appearing on every map, so no major spoiler:
Spoiler (click to show/hide)

Those "buildings" were designed to blend into the surroundings, as if hidden.
All five of the ones present in that screenshot were created using separate calls of the same function.

Here's a cutaway of the interior:
Spoiler (click to show/hide)

Once again, not super impressive, but this is my first real game, so I'm very new to this.
Logged
[7:53:55 PM] Armok, why did you demand that I don't eat you?
[7:54:34 PM] [Armok]: woooooo

Burried Houses - Platform Explorer Demo H - Cloud Scream

Calculus

  • Bay Watcher
    • View Profile
Re: Your best code
« Reply #9 on: December 25, 2009, 05:51:03 pm »

Years ago I wrote robot for a real time combat game, that would connect to the game and keep track of all kills and kill details for later detailed graphing. I did all protocol decoding with a packet sniffer. It was written in PHP, since that was what I knew at the time. This proves Turing equivalence.

The other is code for a big multinational group of organizations, that allows they to keep track of where the money is going. I wrote some voodoo Python code that lets me define budget view templates with code like:

{{budget.ytd.expense.budgeted_amount}}

{{budget.qtr1.income.actual_amount}}

{{category.actual_amount}}

etc.

« Last Edit: December 25, 2009, 05:55:46 pm by Calculus »
Logged

SolarShado

  • Bay Watcher
  • Psi-Blade => Your Back
    • View Profile
Re: Your best code
« Reply #10 on: December 26, 2009, 12:11:28 am »

I wrote a recursive space-filing function in Java this past week, I'm almost certain it's not the most efficient one possible, but it works. It's used to determine where a unit can move to in a turn-based strategy game I'm working on.
Code: [Select]
//fills ret with Points of squares reachable from pA up to distance dist
private static void spaceFillRecurse(GameSquare pA, int dist, Vector<Point> ret) {
 add(ret,pA.getCoordinates());
 if(dist <= 0) { return; }

 Point tmp  = pA.getCoordinates();
 Point tmpN = translate(tmp,0,-1);
 Point tmpS = translate(tmp,0,1);
 Point tmpE = translate(tmp,1,0);
 Point tmpW = translate(tmp,-1,0);

 if(pA.getGrid().getSquare(tmpN) != null && pA.getGrid().getSquare(tmpN).getTransversible()) {
  spaceFillRecurse(pA.getGrid().getSquare(tmpN), dist-1, ret);
 }

 if(pA.getGrid().getSquare(tmpS) != null && pA.getGrid().getSquare(tmpS).getTransversible()) {
  spaceFillRecurse(pA.getGrid().getSquare(tmpS), dist-1, ret);
 }

 if(pA.getGrid().getSquare(tmpE) != null && pA.getGrid().getSquare(tmpE).getTransversible()) {
  spaceFillRecurse(pA.getGrid().getSquare(tmpE), dist-1, ret);
 }

 if(pA.getGrid().getSquare(tmpW) != null && pA.getGrid().getSquare(tmpW).getTransversible()) {
  spaceFillRecurse(pA.getGrid().getSquare(tmpW), dist-1, ret);
 }
}

//rets true if p is already in v
private static boolean add(Vector<Point> v, Point p) {
 synchronized(v) {
  for(int i=0; i < v.size() ;i++) {
   if(v.get(i).equals(p)) { return true; }
  }
  v.add(p); return false;
 }
}

//rets a translated clone of p
private static Point translate(Point p, int x, int y) {
 Point ret = (Point)p.clone();
 ret.translate(x,y);
 return ret;
}
Anyone's free to use it. Any suggestions for improvement are welcome too.
Logged
Avid (rabid?) Linux user. Preferred flavor: Arch

jplur

  • Bay Watcher
    • View Profile
    • http://www.parker-portfolio.com
Re: Your best code
« Reply #11 on: December 26, 2009, 12:46:13 pm »

A binary space partition dungeon generator, written in python.

Not the cleanest code, but one of my best.

Spoiler (click to show/hide)
Logged
I ended up finding out you can speed up pregnancies by changing the mother to a cat to knock them up and changing back before labor

eerr

  • Bay Watcher
    • View Profile
Re: Your best code
« Reply #12 on: December 27, 2009, 02:27:29 am »

Most of the things I'm the most proud of are really ones that are in the interface between different modules, and can't really be understood by reading any single function, or data structures rather than the code itself.
With a scripting language?
Logged

Armok

  • Bay Watcher
  • God of Blood
    • View Profile
Re: Your best code
« Reply #13 on: December 27, 2009, 07:26:38 am »

no, all the examples I can think of currently are either python or assembly.
Logged
So says Armok, God of blood.
Sszsszssoo...
Sszsszssaaayysss...
III...

eerr

  • Bay Watcher
    • View Profile
Re: Your best code
« Reply #14 on: December 27, 2009, 03:57:32 pm »

no, all the examples I can think of currently are either python or assembly.
was the assembly really necessary?
Logged
Pages: [1] 2