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 DevConnect Center
 Service Component Architecture/Service Data Objects Solution Center
 Intel Go Parallel Portal
 Internet.com eBook Library
 IBM Software Construction Toolbox
 Microsoft RIA Development Center
 Destination .NET
XML error: not well-formed (invalid token) at line 53
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%.

Is .NET on Linux Finally Ready?
Red Hat Takes on HPC Market, Microsoft
Python's New Release Bridges the Gap
No Flash Seen on iPhone Horizon
Apple Yields to Complaints Over iPhone NDA
Microsoft Shows Some Ankle With Visual Studio
Gentoo Linux Cancels Distribution
It's Official: Windows 7 at PDC, WinHEC
Oracle Keeps Building on Spoils From BEA
Intel, Oracle Head For 'The Cloud'

C++Ox: The Dawning of a New Standard
Getting Started with Virtualization
Master Complex Builds with MSBuild
eCryptfs: Single-File Encryption in Linux
CCXML in Action: A CCXML Auto Attendant
Ballmer: Current Woes Won't Halt Tech, Microsoft
Microsoft Uses VMworld to Hype Its Hypervisor
Microsoft Charges Ahead in Virtualization
Microsoft Shows Some Ankle With Visual Studio
Top 5 Reasons to Adopt SQL Server 2008

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



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Internet.com eBook: The Pros and Cons of Outsourcing
Go Parallel Article: Scalable Parallelism with Intel(R) Threading Building Blocks
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES