quilt code
[고급자바] 컴퓨터와 가위바위보 프로그램 본문
문제) 컴퓨터와 가위 바위 보를 진행하는 프로그램 작성 |
컴퓨터의 가위 바위 보는 난수를 이용하여 구하고 사용자의 가위 바위 보는 showInputDialog()메소드를 이용하여 입력받는다. 입력 시간은 5초로 제한하고 카운트 다운을 진행한다. 5초 안에 입력이 없으면 게임을 진 것으로 처리한다. 5초 안에 입력이 완료되면 승패를 출력한다. |
결과예시) === 결과 === 컴퓨터 : 가위 당신 : 바위 결과 : 당신이 이겼습니다. |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
public class T07ThreadGame {
public static boolean inputCheck = false;
public static String man = ""; // 사용자의 가위바위보가 저장될 변수
public static void main(String[] args) {
// 난수를 이용하여 컴퓨터의 가위 바위 보를 정한다.
String[] data = {"가위", "바위", "보"};
int index = (int)(Math.random()*3); // 0~2사이의 난수 만들기
String com = data[index];
// 카운트 다운 쓰레드 실행
GameTimer gt = new GameTimer();
gt.start();
// 사용자로 부터 가위, 바위, 보 입력 받기
UserInput input = new UserInput();
input.start();
try {
input.join(); // 입력이 끝날때까지 기다린다.
} catch (InterruptedException e) {
e.printStackTrace();
}
// 결과 판정하기
String result = "";
if( man.equals(com) ){
result = "비겼습니다.";
}else if( (man.equals("가위") && com.equals("보"))
|| (man.equals("바위") && com.equals("가위"))
|| (man.equals("보") && com.equals("바위")) ){
result = "당신이 이겼습니다.";
}else{
result = "당신이 졌습니다.";
}
// 결과 출력
System.out.println("=== 결 과 ===");
System.out.println("컴퓨터 : " + com);
System.out.println("당 신 : " + man);
System.out.println("결 과 : " + result);
}
}
/**
* 게임 타이머
*/
class GameTimer extends Thread{
@Override
public void run() {
for(int i=5; i>=1; i--){
if(T07ThreadGame.inputCheck==true){
return;
}
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("시간이 초과되어 당신이 졌습니다.");
System.exit(0);
}
}
/**
* 사용자 입력 처리를 위한 스레드
*/
class UserInput extends Thread {
@Override
public void run() {
String inputData = "";
do{
inputData = JOptionPane.showInputDialog("가위, 바위, 보를 입력하세요");
}while(!inputData.equals("가위") && !inputData.equals("바위") && !inputData.equals("보"));
T07ThreadGame.inputCheck = true; // 입력이 완료됨을 알려주는 변수값을 변경한다.
T07ThreadGame.man = inputData; // 입력값 설정
}
}
|
cs |
'daily > 고급자바' 카테고리의 다른 글
| [고급자바] Thread(5) (0) | 2023.02.10 |
|---|---|
| [고급자바] Thread (4) (0) | 2023.02.10 |
| [고급자바] Thread(3) (0) | 2023.02.07 |
| [고급자바] Thread (2) (0) | 2023.02.07 |
| [고급자바] Thread (1) (0) | 2023.02.06 |