元小学校教員!がIT企業へ転職したリアルなブログ

公立の小学校教員を4年間勤めた後、IT企業へ転職しました。教育・転職・ITに関する情報を発信していきます。

【初心者】【JavaでHigh&Lowゲームをつくってみた】~その①~

f:id:akiho817:20200420204848j:plain

こんばんは。
駆け出しプログラマーのakhです。

最近は、しりとりプログラムでつまっています…


さて、
Javaでトランプゲームの
High&Lowゲームをつくってみました。
以下、概要です。

概ね以下の技術をつかう
・乱数作成処理
・標準入力の受け付け
・if文、while文の使い方

【ゲームのルール】
1.1~13までの数値を乱数で生成し、その数値を元値とする
2.1~13までの数値を乱数で生成し、その値を比較値とする
3.プレイヤーに元値と比較値のどちらが大きいか解答させる
4.プレイヤーが正解の場合は、正解数を1追加し、
  現在の比較値を元値とし、2の処理へ戻る。
  プレイヤーが間違えた場合は正解回数を出力しゲームを
  終了する。
補足:元値と比較値が同じ値の場合は正解とすること。

以下、コードです。

import java.util.Scanner;
public class TranpGame {

	public static void main(String[] args) {
		System.out.println("************");
		System.out.println("*High & Low*");
		System.out.println("************");
		System.out.println("");
		Scanner sc = new Scanner(System.in);
		while(true){
			int leftCard = (int)(Math.random()*9)+1;
			int rightCard = (int)(Math.random()*9)+1;

			System.out.println(" [問題表示] ");
			System.out.println("*****    *****");
			System.out.println("*   *    * * *");
			System.out.println("* "+leftCard+" *    * * *");
			System.out.println("*   *    * * *");
			System.out.println("*****    *****");
			System.out.println(" High  or  Low?(h/l)>");
			String select = sc.nextLine();
			if(select.equals("h")){
				System.out.println("→Highを選択しました。");
			}else{
				System.out.println("→Lowを選択しました。");
			}

			System.out.println("");
			System.out.println("  [結果表示]  ");
			System.out.println("*****    *****");
			System.out.println("*   *    * * *");
			System.out.println("* "+leftCard+" *    * "+rightCard+" *");
			System.out.println("*   *    * * *");
			System.out.println("*****    *****");
			String result = null;

			if(leftCard<rightCard){
				result="h";
			}else if(leftCard>rightCard){
				result="l";
			}else{
				result = select;
			}
			if(select.equals(result)){
				System.out.println("→You Win!!!!");
			}else{
				System.out.println("→You Lose...");
				System.out.println("--ゲーム終了--");
				break;
			}
		}
	}
}

今回は、

・乱数作成の仕方
・whileでループし続ける、break文を使って
 処理を終わらせること
を学びました。

表示画面

*****    *****
 High  or  Low?(h/l)>
h
→Highを選択しました。

  [結果表示]  
*****    *****
*   *    * * *
* 3 *    * 4 *
*   *    * * *
*****    *****
→You Win!!!!
 [問題表示] 
*****    *****
*   *    * * *
* 2 *    * * *
*   *    * * *
*****    *****
 High  or  Low?(h/l)>
h
→Highを選択しました。

  [結果表示]  
*****    *****
*   *    * * *
* 2 *    * 7 *
*   *    * * *
*****    *****
→You Win!!!!
 [問題表示] 
*****    *****
*   *    * * *
* 4 *    * * *
*   *    * * *
*****    *****
 High  or  Low?(h/l)>
l
→Lowを選択しました。

  [結果表示]  
*****    *****
*   *    * * *
* 4 *    * 4 *
*   *    * * *
*****    *****
→You Win!!!!
 [問題表示] 
*****    *****
*   *    * * *
* 5 *    * * *
*   *    * * *
*****    *****
 High  or  Low?(h/l)>