Banner en java

Banner es el clásico programa de unix para sacar por consola un texto en tamaño grande. Había planteado esto y me mandaron una soluciones efectivas pero algo choriceras. Yo planteo esta. Lo hago pensando orientado a objetos, por tanto divido el problema en cosas, no en funciones. Las cosas que salen son: caracteres, pantalla, y alguien que escribe. En java me quedarían 4 clases, una añadida para hacer el main.

Letter

Este es un hashtable que contiene las letras en un hashtable. No he metido todas, porque al igual que a Carlos esto es algo denigrante.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.cuatrovientos.banner;

import java.util.Hashtable;

/**
 * Letters
 * singleton hashtable that holds all letters
 * @author Pello Xabier
 * note: from now on I'll not forget the private constructor, I swear ;)
 */
public class Letters extends Hashtable<String, String[][]>{

    private static Letters letters = null;
    private static final int LETTER_WIDTH = 4;
    private static final int LETTER_HEIGHT = 5;
    
    /**
     * private constructor
     */
    private Letters () {
        initialize();
    }

    /**
     * getLetters
     * @return
     */
    public static Letters getLetters () {
        if (letters == null) {
            letters = new Letters();
        }

        return letters;
    }

    /**
     * initialize
     * puts letters into the hashtable
     * Note: I'll NOT put all letters, It's too late for this,
     * and I know that this font is horrid, but gimme a break.
     */
    private void initialize () {
        this.put("A",new String[][]{{"A","A","A","A"},
                                    {"A"," "," ","A"},
                                    {"A","A","A","A"},
                                    {"A"," "," ","A"},
                                    {"A"," "," ","A"}});
        this.put("B",new String[][]{{"B","B","B","B"},
                                    {"B"," "," ","B"},
                                    {"B","B","B"," "},
                                    {"B"," "," ","B"},
                                    {"B","B","B","B"}});
        this.put("C",new String[][]{{"C","C","C","C"},
                                    {"C"," "," "," "},
                                    {"C"," "," "," "},
                                    {"C"," "," "," "},
                                    {"C","C","C","C"}});
        this.put("D",new String[][]{{"D","D","D"," "},
                                    {"D"," "," ","D"},
                                    {"D"," "," ","D"},
                                    {"D"," "," ","D"},
                                    {"D","D","D"," "}});
        this.put("E",new String[][]{{"E","E","E","E"},
                                    {"E"," "," "," "},
                                    {"E","E","E"," "},
                                    {"E"," "," "," "},
                                    {"E","E","E","E"}});
    }


    /**
     * getHeight
     * @return hegith of letters
     */
    public int getHeight () {
        return LETTER_HEIGHT;
    }

    /**
     *  getWidth
     * @return width of letters
     */
    public int getWidth () {
        return LETTER_WIDTH;
    }

}
 

Screen

Representa la pantalla, es una especie de lienzo en forma de array de Strings. La función fill es la que nos permite pintar un caracter en unas coordenadas. Y finalmente la función draw vuelca todo el lienzo en pantalla.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.cuatrovientos.banner;

/**
 * Screen
 * The class where we paint the Letters
 * @author Pello Xabier
 * note: from now on I'll not forget the private constructor, I swear ;)
 */
public class Screen {
    private final static int WIDTH = 80;
    private final static int HEIGHT = 24;
    private final static String WHITESPACE = " ";
    private final static char NEWLINE = '\n';
    private String[][] canvas = new String[HEIGHT][WIDTH];
    private static Screen theScreen = null;

    // private constructor
    private Screen () { clear(); }

    /**
     * clears the screen
     */
    private void clear () {
        for (int h = 0;h< HEIGHT; h++)
            for (int w=0;w<WIDTH; w++)
                canvas[h][w] = WHITESPACE;
    }

    /**
     * getScreen
     * @return the one and only screen instance
     */
    public static Screen getScreen() {
        if (theScreen == null) {
            theScreen = new Screen();
        }

        return theScreen;
    }

    /**
     * fill
     * fills  the screen with a matrix at given coords
     * @param what
     * @param x
     * @param y
     */
    public void fill (String[][] what, int x, int y) {

        if (boundsOk(x,y)) {
            int i = 0, j = 0;
            //go on and fill the canvas
            for (int h = y;h< y+what.length; h++) {
                for (int w=x;w<x+what[0].length; w++)
                    canvas[h][w] = what[i][j++];
                i++;j=0;
            }//for

        }//if
    }

    /**
     * draw
     * paints contents on console
     */
    public void draw () {
        for (int h = 0;h< HEIGHT; h++) {
            for (int w=0;w<WIDTH; w++)
                System.out.print(canvas[h][w]);
            System.out.print(NEWLINE);
        }
    }

    /**
     * boundsOk
     * tell us if given coords are inside Screen margins
     * @param x
     * @param y
     * @return true if coords are ok.
     */
    public boolean boundsOk (int x, int y) {
        return (y >= 0 && y < HEIGHT && x >= 0 && x < WIDTH);
    }
}
 

Writer

Usando la pantalla va escribiendo caracteres y avanzando el cursor.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.cuatrovientos.banner;

/**
 * Writer
 * Gets the Screen and writes a word on It.
 * @author Pello Xabier
 */
public class Writer {

    private int initialX;
    private int initialY;

    /**
     * Writer
     * constructor
     * initializes positions at 0
     */
    public Writer () {
        initialX = 0;
        initialY = 0;
    }


    /**
     * Writer
     * constructor
     * initializes positions at x,y
     */
    public Writer (int x , int y) {
        if (Screen.getScreen().boundsOk(x, y)) {
            initialX = x;
            initialY = y;
        } else { // bajeril stylo
            initialX = initialY = 0;
        }
    }

    /**
     * writes the string
     * @param messageToWrite
     */
    public void write (String messageToWrite) {
        int x = initialX;
        int y = initialY;

        if (messageDoesNotFitScreen(messageToWrite)) {
            System.out.println("Sorry. Message does not fit the screen");
            return;
        }

        // It's ok, we took each letter, we write on the screen and we move the cursor forward
        for (int i = 0; i< messageToWrite.length();i++) {
            // TODO next line: choose btw coolness and refactoring
            Screen.getScreen().fill(Letters.getLetters().get(messageToWrite.substring(i, i+1).toUpperCase()), x, y);
            x = x + Letters.getLetters().getWidth() + 1;
        }
        
        // Finally, we draw the screen
        Screen.getScreen().draw();
    }


    /**
     * messageDoesNotFitScreen
     * @param message
     * @return true if message is longer than screen width
     */
    private boolean messageDoesNotFitScreen (String message) {
        return (((message.length()+1) * Letters.getLetters().getWidth()) > 80);
    }
}
 

Main

Instancia writer y escribe,  no más.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.cuatrovientos.banner;

/**
 *
 * @author pello xabier
 * @greetz 1º DAM @cuatrovientos
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        Writer writer = new Writer(5,7);

        writer.write("ABC");
    }

}
 

by Pello Altadill 02/03/2013 00:44:51 - 838 hits