SourcePost__


このページのコンテンツ一覧(5個位までにしてください。上が最新で下が最古です)

宿題スレPart54 >>860 への回答 行列の累乗

以前作った http://www.wikiroom.com/java/index.php?SourcePost_#kf3e8c5e に気持ち悪いところがあったので修正を加えて、さらに累乗の機能を追加しました。

   // PowerMatrixDemo.java
   public class PowerMatrixDemo {
   
       public static void main(String[] args) {
           double[][] matrix = {
              {0.6, 4.0},
              {0.7, 0.3},
           };
   
           double[][] answer = MultiplyMatrix.power( matrix, 2 );
           MultiplyMatrix.printMatrix( answer );
       }
   }
  // MultiplyMatrix.java
  public class MultiplyMatrix {
      /**
       * 行列の出力
       * @param matrix 行列
       */
      public static void printMatrix( double[][] matrix ) {
          // 出力
          int ROWS = matrix.length;
          int COLS = matrix[0].length;
          for( int i=0; i<ROWS; i++ ) {
              System.out.print("[ ");
              for( int j=0; j<COLS; j++ ) {
                  System.out.printf( "%8.3f\t", matrix[i][j]  );
              }
              System.out.println("]");
          }
      }
      
      /**
       * 行列のかけ算
       * @param matrix1 かけられる行列
       * @param matrix2 かける行列
       * @param 答えの行列
       */
      public static double[][] multiply( double[][] matrix1, double[][] matrix2 ) {
          // 答えの行列の確保
          int ROWS = matrix1.length;
          int COLS = matrix2[0].length;
          double[][] answer = new double[ROWS][COLS];
          // 計算
          for( int i=0; i<ROWS; i++ ) {
              for( int j=0; j<COLS; j++ ) {
                  double sum = 0;
                  for( int k=0; k<matrix1[0].length; k++ ) {
                      sum += matrix1[i][k] * matrix2[k][j];
                  }
                  answer[i][j] = sum;
              }
          }
          return answer;
      }
      
      /**
       * 行列の累乗
       * @param matrix 累乗する行列
       * @param powerOf 累乗回数
       * @return 答えの行列
       */
      public static double[][] power( double[][] matrix, int powerOf ) {
          // 行列の累乗のときは与えられる行列は必ず正方行列。
          if( matrix.length != matrix[0].length ) throw new IllegalArgumentException( "正方行列ではないので累乗計算はできません。" );
          double[][] answer = matrix;
          for( int i=2; i<=powerOf; i++ ) {
              answer = multiply( answer, matrix );
          }
          return answer;
      }
  }

宿題スレPart54 >>765 課題2 への回答 石取りゲーム

こーゆーの英語でなんて言うのかわからんので、クラス名は適当です。

   // Demo.java
   import java.io.BufferedReader;
   import java.io.IOException;
   import java.io.InputStreamReader;
   
   public class Demo {
   
       private int number;
       
       public static void main(String[] args) {
           Demo self = new Demo();
           self.start();
           self.process();
       }
       
       private void start() {
           System.out.println( "COM:「ゲームを始めます。」" );
           // 石の数は10〜19の範囲にした。
           number = 10 + (int)(Math.random() * 9);
           System.out.println( "COM:「石は全部で" + number + "個あります。」" );
           switch( number%3 ) {
               case 0: {
                   System.out.println( "COM:「お先にどうぞ。」" );
                   break;
               }
               case 1: {
                   System.out.println( "COM:「でわ私から。1個とります。」" );
                   number -= 1;
                   System.out.println( "COM:「石は今" + number + "個あります。」" );
                   break;
               }
               case 2: {
                   System.out.println( "COM:「でわ私から。2個とります。」" );
                   number -= 2;
                   System.out.println( "COM:「石は今" + number + "個あります。」" );
                   break;
               }
               default: {
                   throw new IllegalArgumentException();
               }
           }
       }
       
       private void process() {
           while( number > 0 ) {
               int input = inputKey();
               number -= input;
               // ありえない。
               if( number == 0 ) {
                   winPlayer();
                   break;
               }
               System.out.println( "COM:「石は" + number + "個になりました。」" );
               System.out.println( "COM:「私は" + (3-input) + "個取ります。」" );
               number -= (3-input);
               if( number == 0 ) {
                   winComputer();
                   break;
               }
               System.out.println( "COM:「石は" + number + "個になりました。」" );
           }
       }
       
       private int inputKey() {
           System.out.println( "COM:「何個とりますか?」" );
           System.out.print( "> " );
           BufferedReader br = new BufferedReader( new InputStreamReader(System.in) );
           int input = 0;
           while( input != 1 && input != 2 ) {
               try {
                   input = Integer.parseInt( br.readLine() );
                   if( input != 1 && input != 2 ) {
                       throw new NumberFormatException();
                   }                
               } catch( IOException ioe ) {
                   ioe.printStackTrace();
               } catch( NumberFormatException nfe ) {
                   System.out.println( "COM:「1か2の数字を入れてください。」" );
                   System.out.print( "> " );
               }
           }
           return input;        
       }
   
       private void winPlayer()   { System.out.println( "\nCOM:「あなたの勝ちです。おめでとう!!」" ); }
       private void winComputer() { System.out.println( "\nCOM:「私の勝ちです。残念!!」" ); }
   }

宿題スレPart54 >>765 課題1 への回答 身長管理

   // HeightDemo.java
   import java.io.BufferedReader;
   import java.io.IOException;
   import java.io.InputStreamReader;
   import java.util.HashMap;
   import java.util.StringTokenizer;
   
   public class HeightDemo {
   
       private HashMap heightMap;
       private static final String KEY_UNDER_150       = "    - 149";
       private static final String KEY_FROM_150_TO_159 = "150 - 159";
       private static final String KEY_FROM_160_TO_169 = "160 - 169";
       private static final String KEY_FROM_170_TO_179 = "170 - 179";
       private static final String KEY_OVER_180        = "180 -    ";
       
       public HeightDemo() {
           this.heightMap = new HashMap();
       }
       
       public static void main(String[] args) {
           HeightDemo self = new HeightDemo();
           self.input();
           self.output();
       }
       
       private void input() {
           BufferedReader br = new BufferedReader( new InputStreamReader(System.in) );
           try {
               for( String line; (line=br.readLine()) != null;  ) {
                   StringTokenizer tokenizer = new StringTokenizer( line, " " );
                   int number = Integer.parseInt( tokenizer.nextToken() );
                   if( number == 0 ) return;
                   int height = Integer.parseInt( tokenizer.nextToken() );
                   put( height );
               }
           } catch( IOException ioe ) {
               ioe.printStackTrace();
           }
       }
       
       private void output() {
           System.out.println( KEY_UNDER_150 + " " + get(KEY_UNDER_150) );
           System.out.println( KEY_FROM_150_TO_159 + " " + get(KEY_FROM_150_TO_159) );
           System.out.println( KEY_FROM_160_TO_169 + " " + get(KEY_FROM_160_TO_169) );
           System.out.println( KEY_FROM_170_TO_179 + " " + get(KEY_FROM_170_TO_179) );
           System.out.println( KEY_OVER_180 + " " + get(KEY_OVER_180) );
       }
       
       private void put( int height ) {
           String key;
           if( height < 150 ) {
               key = KEY_UNDER_150;
           } else if( height < 160 ) {
               key = KEY_FROM_150_TO_159;
           } else if( height < 170 ) {
               key = KEY_FROM_160_TO_169;
           } else if( height < 180 ) {
               key = KEY_FROM_170_TO_179;
           } else {
               key = KEY_OVER_180;
           }
           Integer valueInteger = (Integer)heightMap.get( key );
           int value;
           if( valueInteger == null ) value = 0;
           else value = valueInteger.intValue();
           heightMap.put( key, new Integer(++value) );
       }
       
       private int get( String key ) {
           Integer valueInteger = (Integer)heightMap.get( key );
           if( valueInteger == null ) return 0;
           else return valueInteger.intValue();
       }
   }

宿題スレPart54 >>622 への回答 証券取引

   // TradeDemo.java
   import java.io.BufferedReader;
   import java.io.BufferedWriter;
   import java.io.File;
   import java.io.FileNotFoundException;
   import java.io.FileReader;
   import java.io.FileWriter;
   import java.io.IOException;
   import java.io.InputStreamReader;
   import java.text.SimpleDateFormat;
   import java.util.ArrayList;
   import java.util.Date;
   import java.util.StringTokenizer;
   
   public class TradeDemo {
   
       private ArrayList<Customer> customerList = new ArrayList<Customer>();
       private Customer customer;
       private boolean isOldCustomer;
       
       private SimpleDateFormat formatter = new SimpleDateFormat( "[yyyy/MM/dd HH:mm:ss:SSS]" );
       
       public static final File CUSTOMER_DB_FILE = new File( "CUSTOMER_DB" );
       public static final File TRADE_LOG_FILE = new File( "TRADE_LOG" );
   
       public static void main(String[] args) {
           TradeDemo self = new TradeDemo();
           self.readDB();
           self.getUserInfo();
           self.trade();
       }
       
       private void readDB() {
           BufferedReader br3 = null;
           try {
               br3 = new BufferedReader( new FileReader(TradeDemo.CUSTOMER_DB_FILE) );            
           } catch( FileNotFoundException fnfe ) {
               try {
                   if( TradeDemo.CUSTOMER_DB_FILE.createNewFile() ) {
                       System.out.println( "DBファイルがなかったので作成しました。" );
                       br3 = new BufferedReader( new FileReader(TradeDemo.CUSTOMER_DB_FILE) );            
                   } else {
                       System.out.println( "DBファイルがなかったので作成しようとしましたが失敗しました。" );
                       System.exit(1);
                   }
               } catch( IOException ioe ) {
                   ioe.printStackTrace();
                   System.exit(1);
               }
           }
           try {
               for( String line; (line=br3.readLine()) != null;  ) {
                   StringTokenizer tokenizer = new StringTokenizer(line, ",");
                   String dbUserID = tokenizer.nextToken();
                   String dbPassword = tokenizer.nextToken();
                   long dbMoney = Long.parseLong( tokenizer.nextToken() );
                   customerList.add( new Customer( dbUserID, dbPassword, dbMoney ) );
               }
           } catch( IOException ioe ) {
               ioe.printStackTrace();
           } finally {
               try {
                   if( br3 != null ) br3.close();
               } catch( IOException ioe ) {}
           }
       }
       
       private void getUserInfo() {
           try {
               label: while( true ) {
                   System.out.println( "ユーザーIDとパスワードを入力してください。" );
                   BufferedReader br1 = new BufferedReader( new InputStreamReader(System.in) );
                   String userID = "";
                   while( userID.length() <= 0 ) {
                       System.out.print( "ユーザーID > " );
                       userID = br1.readLine();
                   }
                   BufferedReader br2 = new BufferedReader( new InputStreamReader(System.in) );
                   String password = "";
                   while( password.length() <= 0 ) {
                       System.out.print( "パスワード > " );
                       password = br2.readLine();
                   }
                   for( Customer customer : customerList ) {
                       if( userID.equals(customer.getUserID()) && !password.equals(customer.getPassword()) ) {
                           System.out.println( "パスワードが不正、またはすでに使用されているユーザーIDです。" );
                           continue label;
                       } else if( userID.equals(customer.getUserID()) && password.equals(customer.getPassword()) ) {
                           this.customer = new Customer( userID, password, customer.getMoney() );
                           isOldCustomer = true;
                           break label;
                       }
                   }
                   if( !this.isOldCustomer ) {
                       System.out.println( userID + "さんは新規顧客です。" );
                       this.customer = new Customer( userID, password );
                   }
                   break label;
               }
           } catch( IOException ioe ) {
               ioe.printStackTrace();
           }
           
       }
       
       private void trade() {
           try {
               System.out.println( "\n" + "取り引きを始めます。" );
               writeLog( "[USERID:" + this.customer.getUserID() + "] [取り引き開始] 余力 > " + this.customer.getMoney() + "円" );
               label: do {
                   try {
                       System.out.println( "余力 > " + this.customer.getMoney() + "円" );
                       BufferedReader br4 = new BufferedReader( new InputStreamReader(System.in) );
                       char command = '\u0000';
                       while( true ) {
                           System.out.println( "s:売り、b:買い、e:終了のいずれかのコマンドを入力してください。" );
                           try {
                               command = br4.readLine().charAt(0);
                               break;
                           } catch( StringIndexOutOfBoundsException sioobe ) {}
                       }
                       switch( command ) {
                           case 's': {
                               System.out.print( "いくら売りますか > " );
                               BufferedReader br5 = new BufferedReader( new InputStreamReader(System.in) );
                               long sell = Long.parseLong( br5.readLine() );
                               this.customer.addMoney(sell);
                               writeLog( "[USERID:" + this.customer.getUserID() + "] [売り] 売額 > " + sell + "円," +
                                         " 余力 > " + this.customer.getMoney() + "円" );
                               System.out.println( sell + "円売りました。" );
                               break;
                           }
                           case 'b': {
                               System.out.print( "いくら買いますか > " );
                               BufferedReader br6 = new BufferedReader( new InputStreamReader(System.in) );
                               long buy = Long.parseLong( br6.readLine() );
                               this.customer.minusMoney(buy);
                               writeLog( "[USERID:" + this.customer.getUserID() + "] [買い] 買額 > " + buy + "円," +
                                         " 余力 > " + this.customer.getMoney() + "円" );
                               System.out.println( buy + "円買いました。" );
                               break;
                           }
                           case 'e': {
                               writeDB();
                               break label;
                           }
                           default: {
                               System.out.println( "不正なコマンドです。" );
                               break;
                           }
                       }
                   } catch( NumberFormatException nfe ) {
                       System.out.println( nfe );
                   }
               } while(true);
               } catch( IOException ioe ) {
               ioe.printStackTrace();
           }
       }
       
       private void writeDB() {
           BufferedWriter bw = null;
           FileWriter fw = null;
           try {
               fw = new FileWriter( TradeDemo.CUSTOMER_DB_FILE );
               bw = new BufferedWriter( fw );
               bw.append( this.customer.getUserID() + "," + this.customer.getPassword() + "," + this.customer.getMoney() + "\n" );
               bw.flush();
               for( Customer customer : customerList ) {
                   if( this.customer.getUserID().equals(customer.getUserID()) && this.customer.getPassword().equals(customer.getPassword()) ) {
                       continue;
                   }
                   bw.append( customer.getUserID() + "," + customer.getPassword() + "," + customer.getMoney() + "\n" );
                   bw.flush();
               }
               System.out.println( "終了します..." );
           } catch( IOException ioe ) {
               ioe.printStackTrace();
           } finally {
               try {
                   if( bw != null ) bw.close();
                   if( fw != null ) fw.close();
               } catch( IOException ioe ){
                   ioe.printStackTrace();
               }
           }
       }
       
       private void writeLog( String message ) {
           BufferedWriter bw = null;
           FileWriter fw = null;
           try {
               fw = new FileWriter( TradeDemo.TRADE_LOG_FILE, true );
               bw = new BufferedWriter( fw );
               bw.append(  formatter.format( new Date() ) + " " + message + "\n" );
               bw.flush();
           } catch( IOException ioe ) {
               ioe.printStackTrace();
           } finally {
               try {
                   if( bw != null ) bw.close();
                   if( fw != null ) fw.close();
               } catch( IOException ioe ) {
                   ioe.printStackTrace();
               }
           }
       }
   
   }
   // Customer.java
   public final class Customer {
       private String userID;
       private String password;
       private long money;
       
       public Customer( String userID, String password, long money ) {
           this.userID = userID;
           this.password = password;
           this.money = money;
       }
       
       public Customer( String userID, String password ) {
           this( userID, password, 1000000 );
       }
       
       public long getMoney() {
           return money;
       }
       public void addMoney(long money) {
           if( money <= 0 ) throw new NumberFormatException( "入力値が不正です。" );
           else this.money += money;
       }
       public void minusMoney(long money) throws NumberFormatException {
           if( money <= 0 ) throw new NumberFormatException( "入力値が不正です。" );
           else if( this.money < money ) throw new NumberFormatException( "余力がありません。" );
           else this.money -= money;
       }
       public String getPassword() {
           return password;
       }
       public String getUserID() {
           return userID;
       }
   }

宿題スレPart53 >>903 への回答 ドラクエ的ポーカー

完成度は低いです。ヤル気なくなった感あり。

   // DQPoker.java
   import javax.swing.WindowConstants;
   
   public class DQPoker {
       public static void main(String[] args) {
           Player player = new Player("ギコ", 100);
           DQPokerFrame frame = new DQPokerFrame(player);
           frame.setTitle("DQ Poker");
           frame.setSize(Constants.WINDOW_WIDTH, Constants.WINDOW_HEIGHT);
           frame.setResizable(false);
           frame.setVisible(true);
           frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
       }
   }
   // DQPokerFrame.java
   import java.awt.BorderLayout;
   import java.awt.Color;
   import java.awt.Font;
   import java.awt.GridLayout;
   import java.awt.event.ActionEvent;
   import java.awt.event.ActionListener;
   import java.awt.event.MouseEvent;
   import java.awt.event.MouseListener;
   import java.io.File;
   import java.io.IOException;
   import java.text.DecimalFormat;
   import java.text.NumberFormat;
   import java.util.Collections;
   import java.util.Vector;
   
   import javax.imageio.ImageIO;
   import javax.imageio.stream.FileImageInputStream;
   import javax.swing.JButton;
   import javax.swing.JFormattedTextField;
   import javax.swing.JFrame;
   import javax.swing.JLabel;
   import javax.swing.JOptionPane;
   import javax.swing.JPanel;
   import javax.swing.JSpinner;
   import javax.swing.JTextArea;
   import javax.swing.SpinnerNumberModel;
   import javax.swing.event.ChangeEvent;
   import javax.swing.event.ChangeListener;
   
   public class DQPokerFrame extends JFrame implements ActionListener, MouseListener, ChangeListener {
       Player player;
       JPanel panel = new JPanel( new BorderLayout() );
       JPanel northPanel = new JPanel();
       JLabel playerMoney = new JLabel();
       JSpinner spinner;
       JFormattedTextField tf;
       JTextArea order = new JTextArea();
       JButton startButton = new JButton("スタート");
       JPanel centerPanel = new JPanel( new GridLayout( 1, 5 ) );
       JPanel southPanel = new JPanel( new GridLayout(3, 1) );
       JLabel message1 = new JLabel();
       JLabel message2 = new JLabel();
       JButton changeButton = new JButton( "交換" );
       JButton exitButton = new JButton( "終了" );
       Vector<Integer> cardTower;
       CardPanel[] cardPanels = new CardPanel[5];
       Card[] cards;
       Vector<Integer> changeList;
       
       public DQPokerFrame( Player player ) {
           this.player = player;
           SpinnerNumberModel model = new SpinnerNumberModel(10, 1, player.getMoney(), 1);
           spinner = new JSpinner(model);
           tf = ((JSpinner.NumberEditor)spinner.getEditor()).getTextField();
           tf.setEditable(true);
           setOrder( (Integer)spinner.getValue() );
           spinner.addChangeListener(this);
           northPanel.add( spinner );
           playerMoney.setText( "" + (player.getMoney()-Integer.parseInt(tf.getText())) );
           northPanel.add( playerMoney );
           northPanel.add( startButton );
           order.setEditable(false);
           northPanel.add( order );
           startButton.addActionListener(this);
   
           message1.setFont( new Font("Dialog", Font.BOLD, 14) );
           message2.setFont( new Font("Dialog", Font.PLAIN, 12) );
           southPanel.add( message1 );
           southPanel.add( message2 );
           changeButton.addActionListener( this );
           changeButton.setEnabled( false );
           JPanel p1 = new JPanel(), p2 = new JPanel(), p3 = new JPanel();
           p1.add(message1);
           p2.add(message2);
           p3.add(changeButton);
           exitButton.addActionListener(this);
           p3.add(exitButton);
           southPanel.add( p1 );
           southPanel.add( p2 );
           southPanel.add( p3 );
           
           panel.add( northPanel, BorderLayout.NORTH );
           panel.add( centerPanel, BorderLayout.CENTER );
           panel.add( southPanel, BorderLayout.SOUTH );
           getContentPane().add( panel );
           
           reset();
       }
       
       private void reset() {
           changeList = new Vector<Integer>();
           cardTower = new Vector<Integer>();
           centerPanel.removeAll();
       }
       
       /**
        * カードを配る
        *
        */
       private void dealCards() { 
           try {
               for( int i=0; i<52; i++ ) cardTower.add( i );
               Collections.shuffle( cardTower );
               cards = new Card[5];
               for( int i=0 ;i<5; i++ ) {
                   int position = cardTower.remove(0);
                   char mark = getMarkChar(position);
                   String number = getNumber(position);
                   String fileName = mark + number + ".bmp";
                   cards[i] = new Card(fileName);
                   cardPanels[i] = new CardPanel();
                   cardPanels[i].addMouseListener(this);
                   cardPanels[i].setImage( ImageIO.read( new FileImageInputStream(new File(Constants.IMAGE_DIRECTORY + fileName)) ) );
                   centerPanel.add( cardPanels[i] );
               }
               message1.setText( DQPokerRule.getHand( cards ).getHandName() );
               message1.setForeground( Color.CYAN );
               message2.setText( "交換するカードを選んで交換ボタンを押してください。" );
               changeButton.setEnabled( true );
               centerPanel.repaint();
           } catch( IOException ioe ) {
               ioe.printStackTrace();
           }
       }
       
       private char getMarkChar(int position) {
           int mark_num = position / 13;
           switch( mark_num ) {
               case 0: return 'c';
               case 1: return 'd';
               case 2: return 'h';
               case 3: return 's';
               default: throw new IllegalArgumentException();
           }
       }
       
       private String getNumber(int position) {
           NumberFormat formatter = new DecimalFormat("00");
           return formatter.format( position%13+2 );
       }
   
       public void actionPerformed(ActionEvent ae) {
           if( ae.getSource() == startButton ) {
               reset();
               dealCards();
               startButton.setEnabled(false);
               spinner.setEnabled(false);
               
           } else if( ae.getSource() == changeButton ) {
               try {                
                   for( int i : changeList ) {        
                       centerPanel.remove( cardPanels[i] );
                       int position = cardTower.remove(0);
                       char mark = getMarkChar(position);
                       String number = getNumber(position);
                       String fileName = mark + number + ".bmp";
                       cards[i] = new Card(fileName);
                       cardPanels[i] = new CardPanel();
                       cardPanels[i].addMouseListener(this);
                       cardPanels[i].setImage( ImageIO.read( new FileImageInputStream(new File(Constants.IMAGE_DIRECTORY + fileName)) ) );
                       centerPanel.add( cardPanels[i], i );
                   }
                   centerPanel.repaint();
                   for( int i=0; i<5; i++ ) cardPanels[i].removeMouseListener(this);
                   DQPokerHand hand = DQPokerRule.getHand( cards );
                   message1.setText( hand.getHandName() );
                   player.setMoney( Integer.parseInt(playerMoney.getText()) + ((Integer)spinner.getValue()*hand.getMagnification()) );
                   
                   message1.setForeground( Color.BLUE );
                   changeButton.setEnabled(false);                
                   
                   if( player.getMoney() <= 0 ) {
                       message2.setText( "所持金がなくなりました..." );
                       JOptionPane.showMessageDialog( this, "  _, ._\n( ゚ Д゚)<所持金がなくなりました...", null, JOptionPane.ERROR_MESSAGE, null );
                       startButton.setEnabled(false);
                       spinner.setEnabled(false);
                   } else {
                       message2.setText( "続ける場合はスタートボタンを押してください。" );
                       startButton.setEnabled(true);
                       spinner.setEnabled(true);
                       for( int i=(Integer)spinner.getValue(); ;  ){
                           try {
                               spinner.setModel( new SpinnerNumberModel(i, 1, player.getMoney(), 1) );
                               playerMoney.setText( "" + (player.getMoney() - (Integer)spinner.getValue()) );
                               break;
                           } catch( IllegalArgumentException iae ) {
                               i--;
                           }
                       }
                   }
               } catch( IOException ioe ) {
                   ioe.printStackTrace();
               }
           } else if( ae.getSource() == exitButton ) {
               System.exit(0);
           }
       }
       
       public void mouseClicked(MouseEvent e) {
           if( e.getSource() instanceof CardPanel ) {
               CardPanel clickedPanel = (CardPanel)e.getSource();
               int x = 0;
               for( x=0; x<cardPanels.length; x++ ) {
                   if( clickedPanel == cardPanels[x] ) break;
               }
               try {
                   changeList.add( x );
                   cardPanels[x].setImage( ImageIO.read( new FileImageInputStream(new File(Constants.IMAGE_DIRECTORY + Constants.BACK_FILE_NAME)) ) );
                   panel.paintImmediately( 0, 0, panel.getWidth(), panel.getHeight() );
               } catch( IOException ioe ) {
                   ioe.printStackTrace();
               }
           }
       }
   
       public void mousePressed(MouseEvent e) {}
       public void mouseReleased(MouseEvent e) {}
       public void mouseEntered(MouseEvent e) {}
       public void mouseExited(MouseEvent e) {}
   
       public void stateChanged(ChangeEvent e) {
           JSpinner sp = (JSpinner)e.getSource();
           playerMoney.setText( "" + (player.getMoney()-(Integer)sp.getValue()) );
           setOrder( (Integer)sp.getValue() );
       }
       
       private void setOrder( int bet ) {
           order.setText( 
                   Constants.HANDS_ROYAL_STRAIGHT_FLUSH.getHandName() + ":" + bet + "x" + Constants.HANDS_ROYAL_STRAIGHT_FLUSH.getMagnification() + "=" + bet*Constants.HANDS_ROYAL_STRAIGHT_FLUSH.getMagnification() + "\n" +
                   Constants.HANDS_STRAIGHT_FLUSH.getHandName() + ":" + bet + "x" + Constants.HANDS_STRAIGHT_FLUSH.getMagnification() + "=" + bet*Constants.HANDS_STRAIGHT_FLUSH.getMagnification() + "\n" +
                   Constants.HANDS_FOUR_CARDS.getHandName() + ":" + bet + "x" + Constants.HANDS_FOUR_CARDS.getMagnification() + "=" + bet*Constants.HANDS_FOUR_CARDS.getMagnification() + "\n" +
                   Constants.HANDS_FULL_HOUSE.getHandName() + ":" + bet + "x" + Constants.HANDS_FULL_HOUSE.getMagnification() + "=" + bet*Constants.HANDS_FULL_HOUSE.getMagnification() + "\n" +
                   Constants.HANDS_FLUSH.getHandName() + ":" + bet + "x" + Constants.HANDS_FLUSH.getMagnification() + "=" + bet*Constants.HANDS_FLUSH.getMagnification() + "\n" +
                   Constants.HANDS_STRAIGHT.getHandName() + ":" + bet + "x" + Constants.HANDS_STRAIGHT.getMagnification() + "=" + bet*Constants.HANDS_STRAIGHT.getMagnification() + "\n" +
                   Constants.HANDS_THREE_CARDS.getHandName() + ":" + bet + "x" + Constants.HANDS_THREE_CARDS.getMagnification() + "=" + bet*Constants.HANDS_THREE_CARDS.getMagnification() + "\n" +
                   Constants.HANDS_TWO_PAIRS.getHandName() + ":" + bet + "x" + Constants.HANDS_TWO_PAIRS.getMagnification() + "=" + bet*Constants.HANDS_TWO_PAIRS.getMagnification() + "\n" +
                   Constants.HANDS_ONE_PAIR.getHandName() + ":" + bet + "x" + Constants.HANDS_ONE_PAIR.getMagnification() + "=" + bet*Constants.HANDS_ONE_PAIR.getMagnification() + "\n" +
                   Constants.HANDS_NO_PAIRS.getHandName() + ":" + bet + "x" + Constants.HANDS_ONE_PAIR.getMagnification() + "=" + bet*Constants.HANDS_NO_PAIRS.getMagnification()
                   );
       }
   
   }
   // DQPokerRule.java
   import java.util.Arrays;
   import java.util.TreeMap;
   
   public final class DQPokerRule {
       private DQPokerRule() {        
       }
       
       /**
        * 役を返却。
        * @param cards
        * @return 役
        * @see ttp://slime4.hp.infoseek.co.jp/poker/page2.html
        */
       public static DQPokerHand getHand( Card[] cards ) {
           // TreeMap:マップがキーの昇順でソートされる。
           TreeMap<Character, Integer> markMap = new TreeMap<Character, Integer>();        
           TreeMap<Integer, Integer> numberMap = new TreeMap<Integer, Integer>();
           for( int i=0; i<cards.length; i++ ) {
               markMap.put( cards[i].getMark(), getMarkValue(markMap, cards[i].getMark())+1 );
               numberMap.put( cards[i].getNumber(), getNumberValue(numberMap, cards[i].getNumber())+1 );
           }
           // フラッシュかどうか
           boolean isFlush = false;
           for( char c : markMap.keySet() ) {
               if( markMap.get(c) == 5 ) isFlush = true;
           }
           // ストレートかどうか
           boolean isStraight = false;
           for( int num : numberMap.keySet() ) {
               int count=0;
               for( int i=num; i<num+5; i++ ) {
                   if( getNumberValue(numberMap, i) == 1 ) count++;
               }
               if( count == 5 ) isStraight = true;
           }
           // フラッシュorストレートの場合
           if( isFlush || isStraight ) {
               // ストレートフラッシュ
               if( isFlush && isStraight ) {
                   // Aがある場合はロイヤルストレートフラッシュ
                   if( getNumberValue( numberMap, 14 ) == 1 ) return Constants.HANDS_ROYAL_STRAIGHT_FLUSH;
                   else return Constants.HANDS_STRAIGHT_FLUSH;
               } else if( isFlush ) {
                   return Constants.HANDS_FLUSH;
               } else if( isStraight ) {
                   return Constants.HANDS_STRAIGHT;
               } else {
                   throw new IllegalArgumentException("ありえません..");
               }
           // フラッシュでもストレートでもない場合
           } else {
               Integer[] values = numberMap.values().toArray( new Integer[0] );
               Arrays.sort( values );
               // フォーカード
               if( values[values.length-1] == 4 ) return Constants.HANDS_FOUR_CARDS;
               // スリーカードがある場合
               else if( values[values.length-1] == 3 ) {
                   // ワンペアもある場合
                   if( values[values.length-2] == 2 ) {
                       return Constants.HANDS_FULL_HOUSE;
                   // ワンペアがない場合
                   } else {
                       return Constants.HANDS_THREE_CARDS;
                   }
               // ワンペアがある場合
               } else if( values[values.length-1] == 2 ) {
                   // もうひとつワンペアがある場合
                   if( values[values.length-2] == 2 ) {
                       return Constants.HANDS_TWO_PAIRS;
                   } else {
                       return Constants.HANDS_ONE_PAIR;
                   }
               } else if( values[values.length-1] == 1 ) {
                   
                   return Constants.HANDS_NO_PAIRS;                
               } else {
                   throw new IllegalArgumentException("ありえません..");
               }
           }        
       }
       
       private static int getMarkValue( TreeMap<Character, Integer> markMap, char mark ) {
           Integer value = markMap.get( mark );
           if( value == null ) return 0;
           else return value;
       }
       
       private static int getNumberValue( TreeMap<Integer, Integer> numberMap, int num ) {
           Integer value = numberMap.get( num );
           if( value == null ) return 0;
           else return value;
       }
   }
   // DQPokerHand.java
   public class DQPokerHand {
       private String handName;
       private int magnification;
       
       public DQPokerHand( String handName, int magnification ) {
           this.handName = handName;
           this.magnification = magnification;
       }
       
       public String getHandName() {
           return this.handName;
       }
       
       public int getMagnification() {
           return this.magnification;
       }
   }
   // Player.java
   public class Player {
       private final String name;
       private int money;
   
       public Player(String name, int money) {
           this.name = name;
           this.money = money;
       }
       public int getMoney() {
           return money;
       }
       public void setMoney(int money) {
           this.money = money;
       }
       public String getName() {
           return name;
       }
   }
   // Card.java
   import java.text.DecimalFormat;
   import java.text.NumberFormat;
   
   public class Card {
       /**
        * 'c':クラブ
        * 'd':ダイヤ
        * 'h':ハート
        * 's':スペード
        */
       private char mark;
       /**
        * 数字は2〜14
        */
       private int number;
       private String fileName;
       
       public Card(char mark, int number) {
           this.mark = mark;
           this.number = number;
       }
       public Card(String fileName) {
           this.fileName = fileName;
           if( !fileName.equals(Constants.BACK_FILE_NAME) ) {
   	        this.mark = fileName.charAt(0);	
   	        this.number = Integer.parseInt(fileName.substring( 1, fileName.indexOf(".") ));
           }
       }
       public char getMark() {
           return mark;
       }
       public int getNumber() {
           return number;
       }
       public String getFileName() {
           return fileName;
       }
       public String getFileName(String str) {
           NumberFormat formatter = new DecimalFormat("00");
           return mark + formatter.format( number ) + ".gif";
       }
       public String toString() {
           return "mark: " + mark + ", number: " + number + ", fileName:" + fileName; 
       }
   }
   // CardPanel.java
   import java.awt.Graphics;
   import java.awt.image.BufferedImage;
   
   import javax.swing.JPanel;
   
   public class CardPanel extends JPanel {
       private BufferedImage img=null;
       public void paint(Graphics g){
           if(img != null){
               g.drawImage(img,0,0,this);
           }
       }
       public void setImage(BufferedImage img){
           this.img = img;
       }
       public BufferedImage getImage() {
           return this.img;
       }
   }
   // Constants.java
   public final class Constants {
       public static final int WINDOW_WIDTH = 640;
       public static final int WINDOW_HEIGHT = 480;
       public static final String IMAGE_DIRECTORY = "./img/";
       public static final String BACK_FILE_NAME = "back.bmp";
       
       public static final DQPokerHand HANDS_ROYAL_STRAIGHT_FLUSH = new DQPokerHand( "ロイヤルストレートフラッシュ", 100 );
       public static final DQPokerHand HANDS_STRAIGHT_FLUSH =  new DQPokerHand( "ストレートフラッシュ", 50 );
       public static final DQPokerHand HANDS_FOUR_CARDS = new DQPokerHand( "フォーカード", 30 );
       public static final DQPokerHand HANDS_FULL_HOUSE = new DQPokerHand( "フルハウス", 15 );
       public static final DQPokerHand HANDS_FLUSH = new DQPokerHand( "フラッシュ", 12 );
       
       public static final DQPokerHand HANDS_STRAIGHT = new DQPokerHand( "ストレート", 8 );
       public static final DQPokerHand HANDS_THREE_CARDS = new DQPokerHand( "スリーカード", 3 );
       public static final DQPokerHand HANDS_TWO_PAIRS = new DQPokerHand( "ツーペア", 2 );
       public static final DQPokerHand HANDS_ONE_PAIR = new DQPokerHand( "ワンペア", 0 );
       public static final DQPokerHand HANDS_NO_PAIRS = new DQPokerHand( "ノーペア", 0 );
   }
written by iys

CONTENTS

最新の20件

2020-11-14 2005-12-06 2006-11-04 2012-07-15 2009-06-19 2011-03-03 2006-12-13 2007-11-05 2014-07-22 2014-07-19 2014-07-09 2014-01-14 2012-09-03 2012-03-28

今日の12件

人気の30件

  • counter: 7621
  • today: 1
  • yesterday: 2
  • online: 1