Friday, August 9, 2024

java: graphics2d and rotation test

 

import java.awt.BasicStroke;

import java.awt.EventQueue;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.geom.AffineTransform;

import java.awt.image.BufferedImage;

import java.io.IOException;


import javax.imageio.ImageIO;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.border.EmptyBorder;


public class JFrameRotate extends JFrame {


private static final long serialVersionUID = 1L;

private JPanel contentPane;


/**

* Launch the application.

*/

public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {

public void run() {

try {

JFrameRotate frame = new JFrameRotate();

frame.setVisible(true);

} catch (Exception e) {

e.printStackTrace();

}

}

});

}

int panelWidth=600, panelHeight=600;


/**

* Create the frame.

*/

public JFrameRotate() {

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setBounds(0, 0, panelWidth, panelHeight);

contentPane = new JPanel();

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));


setContentPane(contentPane);

loadCard();

}


// JFrame: public void paint(Graphics g)

// JPanel: protected void paintComponent(Graphics g)

@Override

public void paint(Graphics g) {

if (bImg!=null) {

//g.drawImage(bImg, xCenter, yCenter, this);

// draw the image

Graphics2D g2d = (Graphics2D) g;

g2d.drawImage(bImg, rotate(10), contentPane);

g2d.drawImage(bImg, rotate(45), contentPane);

g2d.drawImage(bImg, rotate(90), contentPane);

g2d.drawImage(bImg, rotate90(), contentPane);

}

}

int strokeImg =1, widthImg=100, heightImg=150;

int xCenter=200, yCenter=300;

BufferedImage bImg;

private void loadCard() {

bImg = new BufferedImage(widthImg,

heightImg, BufferedImage.TYPE_INT_BGR);

Graphics2D g2d = bImg.createGraphics();

g2d.setStroke(new BasicStroke(1)); // 1 pixel

// https://stackoverflow.com/questions/31152233/opening-image-asset-java-jdk-8

String sFName = "/images/KC.png"; // See here to setup image resources

BufferedImage img;

try {

img = ImageIO.read(getClass().getResource(sFName));

g2d.drawImage(img, strokeImg, strokeImg, widthImg-(2*strokeImg),

heightImg-(2*strokeImg), this);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

private AffineTransform rotate(int degree) {


double rotationAngle=degree*Math.PI/180;

AffineTransform transform = new AffineTransform();

transform.rotate(rotationAngle, xCenter, yCenter);

//transform.rotate(rotationAngle);

transform.translate(xCenter, yCenter);

return transform;

}

/*

* 90 degree only, keep on position top left

*/

private AffineTransform rotate90() {


double rotationAngle=90*Math.PI/180;

AffineTransform transform = new AffineTransform();

transform.rotate(rotationAngle, xCenter, yCenter);

// yCenter-heightImg = horizontal position

// xCenter: vertical position

transform.translate(xCenter, yCenter-heightImg);

return transform;

}

}

Wednesday, August 7, 2024

Eclipse: how to read images from resources

Create resources folder

  1. create "res" folder via "Package Explorer".
  2. right click on "res" folder -> "Build Path" -> "Use as Source Folder". "res" will  be root of your resource.
  3. create "images" folder inside "res" folder. Copy your images into this folder. Path your file becomes "/images/example.jpg".

Accessing images from the "images" folder, use this piece of code into your java source code:

        String cName = "example.jpg";
        String sFName = "/images/"+cName;
        BufferedImage img = ImageIO.read(this.getClass().getResource(sFName));

References:

https://stackoverflow.com/questions/31152233/opening-image-asset-java-jdk-8

Monday, August 5, 2024

windows: disable fast start for multiple OS (dual boot)

Hibernation saves an image of your work and shuts down your computer or put your computer into sleep mode.

Fast Startup only saves an image of the system kernel and loaded drivers to reduce boot time.

Fast Startup may not suitable for System:

  1. multiple os except you never access/share data between multiple os.
  2. maintenance
  3. hardware change

Step to disable fast startup 

  1. Search -> Choose a power plan -> Choose what the power buttons do -> Change settings that are currently unavailable
  2. uncheck "Turn on fast start (recommendation)"
  3. save change and restart

 

Wednesday, July 17, 2024

Debian: using Festival to generate voice from text (Text To Speech/TTS) - AI TTS

folder voice

$ ls /usr/share/festival/voices/english/

Using command interpreter:

$ festival
...
festival> (voice.list)
(kal_diphone)
festival> (SayText "Hello")
#<Utterance 0x7f8747f99ef0>

festival> (quit)

Load text from file output direct to sound

$ festival --tts ./hello.txt 

Load text from file output direct to file

$ text2wave ./hello.txt -o text1.wav

Monday, July 8, 2024

java 17: shuffle 52 playing cards and sort the order base on bridge playing game

This is the code to shuffle 52 playing cards for 4 players and re order each hand cards. I provide to order card base on trump (at right side).

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class Test {
    /*
     * TODO how to repesent card
     */
    public final static String[] S_CLUB = {
        "2C",
        "3C",
        "4C",
        "5C",
        "6C",
        "7C",
        "8C",
        "9C",
        "10C",
        "JC", //JC
        "QC", //QC
        "KC", //KC
        "AC"  //AC
    };

    public final static String[] S_DIAMOND = {
        "2D",
        "3D",
        "4D",
        "5D",
        "6D",
        "7D",
        "8D",
        "9D",
        "10D",
        "JD",
        "QD",
        "KD",
        "AD"
    };
    
    public final static String[] S_HEART = {
        "2H",
        "3H",
        "4H",
        "5H",
        "6H",
        "7H",
        "8H",
        "9H",
        "10H",
        "JH",
        "QH",
        "KH",
        "AH"
    };
    
    public final static String[] S_SPADE = {
        "2S",
        "3S",
        "4S",
        "5S",
        "6S",
        "7S",
        "8S",
        "9S",
        "10S",
        "JS",
        "QS",
        "KS",
        "AS"
    };
    
    public static void main(String[] args) {

        long startTime = System.nanoTime();
        shuffleCard();
        long endTime = System.nanoTime();
        System.out.println("North");
        for (int i=0;i<13;i++) {
            System.out.print(north[i]+" ");
        }
        System.out.println();
        System.out.println("After Sorting");
        ArrayList<String> tmp = sortEnd2Begin(north);
        tmp.forEach((String myCard) ->{
            System.out.print(myCard+" ");
        });
        System.out.println();
        

        System.out.println("EAST");
        for (int i=0;i<13;i++) {
            System.out.print(east[i]+" ");
        }
        System.out.println();
        System.out.println("After Sorting");
        tmp = sortEnd2Begin(east);
        tmp.forEach((String myCard) ->{
            System.out.print(myCard+" ");
        });
        System.out.println();
        
        System.out.println("South");
        for (int i=0;i<13;i++) {
            System.out.print(south[i]+" ");
        }
        System.out.println();
        System.out.println("After Sorting");
        tmp = sortEnd2Begin(south);
        tmp.forEach((String myCard) ->{
            System.out.print(myCard+" ");
        });
        System.out.println();
        
        System.out.println("West");
        for (int i=0;i<13;i++) {
            System.out.print(west[i]+" ");
        }
        System.out.println();
        System.out.println("After Sorting");
        tmp = sortEnd2Begin(west);
        tmp.forEach((String myCard) ->{
            System.out.print(myCard+" ");
        });
        System.out.println();

        System.out.println((endTime-startTime)%1000000+" mili"); // time_ms % 1E+3 + " MicroSeconds, "


    }
    
    static String[] north = new String[13];
    static String[] east = new String[13];
    static String[] south = new String[13];
    static String[] west = new String[13];
    
    private static void shuffleCard() {
        //TODO
        ArrayList<String> cards = new ArrayList<>();
        List<String> listCard = Arrays.asList(S_CLUB);
        cards.addAll(listCard);
        listCard = Arrays.asList(S_DIAMOND);
        cards.addAll(listCard);
        listCard = Arrays.asList(S_HEART);
        cards.addAll(listCard);
        listCard = Arrays.asList(S_SPADE);
        cards.addAll(listCard);
        //System.out.println("card number: "+cards.size()); // debug
        
        cards = shuffle(1,cards);
        
        //System.out.println("Distribution "+cards.size());
        int topPosition = cards.size()-1;
        for (int i=0;i<13;i++) {
            //System.out.println("north "+i+" "+topPosition);  // debug
            String tmp = cards.get(topPosition);
            cards.remove(topPosition);
            topPosition --;
            north[i] = tmp;
            //System.out.println("east "+i+" "+topPosition);  // debug
            tmp = cards.get(topPosition);
            cards.remove(topPosition);
            topPosition --;
            east[i] = tmp;
            //System.out.println("south "+i+" "+topPosition);  // debug
            tmp = cards.get(topPosition);
            cards.remove(topPosition);
            topPosition --;
            south[i] = tmp;
            //System.out.println("west "+i+" "+topPosition);  // debug
            tmp = cards.get(topPosition);
            cards.remove(topPosition);
            topPosition --;
            west[i] = tmp;    
        }
        
        
    }
    
    static Random rand = new Random();
    
    private static ArrayList<String> shuffle(int numSuffle, ArrayList<String> cards) {
        //System.out.println("Suffle: "+numSuffle);  // debug
        Collections.shuffle(cards, rand);
        //System.out.println("Card size "+cards.size()); // debug
        
        if (numSuffle>0) {
            shuffle(numSuffle-1, cards);
        }
        
        return cards;
    }
    
    private static ArrayList<String> sortEnd2Begin(String[] myCards) {
        ArrayList<String> myNewCards = new ArrayList<>();
        myNewCards.add(myCards[0]);
        for (int i=1;i<myCards.length;i++) {
            // loop for unordered myCards
            String card2Sort = myCards[i];
            for (int j=0;j<myNewCards.size();j++) {
                // loop for ordered myNewCards
                // find until card2Sort equal or bigger then existing list
                String cardIterate = myNewCards.get(j);
                //int posCard = beforeOrAfter(card2Sort, cardIterate, 0, iterMax);
                int posCard = beforeOrAfter2(card2Sort, cardIterate);
                if (posCard<=0) {
                    myNewCards.add(j, card2Sort);
                    break;
                } else {
                    //System.out.println(j); // debug
                    if (j+1==myNewCards.size()) {
                        // end of list
                        myNewCards.add(card2Sort);
                        break;
                    }
                }
            }

        }
        return myNewCards;
    }
    
    
    /* -1 wordA before wordB
     * 0 wordA equal wordB
     * 1 wordA after wordB
     * suite order less C D H S higher
     * value suit  less 0 1 2 3 4 5 6 7 8 9 A J K Q
     * map 10 to A
     *      J to B
     *      Q to C
     *      K to D
     *      A to E
     */
    private static int beforeOrAfter2(String wordA, String wordB) {
        //System.out.print("word "+wordA+" "+wordB+" "); // debug
        char charA = wordA.charAt(wordA.length()-1);
        char charB = wordB.charAt(wordB.length()-1);
        //System.out.println(wordA+" "+wordB+" End "+charA+" "+charB+" "); // debug
        if (charA<charB) {
            return -1;
        } else if (charA>charB) {
            return 1;
        } else {
            // equal
            charA = wordA.charAt(wordA.length()-2);
            charB = wordB.charAt(wordB.length()-2);
            // mapping charA to correct order
            if (charA=='0') {
                charA='A';
            } else if (charA=='J') {
                charA='B';
            } else if (charA=='Q') {
                charA='C';
            } else if (charA=='K') {
                charA='D';
            } else if (charA=='A') {
                charA='E';
            }
            // mapping charB to correct order
            if (charB=='0') {
                charB='A';
            } else if (charB=='J') {
                charB='B';
            } else if (charB=='Q') {
                charB='C';
            } else if (charB=='K') {
                charB='D';
            } else if (charB=='A') {
                charB='E';
            }
            
            //System.out.println(" First "+charA+" "+charB); // debug
            if (charA<charB) {
                return -1;
            } else if (charA>charB) {
                return 1;
            }
        }
        
        return 0;
    }

    public static ArrayList<String> sortCardsWithTrump(ArrayList<String> myCards, char trump) {
        ArrayList<String> myNewCards = new ArrayList<>();
        myNewCards.add(myCards.get(0));
        for (int i=1;i<myCards.size();i++) {
            // loop for unordered myCards
            String card2Sort = myCards.get(i);
            for (int j=0;j<myNewCards.size();j++) {
                // loop for ordered myNewCards
                // find until card2Sort equal or bigger then existing list
                String cardIterate = myNewCards.get(j);
                //int posCard = beforeOrAfter(card2Sort, cardIterate, 0, iterMax);
                int posCard = beforeOrAfter2Trump(card2Sort, cardIterate, trump);
                if (posCard<=0) {
                    myNewCards.add(j, card2Sort);
                    break;
                } else {
                    //System.out.println(j); // debug
                    if (j+1==myNewCards.size()) {
                        // end of list
                        myNewCards.add(card2Sort);
                        break;
                    }
                }
            }

        }
        return myNewCards;
    }
    
    /* -1 wordA before wordB
     * 0 wordA equal wordB
     * 1 wordA after wordB
     * NO TRUMP CDHS
     * TRUMP Map to Z for trump
     * suite order less C D H S higher
     * value suit  less 0 1 2 3 4 5 6 7 8 9 A J K Q
     * map 10 to A
     *      J to B
     *      Q to C
     *      K to D
     *      A to E
     */
    private static int beforeOrAfter2Trump(String wordA, String wordB, char trump) {
        //System.out.print("word "+wordA+" "+wordB+" "); // debug
        char charA = wordA.charAt(wordA.length()-1);
        char charB = wordB.charAt(wordB.length()-1);
        //System.out.println(wordA+" "+wordB+" End "+charA+" "+charB+" "); // debug
        // remap char for TRUMP
        // mapping charA to correct order
        if (charA==trump) {
            charA='Z';
        }
        // mapping charB to correct order
        if (charB==trump) {
            charB='Z';
        }
        if (charA<charB) {
            return -1;
        } else if (charA>charB) {
            return 1;
        } else {
            // equal
            charA = wordA.charAt(wordA.length()-2);
            charB = wordB.charAt(wordB.length()-2);
            // mapping charA to correct order
            if (charA=='0') {
                charA='A';
            } else if (charA=='J') {
                charA='B';
            } else if (charA=='Q') {
                charA='C';
            } else if (charA=='K') {
                charA='D';
            } else if (charA=='A') {
                charA='E';
            }
            // mapping charB to correct order
            if (charB=='0') {
                charB='A';
            } else if (charB=='J') {
                charB='B';
            } else if (charB=='Q') {
                charB='C';
            } else if (charB=='K') {
                charB='D';
            } else if (charB=='A') {
                charB='E';
            }
           
            //System.out.println(" First "+charA+" "+charB); // debug
            if (charA<charB) {
                return -1;
            } else if (charA>charB) {
                return 1;
            }
        }
        return 0;
    }

}