うーん、欲を言えば、オブジェクト指向でこなしたいです。
ヒントはもらっています。「ジャンケンの手をクラスにする」です。
オブジェクト指向でジャンケンの手のクラスにすると、どうなりますが、
extends 継承を使うにはどのように変えたらいいですか?
今はジャンケンの手はフィールドですね。
3人でのジャンケンの判定をしたいプログラムを作りたいのですが、詰まりました。
まず勝敗がつくパターンはジャンケンの手が2種類の時というのは分かりました。
①勝ったプレイヤーが2人の時、勝者のプレイヤー2人を返すメソッドで可能ではないような感じですし・・・
3人で勝敗がつくパターンは2人が同じ種類のジャンケンの手を出している
・・・2人が勝つパターンか、その他の1人が勝つパターン、です。
②同じ種類のジャンケンの手を出しているプレイヤーを判別認識させたい、です。
書籍のプログラムを改造しようと手を付けてみたものの、詰まってしまいました。
//@param player1 判定対象プレイヤー1 //@param player2 判定対象プレイヤー2 //@return 勝ったプレイヤー。引き分けの時はnullを返す。 private Player judgeJanken(Player player1, Player player2, Player player3){ Player winner = null; //プレイヤー1の手を出す int player1hand = player1.showHand(); //プレイヤー2の手を出す int player2hand = player2.showHand(); int player3hand = player3.showHand(); printHand(player1hand); System.out.print(" vs. "); printHand(player2hand); System.out.print(" vs. "); printHand(play3hand); System.out.print("\n"); int[] hands = { player1hand, player2hand, player3hand }; int type = 1; int maxType = 0; for(int i = 0; i < hands.length; i++){ for(int j = i + 1; j < hands.length ; j++){ if(hands[i] != hands[j]){ type++; } if(maxType < type){ maxType = type; } type = 1; } } } if(maxType == 2){ if(hands[0] == Player.STONE && hands[1] ==Player.STONE && hands[2] == Player.SCISSORS){ System.out.println(player1.getName() + "と" + player2.getName() + "が勝ちました!"); player1.winCount_++; player2.winCount_++; } else if(hands[0] == Player.STONE && hands[1] == Player.SCISSORS && hands[2] == Player.STONE){ System.out.println(player1.getName() + "と" + player3.getName() + "が勝ちました!"); player1.winCount_++; player3.winCount_++; } else if(hands[0] == Player.SCISSORS && hands[1] == Player.STONE && hands[2] == Player.STONE){ System.out.println(player2.getName() + "と" + player3.getName() + "が勝ちました!"); player2.winCount_++; player3.winCount_++; }
と、こんな風に書いて行けばいいのは分かりました。
_____________________________
うーん、欲を言えば、オブジェクト指向でこなしたいです。
ヒントはもらっています。「ジャンケンの手をクラスにする」です。
オブジェクト指向でジャンケンの手のクラスにすると、どうなりますが、
extends 継承を使うにはどのように変えたらいいですか?
今はジャンケンの手はフィールドですね。
/* if((player1hand == Player.STONE && player2hand == Player.SCISSORS) * ||(player1hand == Player.SCISSORS && player2hand == Player.PAPER) * ||(player1hand == Player.PAPER && player2hand == Player.STONE)){ * winner = player1; * } else if( * (player1hand == Player.STONE && player2hand == Player.PAPER) * ||(player1hand == Player.SCISSORS && player2hand == Player.STONE) * ||(player1hand == Player.PAPER && player2hand == Player.SCISSORS)){ * winner = player2; * } * //どちらでもない場合は引き分け(nullを返す) return winner; }
回答6件
あなたの回答
tips
プレビュー