advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement


Tutorials : Java by Example : Section 7 :
Section Seven Contents
Fun With Letters and Words
Rotating Lines and Polygons
Sorting and Shuffling

Letters - Words - Lines - Shuffle

Sorting and Shuffling

Two of the most needed algorithms (not only) for game programming are sorting and shuffling of a series (an array) of numbers. The following applet combines them in an easy to understand and pleasant to look at manner. It also features three custom drawn buttons, for sorting, shuffling and drawing new numbers. On every draw 77 new numbers (represented by the int MAX) in the range 1 to 200 are drawn: getNewNumbers() and are stored in the array number[]. In this method it is also made sure that the same number is never drawn twice, to demonstrate this algorithm here too (although it is by no means advisable to use this technique always. A series of truely random numbers almost always includes doubles!). To get the array sorted, we use the method sortArray() and the helper method sort(int, int). Since simple data types cannot be passed by reference (as they can in C/C++), we need to declare two separate int variables a and b to hold the values of the sorting in every loop we call the sort(int,int) method.

To (re)shuffle the array, we use the method shuffle, which replaces every element of the array with a randomly selected other element.
In the method drawStuff() we use a tricky piece of code to draw the content of each array element in a neatly arranged table, whenever the array is sorted:

int j=15;
int k=10;

for(i=0;i<MAX;i++)
{
    if(sorted)
        gBuffer.drawString(""+number[i],k,j);

    if((i+1)%11==0){k=10;j+=10;}
        else {k+=20;}
}

i+1%11==0 means, "whenever the rest of a division of i+1 with 11 is 0". Since we have 77 array elements, I arranged the numbers in 11 columns and 7 rows. So, when the 11th element in a row is drawn, the y coordinate for the next row is incremented by 10 pixels and the x coordinate is assigned the value 10, for the first column. Else, the x value for the numbers is incremented by 20 pixels in each round of the loop.

In order for the custom drawn buttons (the Java buttons are just plain ugly and cannot be placed where you want) to react on mouseMove and mouseDown events, we place methods of our FancyButton class inside our according applet methods. This way we can submit the mouse coordinates to our button objects and can submit mouse clicks within the button rectangles, to set the public boolean flag variable "pressed" and to make the button appear pressed (last argument in the draw3DRect method).

//Sourcecode

import java.awt.*;
import java.applet.*;

class FancyButton
{
    private String text;
    public boolean over, pressed;
    private Rectangle r=new Rectangle();
    private Graphics g;
    private Font font;
    private Color color=new Color(180,180,65);

    public FancyButton(String s, int x, int y, int w, int h)
    {
        text=s;
        r.x=x;
        r.y=y;
        r.width=w;
        r.height=h;

        font=new Font("Dialog", Font.PLAIN, 10);
    }

    public void reportMouseMovement(int x, int y)
    {
        if(r.inside(x,y))
            over=true;
        else
            over=false;
    }

    public void reportMouseDown(int x, int y)
    {
        if(r.inside(x,y))
            pressed=true;
    }

    private void drawButton()
    {
        g.setColor(color);

        if(!over)
        {
            g.drawRect(r.x,r.y,r.width,r.height);
        }
        else
        {
            g.draw3DRect(r.x,r.y,r.width,r.height,!pressed);
        }

        //measure the size of the string to center it
        FontMetrics fm = g.getFontMetrics(font);
        int stringWidth=fm.stringWidth(text);
            int stringHeight=g.getFontMetrics().getAscent()+6;

        g.setFont(font);
        g.setColor(Color.black);

        //center the string inside the button
        g.drawString(text, (r.x+r.width/2)-stringWidth/2,
        r.y+r.height-stringHeight/2);
    }

    public void paint(Graphics gr)
    {
        g=gr;
        drawButton();
    }
}

public class Project43 extends Applet
{
    Image Buffer;
    Graphics gBuffer;
    Font font;
    int a,b,i,j,number[];
    final static int MAX=77;
    boolean sorted;
    FancyButton fb1,fb2,fb3;

    public void init()
    {
        Buffer=createImage(size().width,size().height);
        gBuffer=Buffer.getGraphics();
        font=new Font("Helvetica", Font.PLAIN, 10);

        fb1=new FancyButton("Sort",50,215,80,25);
        fb2=new FancyButton("Shuffle",150,215,80,25);
        fb3=new FancyButton("New Numbers",250,215,100,25);

        number = new int[MAX];

        getNewNumbers();
    }

    void getNewNumbers()
    {
        //fill our array with random numbers
        //guarantee different numbers to be drawn!
        for (i=0;i<MAX;i++)
        {
            //Random number from 1 to 200
            int rnd = ((int)(Math.random()*200)+1);

            number[i]=rnd;

            if (i>0)
            {
                for (j=i;j>0;j--)
                {
                    if (number[i]==number[j-1])
                        i--;
                }
            }
        }
    }

    void sort(int k, int l)
    {
        if(k>l)
        {
            int temp=k;
            k=l;
            l=temp;
        }
        a=k;
        b=l;
    }

    void sortArray()
    {
        for(i=0; i<MAX; i++)
        {
            for(j=i+1;j<MAX;j++)
            {
                sort(number[i],number[j]);

                number[i]=a;
                number[j]=b;
            }
        }
    }

    void shuffle()
    {
        for(i=0; i<MAX; i++)
        {
            j=(int)(Math.random()*MAX);

            if(i!=j)
            {
                int temp=number[i];
                number[i]=number[j];
                number[j]=temp;
            }
        }
    }

    public void drawStuff()
    {
        gBuffer.setColor(new Color(235,235,210));
        gBuffer.fillRect(0,0,size().width,size().height);

        gBuffer.setColor(Color.black);
        gBuffer.drawRect(0,0,size().width-1,size().height-1);

        for(i=0;i<MAX;i++)
        {
            gBuffer.setColor(Color.red);
            gBuffer.fill3DRect(i*5+8,205-number[i],4,number[i],true);
        }

        fb1.paint(gBuffer);
        fb2.paint(gBuffer);
        fb3.paint(gBuffer);

        gBuffer.setFont(font);
        gBuffer.setColor(Color.blue);

        j=15;
        int k=10;

        for(i=0;i<MAX;i++)
        {
            if(sorted)
                gBuffer.drawString(""+number[i],k,j);

            if((i+1)%11==0){k=10;j+=10;}
                else {k+=20;}
        }
    }

    public boolean mouseMove(Event evt,int x,int y)
    {
        fb1.reportMouseMovement(x,y);
        fb2.reportMouseMovement(x,y);
        fb3.reportMouseMovement(x,y);

        repaint();
        return true;
    }

    public boolean mouseDown(Event evt,int x,int y)
    {
        fb1.reportMouseDown(x,y);
        fb2.reportMouseDown(x,y);
        fb3.reportMouseDown(x,y);

        if(fb1.pressed){sortArray();sorted=true;}
        if(fb2.pressed){shuffle();sorted=false;}
        if(fb3.pressed){getNewNumbers();sorted=false;}

        repaint();
        return true;
    }

    public boolean mouseUp(Event evt,int x,int y)
    {
        fb1.pressed=fb2.pressed=fb3.pressed=false;

        repaint();
        return true;
    }

    public void update(Graphics g)
    {
        paint(g);
    }

    public void paint(Graphics g)
    {
        drawStuff();

        g.drawImage (Buffer,0,0, this);
    }
}

 

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 Avaya Developer Showcase
 MSDN Spotlight
 PHP for Windows Showcase
XML error: undefined entity at line 34
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

IBM Brings Developers Into the Cloud
Apache at 10: You Can't Buy Us
Microsoft's CodePlex Foundation Moving Forward
Apple Claims 100,000 Apps, Google Analyzes Them
Nokia Latest to Play Opera Mobile 10 Browser
PayPal Opens Up Payment Platform to Devs
Ubuntu Linux 9.10 'Karmic Koala' Starts Its Climb
IBM Links Rational Developer Tools, Tivoli Apps
Libraries Give Vista Apps a Windows 7 Look
Ubuntu: The 'Default Alternative' to Windows?

Delivering Web-based Embedded Fonts in CSS 3
Adobe Helps PHP Developers Create Rich Internet Applications
Java Developers Finding a Home at Adobe Flex
Virtualization Delivers a Dynamic Infrastructure
Consuming XML Web Services in iPhone Applications
Build a More Agile Business with IBM
POJO-Based Solutions for LDAP Access: One Good, One Better
IBM Offers Enhanced Measurement and Management for Energy Usage
IBM Helps Transformation to an Information-Based Enterprise
Top Five Touch UI-Related Design Guidelines

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs