このページのコンテンツ一覧(5個位までにしてください。上が最新で下が最古です)
// RockPaperScissors.java package main; public class RockPaperScissors { public static void main(String[] args) { RockPaperScissorsGame.getInstance().play(); } }
// RockPaperScissorsGame.java package main; import strategy.CPU; import strategy.CleverCPU; public class RockPaperScissorsGame { public static RockPaperScissorsGame self = new RockPaperScissorsGame(); RockPaperScissorsFrame frame; CPU opponent; private RockPaperScissorsGame() { this.frame = RockPaperScissorsFrame.getInstance(); // 下の2つのうちどちらかを選ぶ。 // this.opponent = new RandomCPU( "CPU" ); this.opponent = new CleverCPU( "賢いCPU" ); } public static RockPaperScissorsGame getInstance() { return self; } /** * ゲーム開始 * */ public void play() { frame.label.setText( opponent.getName() + ":「じゃーんけーん」" ); frame.label.setIcon(null); } /** * 勝敗判定 * @param myHandId プレイヤの手(ID) * @param opponentHandId CPUの手(ID) * @return プレイヤの勝ち:3, CPUの勝ち:2, 引き分け:1 */ public int judge( int myHandId, int opponentHandId ) { // 引き分け if( myHandId == opponentHandId ) return 1; else if( (myHandId+3-opponentHandId)%3 == 2 ) return 3; else if( (myHandId+3-opponentHandId)%3 == 1 ) return 2; else return 9; } }
// RockPaperScissorsFrame.java package main; import hand.Hand; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import constants.HandConstants; import util.MyProperties; public class RockPaperScissorsFrame extends JFrame implements ActionListener, WindowListener { JLabel resultLabel, label; JButton rockButton, scissorButton, paperButton; JPanel panel, centerPanel, southPanel; MyProperties properties; int win, lose, draw; final String CONFIG_FILE_NAME = "RockPaperScissors.txt"; final String LOCATE_X = "locateX"; final String LOCATE_Y = "locateY"; final String WIN = "win"; final String LOSE = "lose"; final String DRAW = "draw"; public static RockPaperScissorsFrame self = new RockPaperScissorsFrame(); public static RockPaperScissorsFrame getInstance() { return self; } private RockPaperScissorsFrame() { panel = new JPanel(new BorderLayout()); centerPanel = new JPanel( new BorderLayout() ); southPanel = new JPanel(); resultLabel = new JLabel(); resultLabel.setHorizontalAlignment( JLabel.CENTER ); label = new JLabel(); label.setHorizontalAlignment( JLabel.CENTER ); centerPanel.add( label, BorderLayout.CENTER ); // rockButton = new JButton( HandConstants.HAND_ROCK.getIcon() ); rockButton.setName( "" + HandConstants.HAND_ROCK.getId() ); scissorButton = new JButton( HandConstants.HAND_SCISSOR.getIcon() ); scissorButton.setName( "" + HandConstants.HAND_SCISSOR.getId() ); paperButton = new JButton( HandConstants.HAND_PAPER.getIcon() ); paperButton.setName( "" + HandConstants.HAND_PAPER.getId() ); rockButton.addActionListener(this); scissorButton.addActionListener(this); paperButton.addActionListener(this); southPanel.add( rockButton ); southPanel.add( scissorButton ); southPanel.add( paperButton ); // panel.add(resultLabel, BorderLayout.NORTH); panel.add(centerPanel, BorderLayout.CENTER); panel.add(southPanel, BorderLayout.SOUTH); getContentPane().add(panel); try { loadConfig(); } catch( FileNotFoundException fnfe ) { try { if( new File(CONFIG_FILE_NAME).createNewFile() ) { loadConfig(); } } catch( IOException ioe ) { } } catch( IOException ioe ) { } this.setTitle( "じゃんけん" ); this.setSize( 300, 200 ); this.setResizable(false); this.setVisible(true); this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); addWindowListener(this); } /** * 設定ファイルをロード〜設定 * @throws IOException */ private void loadConfig() throws IOException { FileInputStream configFileStream = null; try { configFileStream = new FileInputStream(CONFIG_FILE_NAME); properties = new MyProperties(); properties.load(configFileStream); getContentPane().setLocation(properties.getInt(LOCATE_X, 0), properties.getInt(LOCATE_Y, 0)); this.setLocation(properties.getInt(LOCATE_X, 0), properties.getInt(LOCATE_Y, 0)); this.win = properties.getInt( WIN, 0 ); this.lose = properties.getInt( LOSE, 0 ); this.draw = properties.getInt( DRAW, 0 ); resultLabel.setText( "勝ち:" + win + " 負け:" + lose + " 引き分け:" + draw ); } finally { if(configFileStream != null) configFileStream.close(); } } public void actionPerformed(ActionEvent e) { if( e.getSource() == rockButton || e.getSource() == scissorButton || e.getSource() == paperButton ) { RockPaperScissorsGame game = RockPaperScissorsGame.getInstance(); // 対戦相手が次に出す手 Hand nextHand = game.opponent.considerNextHand(); label.setText( game.opponent.getName() + ":「ぽいっ」" ); label.setIcon( nextHand.getIcon() ); int myHandId = Integer.parseInt( ((JButton)e.getSource()).getName() ); int opponentHandId = nextHand.getId(); // 勝敗判定 int result = game.judge(myHandId, opponentHandId); // CPUに勝敗結果を通知する。 game.opponent.setResult( result ); switch( result ) { // プレイヤの勝ち case 3: { win++; break; // CPUの勝ち } case 2: { lose++; break; // 引き分け } case 1: { draw++; break; // その他 } default: { throw new IllegalArgumentException( "あり得ない例外です:" + result ); } } resultLabel.setText( "勝ち:" + win + " 負け:" + lose + " 引き分け:" + draw ); // 緊急描画 centerPanel.paintImmediately( 0, 0, centerPanel.getWidth(), centerPanel.getHeight() ); // 1ゲーム終わるごとに結果を保存することにする。 saveConfig(); try { Thread.sleep(1000); } catch( InterruptedException ie ) {} game.play(); } } public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) { saveConfig(); System.exit(0); } public void windowClosed(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} /** * 設定ファイルにセーブ * */ private void saveConfig() { FileOutputStream configFileStream = null; properties.putInt(LOCATE_X, this.getX()); properties.putInt(LOCATE_Y, this.getY()); properties.putInt(WIN, this.win); properties.putInt(LOSE, this.lose); properties.putInt(DRAW, this.draw); try { configFileStream = new FileOutputStream(CONFIG_FILE_NAME); properties.store(configFileStream, "Data"); configFileStream.flush(); } catch( IOException ioe ) { ioe.printStackTrace(); } finally { try { if( configFileStream != null ) configFileStream.close(); } catch( IOException ioe ) {} } } }
// CPU.java package strategy; import hand.Hand; public abstract class CPU { private String name; private int result; public CPU( String name ) { this.name = name; } /** * 次に出す手を決める。<br> * * @return 次に出す手 */ public abstract Hand considerNextHand(); public void setResult( int result ) { this.result = result; } public int getResult( ) { return this.result; } public String getName() { return this.name; } }
// RandomCPU.java package strategy; import hand.Hand; import constants.HandConstants; /** * 何の情報もなしにただランダムに手を決めるだけのCPU。 */ public class RandomCPU extends CPU { public RandomCPU(String name) { super(name); } /** * 何の情報もなしにただランダムに手を決めるだけの戦術。 */ @Override public Hand considerNextHand() { int random = (int)(Math.random() * 3); return HandConstants.HANDS[random]; } }
// CleverCPU.java package strategy; import hand.Hand; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import constants.HandConstants; /** * プレイヤが何を何回出したかを把握しているCPU */ public class CleverCPU extends CPU { /** * プレイヤが今までに何を何回出したか */ HashMap<Hand, Integer> opponentHistory; Hand beforeHand; public CleverCPU(String name) { super(name); this.opponentHistory = new HashMap<Hand, Integer>(); } /** * プレイヤの手の傾向を読んで、プレイヤが出さない手を見切る戦術。 * プレイヤが決まって1つまたは2つの手しか出さない場合に有効。 */ @Override public Hand considerNextHand() { //System.out.println( opponentHistory.toString() ); //System.out.print( "賢いCPU:「前回俺は" + beforeHand + "だして結果は" ); //if( getResult() == 3 ) { // System.out.println( "プレイヤの勝ちだった」" ); //} else if( getResult() == 2 ) { // System.out.println( "俺の勝ちだった」" ); //} else if( getResult() == 1 ) { // System.out.println( "引き分けだった」" ); //} else { // System.out.println( "多分初回」" ); //} int opponentRockCount = get( HandConstants.HAND_ROCK ); int opponentScissorCount = get( HandConstants.HAND_SCISSOR ); int opponentPaperCount = get( HandConstants.HAND_PAPER ); // 初回 if( beforeHand == null ) { // 履歴をセットしない // プレイヤがグーを出したケース } else if( (beforeHand == HandConstants.HAND_ROCK && getResult() == 1) || (beforeHand == HandConstants.HAND_SCISSOR && getResult() == 3) || (beforeHand == HandConstants.HAND_PAPER && getResult() == 2) ) { //System.out.println( "賢いCPU:「前回プレイヤはグーを出したっぽい」\n" ); opponentHistory.put( HandConstants.HAND_ROCK, ++opponentRockCount ); // プレイヤがチョキを出したケース } else if( (beforeHand == HandConstants.HAND_ROCK && getResult() == 2) || (beforeHand == HandConstants.HAND_SCISSOR && getResult() == 1) || (beforeHand == HandConstants.HAND_PAPER && getResult() == 3) ) { //System.out.println( "賢いCPU:「前回プレイヤはチョキを出したっぽい」\n" ); opponentHistory.put( HandConstants.HAND_SCISSOR, ++opponentScissorCount ); // プレイヤがパーを出したケース } else if( (beforeHand == HandConstants.HAND_ROCK && getResult() == 3) || (beforeHand == HandConstants.HAND_SCISSOR && getResult() == 2) || (beforeHand == HandConstants.HAND_PAPER && getResult() == 1) ) { //System.out.println( "賢いCPU:「前回プレイヤはパーを出したっぽい」\n" ); opponentHistory.put( HandConstants.HAND_PAPER, ++opponentPaperCount ); } ArrayList<Hand> myList = new ArrayList<Hand>( opponentRockCount+opponentScissorCount+opponentPaperCount ); for( int i=0; i<opponentRockCount; i++ ) myList.add( HandConstants.HAND_PAPER ); for( int i=0; i<opponentScissorCount; i++ ) myList.add( HandConstants.HAND_ROCK ); for( int i=0; i<opponentPaperCount; i++ ) myList.add( HandConstants.HAND_SCISSOR ); Collections.shuffle( myList ); Hand nextHand = null; try { nextHand = myList.get(0); // 初回のみランダム } catch( IndexOutOfBoundsException iooe ) { nextHand = HandConstants.HANDS[(int)(Math.random() * 3)]; } // 次回のために今から出す手を覚えておき、次回の「前回出した手」にする。 beforeHand = nextHand; return nextHand; } private int get( Hand hand ) { Integer integer = opponentHistory.get( hand ); if( integer == null ) return 0; else return integer; } }
// Hand.java package hand; import javax.swing.ImageIcon; public class Hand { private int id; private String name; private ImageIcon icon; public Hand( int id, String name, ImageIcon icon ) { this.id = id; this.name = name; this.icon = icon; } public int getId() { return this.id; } public String getName() { return this.name; } public ImageIcon getIcon() { return this.icon; } public String toString() { return name; } }
// HandConstants.java package constants; import hand.Hand; import javax.swing.ImageIcon; public final class HandConstants { public static final Hand HAND_ROCK = new Hand( 0, "グー", new ImageIcon("gu.gif") ); public static final Hand HAND_SCISSOR = new Hand( 1, "チョキ", new ImageIcon("cyoki.gif") ); public static final Hand HAND_PAPER = new Hand( 2, "パー", new ImageIcon("pa.gif") ); public static final Hand[] HANDS = new Hand[] { HAND_ROCK, HAND_SCISSOR, HAND_PAPER, }; }
// MyProperties.java package util; import java.util.*; /** * @see ttp://sei.qee.jp/program/java/ohjava/backnum/05/0094.html */ public class MyProperties extends Properties { public MyProperties() { super(); } /** * String型データの取得 */ public String get(String key, String defaultValue) { return getProperty(key, defaultValue); } /** * boolean型データの取得 */ public boolean getBoolean(String key, boolean defaultValue) { return Boolean.getBoolean(getProperty(key, Boolean.toString(defaultValue))); } /** * int型データの取得 */ public int getInt(String key, int defaultValue) { String value = getProperty(key, Integer.toString(defaultValue)); try { return Integer.parseInt(value); } catch( NumberFormatException e ) { return defaultValue; } } /** * String型データの設定 */ public void put(String key, String value) { setProperty(key, value); } /** * boolean型データの設定 */ public void putBoolean(String key, boolean value) { setProperty(key, Boolean.toString(value)); } /** * int型データの設定 */ public void putInt(String key, int value) { setProperty(key, Integer.toString(value)); } }
// UranaiApp.java public class UranaiApp { public static void main(String[] args) { // 課題1 Uranai person1 = new Uranai( args[0] ); Uranai person2 = new Uranai( args[1] ); person1.printName(); person1.printSynastryTo(person2); person2.printName(); person2.printSynastryTo(person1); // 課題2 Uranai.hantei( person1, person2 ); } }
// Uranai.java public class Uranai { private String hiraganaName; private String numericName; public Uranai( String hiraganaName ) { this.hiraganaName = hiraganaName; StringBuffer buffer = new StringBuffer(hiraganaName.length()); for( int i=0; i<hiraganaName.length(); i++ ) { try { buffer.append( getNumber(hiraganaName.charAt(i)) ); } catch( IllegalArgumentException iae ) { iae.printStackTrace(); } } this.numericName = buffer.toString(); } private int getNumber( char c ) { switch( c ) { case 'あ': case 'か': case 'さ': case 'た': case 'な': case 'は': case 'ま': case 'や': case 'ら': case 'わ': case 'が': case 'ざ': case 'だ': case 'ば': case 'ぱ': case 'ゃ': return 1; case 'い': case 'き': case 'し': case 'ち': case 'に': case 'ひ': case 'み': case 'り': case 'ゐ': case 'ぎ': case 'じ': case 'ぢ': case 'び': case 'ぴ': case 'ぃ': return 2; case 'う': case 'く': case 'す': case 'つ': case 'ぬ': case 'ふ': case 'む': case 'ゆ': case 'る': case 'ぐ': case 'ず': case 'づ': case 'ぶ': case 'ぷ': case 'ぅ': case 'ゅ': return 3; case 'え': case 'け': case 'せ': case 'て': case 'ね': case 'へ': case 'め': case 'れ': case 'ゑ': case 'げ': case 'ぜ': case 'で': case 'べ': case 'ぺ': case 'ぇ': return 4; case 'お': case 'こ': case 'そ': case 'と': case 'の': case 'ほ': case 'も': case 'よ': case 'ろ': case 'を': case 'ご': case 'ぞ': case 'ど': case 'ぼ': case 'ぽ': case 'ぉ': case 'ょ': return 5; default: throw new IllegalArgumentException( "サポートされていない文字なので無視します:" + c ); } } /** * 名前表示 * */ public void printName() { System.out.println( "私の名前は" + hiraganaName + "です。" ); } /** * 相性表示 * @param partner 相手 */ public void printSynastryTo( Uranai partner ) { String pairNumericString = this.numericName + partner.numericName; int synastry = Uranai.calculateSynastry( pairNumericString ); System.out.println( "私" + "(" + this.hiraganaName + ")と" + partner.hiraganaName + "の相性は" + synastry + "%です。" ); } /** * 計算 * @param pairNumericString 二人文の長い数字列 * @return 相性(単位はパーセント) */ private static int calculateSynastry( String pairNumericString ) { int length = pairNumericString.length(); String synastryString = null; while( length >= 3 ) { synastryString = ""; for( int i=0; i<length-1; i++ ) { int iNumber = pairNumericString.charAt(i) - 48; int iPlus1Number = pairNumericString.charAt(i+1) - 48; synastryString += ((iNumber+iPlus1Number)%10); } System.out.println( "synastryString: " + synastryString ); pairNumericString = synastryString; length--; } return Integer.parseInt( synastryString ); } /** * 課題2 * @param person1 一人目 * @param person2 二人目 */ public static void hantei( Uranai person1, Uranai person2 ) { String pairNumericString = person1.numericName + person2.numericName; System.out.println( person1.hiraganaName + "と" + person2.hiraganaName + "の相性は" + Uranai.calculateSynastry( pairNumericString ) + "%です。" ); } }
// TicTacToe.java import java.applet.Applet; /* <applet code="TicTacToe.class" width=0 height=0> </applet> */ public class TicTacToe extends Applet { public void init() { TicTacToeFrame frame = TicTacToeFrame.getInstance(); frame.setTitle( "○×ゲーム" ); frame.setSize( 200, 200 ); frame.setResizable( false ); frame.setVisible( true ); frame.player1.play(); } }
// TicTacToeFrame.java import java.awt.BorderLayout; import java.awt.Button; import java.awt.Checkbox; import java.awt.Color; import java.awt.Dialog; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Label; import java.awt.Panel; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; public class TicTacToeFrame extends Frame implements ActionListener, WindowListener { Button[] buttons = new Button[9]; Player player1, player2; private TicTacToeFrame() { setLayout( new GridLayout( 3, 3 ) ); for( int i=0; i<buttons.length; i++ ) { buttons[i] = new Button(); buttons[i].setBackground( Color.WHITE ); buttons[i].addActionListener( this ); buttons[i].setName( "" + i ); add( buttons[i] ); } addWindowListener(this); createPlayers(); } private static TicTacToeFrame self = new TicTacToeFrame(); public static TicTacToeFrame getInstance() { return self; } /** * プレイヤの生成 * */ private void createPlayers() { final Dialog dialog = new Dialog( this, "プレイヤの生成", true ); Panel panel = new Panel( new GridLayout( 2, 1 ) ); Panel panel1 = new Panel( new BorderLayout() ); Panel panel2 = new Panel( new BorderLayout() ); final TextField tf1, tf2; final Checkbox cb1, cb2; panel1.add( new Label( "先手" ), BorderLayout.WEST ); panel1.add( tf1 = new TextField( "( ´д)" ), BorderLayout.CENTER ); panel1.add( cb1 = new Checkbox("CPU?"), BorderLayout.EAST ); panel2.add( new Label( "後手" ), BorderLayout.WEST ); panel2.add( tf2 = new TextField( "(д` )" ), BorderLayout.CENTER ); panel2.add( cb2 = new Checkbox("CPU?"), BorderLayout.EAST ); panel.add( panel1 ); panel.add( panel2 ); Button playButton = new Button( "play" ); playButton.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { if( cb1.getState() ) player1 = new CPU( tf1.getText(), "○" ); else player1 = new Human( tf1.getText(), "○" ); if( cb2.getState() ) player2 = new CPU( tf2.getText(), "×" ); else player2 = new Human( tf2.getText(), "×" ); dialog.dispose(); } } ); dialog.add( panel, BorderLayout.CENTER ); dialog.add( playButton, BorderLayout.SOUTH ); dialog.setSize( 200, 100 ); dialog.setLocation( this.getX() + 0, this.getY() + 50 ); dialog.setResizable( false ); dialog.setVisible( true ); } /** * Humanがボタンを押した。 * 次にバトンタッチする(HumanかCPUのplay()を呼ぶ)。 */ public void actionPerformed(ActionEvent e) { int num = Integer.parseInt( ((Button)e.getSource()).getName() ); Player nowPlayer = getTurn( player1.getMyList().size() + player2.getMyList().size() ); nowPlayer.addMyList( num ); buttons[num].setLabel( nowPlayer.getLabel() ); buttons[num].setEnabled(false); // 勝ち負け判定 if( nowPlayer.getMyList().size() >= 3 ) { // 最後まで行った if( nowPlayer.getMyList().size() == 5 ) { // 決着が付かない if( !nowPlayer.judge() ) { showEndMessage( "引き分け" ); return; } } if( nowPlayer.judge() ) { String str; if( nowPlayer.getLabel().equals( "○" ) ) str = "先手"; else str = "後手"; showEndMessage( str + "の" + nowPlayer.getName()+"さんの勝ち" ); return; } } // 対戦相手にバトンタッチ Player opponent = getTurn( player1.getMyList().size() + player2.getMyList().size() ); opponent.play(); } /** * 終了時のダイアログを表示 * @param message 表示するメッセージ */ public void showEndMessage( String message ) { Dialog dialog = new Dialog( this, message, true ); Button okButton = new Button( "ok" ); okButton.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { dispose(); } } ); dialog.add( new Label( message + "です。"), BorderLayout.CENTER ); dialog.add( okButton, BorderLayout.SOUTH ); dialog.setSize( 200, 100 ); dialog.setLocation( this.getX() + 0, this.getY() + 50 ); dialog.setResizable( false ); dialog.setVisible( true ); } /** * 誰の順番なのかを判断 * @param already すでに○か×が描かれている数 * @return 先手または後手 */ public Player getTurn( int already ) { return (already % 2 == 0) ? player1 : player2; } public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) { dispose(); } public void windowClosed(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} }
// Player.java import java.util.TreeSet; public abstract class Player { private String name; private String label; private TreeSet<Integer> myList; public Player( String name, String label ) { this.name = name; this.label = label; myList = new TreeSet<Integer>(); } public TreeSet<Integer> getMyList() { return myList; } public void addMyList( int position ) { myList.add( position ); } public String getName() { return name; } public String getLabel() { return label; } public abstract void play(); /** * 列をそろえているかどうか判定 * * @return そろえていればtrue */ public boolean judge() { Integer[] positionsObject = (Integer[])(getMyList().toArray( new Integer[0] )); for( int i=0; i<positionsObject.length; i++ ) { // 左から右への判定 // 左の列の時 if( positionsObject[i] % 3 == 0 ) { // その隣2つを持っている場合 if( getMyList().contains( positionsObject[i] + 1 ) && getMyList().contains( positionsObject[i] + 2 )) { return true; } } // 上から下への判定 // 上の列の時 if( positionsObject[i] < 3 ) { // その下2つを持っている場合 if( getMyList().contains( positionsObject[i] + 3 ) && getMyList().contains( positionsObject[i] + 6 ) ) { return true; } } // 斜めの判定 左上から右下 if( getMyList().contains( 0 ) && getMyList().contains( 4 ) && getMyList().contains( 8 ) ) { return true; } // 斜めの判定 右上から左下 if( getMyList().contains( 2 ) && getMyList().contains( 4 ) && getMyList().contains( 6 ) ) { return true; } } return false; } }
// CPU.java import java.awt.Button; public class CPU extends Player { public CPU(String name, String label) { super(name, label); } @Override public void play() { try { // 考えているっぽい雰囲気 long waitTime = (long)(Math.random()*1000); Thread.sleep( waitTime ); TicTacToeFrame frame = TicTacToeFrame.getInstance(); Button[] buttons = frame.buttons; // TODO なんらかのアルゴリズムを考えないと今のままではゲームにならない。 // frameをもらってきてるから、自分と相手がどこにマークを付けたかは分かっているので // それを基にアルゴリズム組んでみてください。 System.out.println( "自分はplayer1ですか? " + (frame.player1 == this) ); System.out.println( "自分はplayer2ですか? " + (frame.player2 == this) ); for( int i=0; i<buttons.length; i++ ) { if( buttons[i].isEnabled() ) { addMyList( i ); buttons[i].setLabel( getLabel() ); buttons[i].setEnabled(false); break; } } // 勝ち負け判定 if( getMyList().size() >= 3 ) { // 最後まで行った if( getMyList().size() == 5 ) { // 決着が付かない if( !judge() ) { frame.showEndMessage( "引き分け" ); return; } } if( judge() ) { String str; if( getLabel().equals( "○" ) ) str = "先手"; else str = "後手"; frame.showEndMessage( str + "の" + getName()+"さんの勝ち" ); return; } } // 対戦相手にバトンタッチ Player opponent = frame.getTurn( frame.player1.getMyList().size() + frame.player2.getMyList().size() ); opponent.play(); } catch( InterruptedException ie ) { } } }
// Human.java public class Human extends Player { public Human(String name, String label) { super(name, label); } public void play() { // 人まかせ } }
// FourArithmeticOperationsDemo.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class FourArithmeticOperationsDemo { public static void main(String[] args) { BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) ); boolean isCorrectNum1 = false; int num1 = 0; while( !isCorrectNum1 ) { System.out.print( "値1を入力 > " ); try { num1 = Integer.parseInt( br.readLine() ); isCorrectNum1 = true; } catch( IOException ioe ) { } catch( NumberFormatException nfe ) { } } boolean isCorrectOperator = false; char operator = '\u0000'; while( !isCorrectOperator ) { try { System.out.print( "演算子を入力 > " ); String operatorString = br.readLine(); if( operatorString.equals("+") || operatorString.equals("-") || operatorString.equals("*") || operatorString.equals("/") ) { isCorrectOperator = true; operator = operatorString.charAt(0); } } catch( IOException ioe ) { } } boolean isCorrectNum2 = false; int num2 = 0; while( !isCorrectNum2 ) { System.out.print( "値2を入力 > " ); try { num2 = Integer.parseInt( br.readLine() ); if( operator == '/' && num2 == 0 ) { System.out.println( " ゼロ割りです。" ); continue; } isCorrectNum2 = true; } catch( IOException ioe ) { } catch( NumberFormatException nfe ) { } } String result = null; switch( operator ) { case '+': { result = num1 + " + " + num2 + " = " + (num1+num2); break; } case '-': { result = num1 + " - " + num2 + " = " + (num1-num2); break; } case '*': { result = num1 + " * " + num2 + " = " + (num1*num2); break; } case '/': { int remainder = num1 % num2; if( remainder == 0 ) result = num1 + " / " + num2 + " = " + (num1/num2); else result = num1 + " / " + num2 + " = " + (num1/num2) + "あまり" + (num1%num2); break; } } System.out.println( result ); } }
// DrawGraph.java import java.applet.Applet; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; /* <applet code="DrawGraph.class" width=450 height=400> </applet> */ /** * @see ttp://cwoweb2.bai.ne.jp/~jgb11101/files/java-basic/14.html */ public class DrawGraph extends Applet implements /*ActionListener*/ChangeListener { double x, y, z, f1, f2, min, max; int z1, z2; JSlider slider; public void init() { setFont(new Font("Serif", Font.BOLD, 12)); slider = new JSlider( 1, 100 ); slider.setMajorTickSpacing(10); slider.setPaintTicks(true); slider.addChangeListener( this ); add(slider); } public void paint(Graphics g) { update(g); } public void update(Graphics g) { x = -Double.valueOf(slider.getValue()).doubleValue(); // 軸を描画する Dimension d = getSize(); int width = d.width; int height = d.height; g.setColor(Color.white); g.fillRect(0, 0, d.width, d.height); g.setColor(Color.gray); g.drawLine(0, height / 2 + 30, width, height / 2 + 30); g.drawLine(width / 2, 30, width / 2, height); g.drawString( Double.toString(x), 0, height / 2 + 45 ); g.drawString( Double.toString(-x), width - 20, height / 2 + 45 ); // y 軸の幅を求める double dx = -2 * x / width; z = x; min = 0.0; max = 0.0; for( int i = 0; i < width - 1; i++ ) { y = df(z); if( y < min ) min = y; if( y > max ) max = y; z += dx; } // y の両端の値を描画する y = Math.ceil(100 * Math.max(Math.abs(min), Math.abs(max))) / 100.0; g.setColor(Color.gray); g.drawString(Double.toString(-y), width / 2 + 5, height - 5); g.drawString(Double.toString(y), width / 2 + 5, 50); // 波形を描画する g.setColor(Color.blue); for( int i = 0; i < width - 1; i++ ) { f1 = df(x) / (1.1 * y); f2 = df(x + dx) / (1.1 * y); z1 = (int) ((height - height * f1) / 2); z2 = (int) ((height - height * f2) / 2); g.drawLine(i, z1 + 30, i + 1, z2 + 30); x += dx; } // スライダーバーが消えるのでpaintする。 super.paint(g); } double df(double x) { // y= -x^3 + 20x^2 + 800x - 3000 return -Math.pow( x, 3 ) + 20*Math.pow( x, 2 ) + 800*x - 3000; } public void stateChanged(ChangeEvent ce) { if( ce.getSource() == slider ) { repaint(); } } }