국비지원 JAVA 풀스택 과정/JAVA
[JAVA] 주사위 게임
ODaram
2022. 10. 4. 16:52
Dice Game
주사위 게임 만들기
1. 화면에 "주사위를 굴릴까요? Enter키를 누르세요." 라는 메시지 출력
2. 사용자는 Enter키를 누른다.
3. 화면에 사용자가 뽑은 주사위 번호를 출력한다.
4. 화면에 "컴퓨터가 주사위를 굴릴까요? Enter를 누르세요"라는 메시지 출력
5. 사용자는 Enter 를 누른다.
6. 컴퓨터가 뽑은 주사위 번호를 출력
7.사용자의 주사위 번호와 컴퓨터의 주사위 번호를 비교하여
사용자가 더 높은 숫자이면 "You Win!",
낮은 숫자이면 "You Lose!",
비기면 "Draw" 라는 메시지를 출력한다.
1. 할 수 있는 것 : 메시지 출력, 난수 발생: Math.random(), Random 클래스의 nextInt()로 난수를 발생한다,
두개의 숫자를 비교해서 메시지를 출력(if ~ else if ~ else)
2. 할 수 없는 것 : 사용자가 Enter키를 눌렀을 때 인식하는 것 :
Enter 키를 누르면 행이 변경된다 -> System.out.println(scan.nextLine());
package com.dream.controls;
import java.util.Random;
import java.util.Scanner;
public class DiceGame {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//System.in:자바에서 지원하는 가장 기본적인 입력 스트림
Random rd =new Random();
// 난수를 발생시키는 기능이 있는 클래스
int user=0, com=0, random=0;
String result="";
System.out.println("=====Dice Game=====\n");
//System.out:자바에서 지원하는 가장 기본적인(콘솔 뷰) 출력 스트림
System.out.println("☞ 사용자 주사위");
System.out.print("주사위를 굴릴까요? Enter 키를 누르세요.");
scan.nextLine();
// System.out.println(scan.nextLine()); //사용자가 Enter 키를 눌렀음을 인식한다.
user = rd.nextInt(6) + 1 ; // 1~6까지의 난수 발생
System.out.println("당신이 뽑은 수 : "+user+"\n");
System.out.println("☞ 컴퓨터 주사위");
System.out.print("주사위를 굴릴까요? Enter 키를 누르세요.");
scan.nextLine();
// System.out.println(scan.nextLine());
com=rd.nextInt(6)+1; // rd.nextInt(6)는 0~5까지의 난수를 발생시킨다.
System.out.println("컴퓨터가 뽑은 수 : "+com+"\n");
if(user > com) {
result = "You Win ✌( ・ ̫・ )";
}else if(user < com) {
result = "You Lose •̄_•̄";
}else {
result = "Draw (˙ ૄ˙ )";
}
System.out.println(result);
}
}