Java by Example - fun with letters and words

back 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 next

Let's have a little fun with random letters! First, we create a String object alphabet, containing all 26 letters of the alphabet. Then we draw a random number between 0 and 25 and use it as an argument in the String method substring. We pass two integer arguments for the first and the last character of the new substring, so we get a random character. To make it fun to watch, we also randomize the color, size and position of the letter on the screen. After some time, we redraw the background black.

//Sourcecode

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

public class Project37 extends Applet implements Runnable
{
    Thread runner;
    Image Buffer;
    Graphics gBuffer;
    String alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int ticker;

    public void init()
    {
        //create graphics buffer, the size of the applet
        Buffer=createImage(size().width,size().height);
        gBuffer=Buffer.getGraphics();
    }

    public void start()
    {
        if (runner == null)
        {
            runner = new Thread (this);
            runner.start();
        }
    }

    public void stop()
    {
        if (runner != null)
        {
            runner.stop();
            runner = null;
        }
    }

    public void run()
    {
        while(true)
        {
            try {runner.sleep(50);}
            catch (Exception e) { }

            repaint();
        }
    }

    public void drawStuff()
    {
        //repaint background after 20 seconds
        if(ticker==0)
        {
            gBuffer.setColor(Color.black);
            gBuffer.fillRect(0,0,size().width,size().height);
        }

        ticker++;
        if(ticker>400)
            ticker=0;

        //random font size 10..50
        int fontSize=(int)(Math.random()*40)+10;

        //random font color
        int red=(int)(Math.random()*255);
        int green=(int)(Math.random()*255);
        int blue=(int)(Math.random()*255);
        gBuffer.setColor(new Color(red, green, blue));

        //random coordinates within the applet bounderies
        int x=(int)(Math.random()*size().width);
        int y=(int)(Math.random()*size().height);

        //random substring from the alphabet string (one out of 26 characters)
        int character=(int)(Math.random()*26);
        String s=alphabet.substring(character, character+1);

        gBuffer.setFont(new Font("TimesRoman", Font.PLAIN,  fontSize));
        gBuffer.drawString(s,x,y);
    }

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

    public void paint(Graphics g)
    {
        drawStuff();
        g.drawImage (Buffer,0,0, this);
    }
}

Now let's have some real fun with falling letters! We create a class FallingCharacter that represents the falling letters. We create an array of objects of that class (here: 100, represented by the variable MAX, can be changed easily). Each object takes care for random values for the initial position, size, color and speed! The speed is represented by the double precision floating point variable yinc, which is added to the y position in the member method fall(). Only floating point variables guarantee for smooth movement in many different speed values. They are casted to int values only in the paint method, in the end. The constructor of the FallingCharacter class receives the width and height of the applet as parameters, to make it possible to easily change the applet size without changing the code. After reaching the bottom of the window, the letters reappear at the top again.

//Sourcecode

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

class FallingCharacter
{
    int fontSize, h;
    double x, y, yinc;
    String s, alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    Color color;
    Graphics g;
    Font font;

    public FallingCharacter(int width, int height)
    {
        h=height;

        //random font size 10..50
        fontSize=(int)(Math.random()*40)+10;
        font=new Font("TimesRoman", Font.PLAIN,  fontSize);

        //random font color
        int red=(int)(Math.random()*255);
        int green=(int)(Math.random()*255);
        int blue=(int)(Math.random()*255);
        color=new Color(red, green, blue);

        //random initial coordinates within the applet bounderies
        x=(Math.random()*width);
        y=(Math.random()*height);

        //random falling speed
        yinc=(Math.random()*2.5)+1.0;

        //random substring from the alphabet string (one out of 26 characters)
        int character=(int)(Math.random()*26);
        s=alphabet.substring(character, character+1);
    }

    public void fall()
    {
        if(y<h+fontSize)
            y+=yinc;
        else
            y=-fontSize;
    }

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

        g.setColor(color);
        g.setFont(font);
        g.drawString(s,(int)x,(int)y);
    }
}

public class Project38 extends Applet implements Runnable
{
    Thread runner;
    Image Buffer;
    Graphics gBuffer;
    int i;
    static final int MAX=100;
    FallingCharacter fc[];

    public void init()
    {
        //create graphics buffer, the size of the applet
        Buffer=createImage(size().width,size().height);
        gBuffer=Buffer.getGraphics();

        fc = new FallingCharacter[MAX];

        for(i=0;i<MAX;i++)
            fc[i] = new FallingCharacter(size().width-30,size().height);
    }

    public void start()
    {
        if (runner == null)
        {
            runner = new Thread (this);
            runner.start();
        }
    }

    public void stop()
    {
        if (runner != null)
        {
            runner.stop();
            runner = null;
        }
    }

    public void run()
    {
        while(true)
        {
            Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

            try {runner.sleep(15);}
            catch (Exception e) { }

            repaint();
        }
    }

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

        for(i=0;i<MAX;i++)
            fc[i].fall();

        for(i=0;i<MAX;i++)
            fc[i].paint(gBuffer);
    }

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

    public void paint(Graphics g)
    {
        drawStuff();
        g.drawImage (Buffer,0,0, this);
    }
}

To conclude this chapter, let's create some funny random words! Some of them will sound familiar, some really are. The algorithm is quite similar to the last applets, but this time we create two String constants, containing vowels and the consonants each. In our method randomWord(), which returns the random string when we call it, we create 3 random characters, each of the vowels and the consonants string. Then we combine these characters in a specific order, to get words without two consonants or vowels in succession. I use one of four algorithms, that are selected at random. To make it more fun to watch, I create only 1 word a second and print them one below the other and shifted to the right, until the window is full. Then the background is repainted and everything starts again.

//Sourcecode

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

public class Project39 extends Applet implements Runnable
{
    Thread runner;
    Image Buffer;
    Graphics gBuffer;
    String vowels="aeiouy";                       //6 characters
    String consonants="bcdfghklmnprstvwz";        //17 characters
    int x=10, y=30;
    Font font=new Font("Helvetica", Font.PLAIN,  30);
    Color bgColor=new Color(0,120,0);

    public void init()
    {
        //create graphics buffer, the size of the applet
        Buffer=createImage(size().width,size().height);
        gBuffer=Buffer.getGraphics();
    }

    public void start()
    {
        if (runner == null)
        {
            runner = new Thread (this);
            runner.start();
        }
    }

    public void stop()
    {
        if (runner != null)
        {
            runner.stop();
            runner = null;
        }
    }

    public void run()
    {
        while(true)
        {
            try {runner.sleep(1000);}
            catch (Exception e) { }

            repaint();
        }
    }

    String randomWord()
    {
        int c1=(int)(Math.random()*17);
        int c2=(int)(Math.random()*17);
        int c3=(int)(Math.random()*17);

        String sc1=consonants.substring(c1, c1+1);
        String sc2=consonants.substring(c2, c2+1);
        String sc3=consonants.substring(c2, c2+1);

        int v1=(int)(Math.random()*6);
        int v2=(int)(Math.random()*6);
        int v3=(int)(Math.random()*6);

        String sv1=vowels.substring(v1, v1+1);
        String sv2=vowels.substring(v2, v2+1);
        String sv3=vowels.substring(v3, v3+1);

        //algo 0=cvcvc
        //algo 1=cvcvcv
        //algo 2=vcvc
        //algo 3=vcvcv

        String word;
        int algo=(int)(Math.random()*4);

        switch(algo)
        {
            case 0: word=sc1+sv1+sc2+sv2+sc3;
                break;

            case 1: word=sc1+sv1+sc2+sv2+sc3+sv3;
                break;

            case 2: word=sv1+sc1+sv2+sc2+sv3;
                break;

            default: word=sv1+sc1+sv2+sc2+sv3+sc3;
        }

        return word;
    }

    void drawStuff()
    {
        //repaint background if window is full
        if(y==30)
        {
            gBuffer.setColor(bgColor);
            gBuffer.fillRect(0,0,size().width,size().height);
        }

        gBuffer.setFont(font);

        //pause after the last word
        if(y<300)
        {
            String s=randomWord();
            //the drop shadow
            gBuffer.setColor(Color.black);
            gBuffer.drawString(s,x+2,y+2);

            gBuffer.setColor(Color.green);
            gBuffer.drawString(s,x,y);
        }

        y+=36;
        x+=25;

        if(y>350)
        {
            y=30;
            x=10;
        }
    }

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

    public void paint(Graphics g)
    {
        drawStuff();
        g.drawImage (Buffer,0,0, this);
    }
}

back 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 next

0 - setup - getting your tools ready
1 - basic graphics functions
2 - simple methods and basic data types
3 - IF, ELSE and SWITCH: basic control structures
4 - introducing the operators
5 - methods with and without a return value
6 - using methods and basic mouse functions
7 - fonts, random numbers and timers
8 - flicker free graphics, GIF and JPEG display
9 - animation with GIF pictures, sprite animation
10 - loops, advanced color functions
11 - random colors and arrays
12 - digital clocks, HTML page parameters
13 - introducing classes and objects
14 - using the Vector class
15 - using mouseMove and mouseDrag
16 - keyboard commands and playing sound
17 - detecting collisions and intersections
18 - a Bouncing Balls applet
19 - fun with letters and words
20 - rotating lines and polygons
21 - sorting and shuffling


© 2000 by Johannes Wallroth
www.programming.de

watson@programming.de