JAVA

[JAVA2] 동물키우기 게임 만들기

보라해바라기 2023. 7. 16. 12:46
SMALL

1. startGame.java (게임 UI)

package com.jangjihye.pettycoon.domain;
import java.io.IOException;
import java.util.Scanner;

import com.jangjihye.pettycoon.statics.PetType;

// 게임 시작 화면
// 객체: input (번호 입력)
public class startGame {
	// jar 파일 배포를 위한 워닝 제거
	@SuppressWarnings({ "resource" })
	public static void main(String[] args) {
		
		int begin = 0; // 처음으로 돌아오기
		User user = null;
		
		// loopOut : 탈출 반복문 지정
		loopOut:
			while (begin == 0) {
			System.out.println("♥ 동 물 키 우 기 ♥");
			System.out.println("");
			System.out.println("[시작 메뉴]");
			System.out.println("(1) 게임 시작");
			System.out.println("(2) 종료" );
			System.out.print("번호를 입력해주세요: ");
			
			Scanner s1 = new Scanner(System.in);
			int startInput = s1.nextInt(); // 입력 값이 숫자.
			
			// 게임 시작 화면 (메인 메뉴에서 범위를 넘는 값을 입력했을 때, 다시 메인 메뉴로 돌아오는 기능 구현 완!)
			if (startInput == 1) {
				begin++;
				System.out.println("게임을 시작합니다.");
				System.out.println("메인 메뉴로 이동합니다.");
				System.out.println("");
				 
				while (true) {
					System.out.println("[메인 메뉴]");
					System.out.println("(1) 펫 고르기");
					System.out.println("(2) 이전 메뉴 이동" );
					System.out.print("번호를 입력해주세요: ");
					// 펫 고르기
					Scanner s2 = new Scanner(System.in);
					int mainInput = s2.nextInt();
					if (mainInput == 1) {
						while(true) {
							System.out.println("");
							System.out.println("펫을 골라주세요.");
							System.out.println("1. 강아지");
							System.out.println("2. 고양이");
							System.out.println("3. 앵무새");
							System.out.println("4. 햄스터");
							
							// 각 항목 선택에 따른 출력
							System.out.print("펫 고르기(번호 입력): ");
							Scanner s3 = new Scanner(System.in);
							int petTypeInput = s3.nextInt();
							System.out.println();
							
							if (petTypeInput>=1 && petTypeInput<=4) {
								if (petTypeInput == 1) {
									user = new User(PetType.DOG);
								} else if (petTypeInput == 2) {
									user = new User(PetType.CAT);
								} else if (petTypeInput == 3) {
									user = new User(PetType.PARROT);
								} else if (petTypeInput == 4) {
									user = new User(PetType.HAMSTER);
								}
								System.out.print("펫의 이름을 입력하세요: ");
								Scanner s4 = new Scanner(System.in);
								String petNameInput = s4.nextLine();
								user.createPetName(petNameInput);
								System.out.println("[펫 관리]");
								System.out.println(user.getUserPet());
								break;
							}
							 else {
								System.out.println();
								System.out.println("값을 다시 입력하세요.");
								continue;
							}
						}
						
						// 펫 관리 메뉴
						while(true) {
							System.out.println("");
							System.out.println("[메뉴]");
							System.out.println("1. 먹이주기");
							System.out.println("2. 씻기기");
							System.out.println("3. 미용하기");
							System.out.println("4. 산책하기");
							System.out.println("5. 게임 종료");
							
							System.out.print("번호를 입력하세요:" );
							Scanner s5 = new Scanner(System.in);
							int playInput = s5.nextInt(); // 입력 값이 숫자.
							// 원할 때 까지, 놀아주기 가능해야 함! (반복 해야 함. > 5번 입력 시, 게임 종료하고 반복도 멈춤.)
							// while 사용
							
							if (playInput>=1 && playInput<=4){
							if (playInput == 1) {
								System.out.println("<먹이 주기>를 수행했습니다.");
								user.Feed();
							} else if (playInput == 2) {
								System.out.println("<씻겨 주기>를 수행했습니다.");
								user.Wash();
							} else if (playInput == 3) {
								System.out.println("<미용 하기>를 수행했습니다.");
								user.Grooming();
							} else if (playInput == 4) {
								System.out.println("<산책 하기>를 수행했습니다.");
								user.Walk();
							}
							// 일정 시간이 지나면 나이 1 증가
							System.out.println();
							System.out.println("[펫 상태]");
							System.out.println(user.getUserPet());
							continue;
							} else if (playInput == 5) {
								System.out.println("게임을 종료합니다.");
								break loopOut;
							} else {
								System.out.println("값을 다시 입력하세요.");
								continue;
							}
						}
						
					} else if (mainInput == 2) {
						System.out.println("이전 메뉴로 이동합니다.");
						System.out.println("");
						begin = 0;	
						break;
					} else {
						System.out.println("값을 다시 입력하세요.");
						System.out.println("");
						continue;
						// 구현하기 !
					}
					
				}
			} else if (startInput == 2) {
				System.out.println("게임을 종료합니다.");
				begin++;
				clearScreen(30);
			} else {
				System.out.println("값을 다시 입력하세요.");
				System.out.println("");
				clearScreen(30);
				continue; // 똑같은 메뉴 다시 보여주어 값 받기
			}
		}
	}
	
	public static void clearScreen(int line) {
    	try {
    		final String os = System.getProperty("os.name");
    		if (os.contains("Windows")) {
    			new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
    		} else {
    			System.out.print("33[H33[2J");
    			System.out.flush();
    		}
		} catch (IOException | InterruptedException ex) {
			ex.printStackTrace();
		} 
    	
    }
	
}

 

2. Pet.java

package com.jangjihye.pettycoon.domain;

import java.util.Random;
import com.jangjihye.pettycoon.statics.PetType;

//  펫 상태
public class Pet {
	private String name; // 이름
	private String gender; // 성별
	private String type; // 펫 종류 (사용자가 펫 종류를 고를 수 있음)
	protected int age; // 나이
	protected int satiety; // 포만감
	protected int cleanliness; // 청결도
	protected int beauty; // 미모
	protected int stress; // 스트레스
	protected int liking; // 호감도
	
	// 펫 생성 시, type 지정하며 펫 생성하고 그 다음 펫 이름을 지정 (생성자 사용) > 제약사항 구현
	public Pet(String type) {
		// 펫 종류는 선택하고 난 후, 고정됨.
		setType(type);
		
		// 성별 : 랜덤
		long seed = System.currentTimeMillis();
		Random rand = new Random(seed);
		this.gender = (rand.nextBoolean()) ? PetType.WOMAN : PetType.MAN;
		
		// 나이 : 초기값 1
		this.age = 1;
	}
	
	// 1. 펫 종류를 지정할 수 있는 동작 정의
	// Setter 이용
	// User에 있는 Feed, Wash, Grooming, Walk를 Pet에 쓰면 더 간결한 코드가 될 수도? 
	
	public void setType(String type) {
		this.type = type;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public void setSatiety(int satiety) {
		this.satiety = satiety;
	}

	public void setCleanliness(int cleanliness) {
		this.cleanliness = cleanliness;
	}
	
	public void setBeauty(int beauty) {
		this.beauty = beauty;
	}
	
	public void setStress(int stress) {
		this.stress = stress;
	}
	
	public void setLiking(int liking) {
		this.liking = liking;
	}
	
	// 나이 증가를 위한 메서드
	
	
	//

	// Pet 클래스의 toString() 메서드;
	@Override
	public String toString() {
		return "이름: " + name + ", 성별: " + gender + ", 종: " + type + ", 나이: " + age + ", 포만감: " + satiety
				+ ", 청결도: " + cleanliness + ", 미모: " + beauty + ", 스트레스: " + stress + ", 만족도: " + liking;
	}
	
	
	
}

 

3. User.java

package com.jangjihye.pettycoon.domain;

// pet 클래스를 사용자의 필드로 사용
public class User extends Pet{
	private Pet userPet;
	
	// User 클래스로 인스턴스가 생성될 때, Pet 클래스의 인스턴스도 동시에 생성되게 한다.
	public User(String petType) {
		super(petType);
		this.userPet = new Pet(petType);
	}
	
	// Getter / Setter
	public Pet getUserPet() {
		return userPet;
	}
	
	// End of Getter / Setter
	
	
	// 사용자가 펫의 이름을 지정할 수 있도록 메서드를 만든다.
	// Setter 느낌을 주지 않기 위해, 다른 키워드 사용 (create)
	public void createPetName(String name) {
		userPet.setName(name);
	}
	
	// 먹이 주기, 씻겨주기, 미용시키기, 산책하기 구현
	// 값 누적 : setter 안의 값을 "연산 식으로" 구현
	// Pet의 protected int들을 사용!
	
	public void Feed() {
//		* 상태변화
//		1. 포만감이 5 상승한다. 2. 청결도가 2 감소한다. 3. 스트레스가 3 감소한다. 4. 호감도가 3 상승한다.
		userPet.setSatiety(satiety += 5); // 포만감
		userPet.setCleanliness(cleanliness -= 2); // 청결도
		userPet.setStress(stress -= 3); // 스트레스
		userPet.setLiking(liking += 3); // 호감도
		
	}
	
	public void Wash() {
//		 * 상태변화
//		 1. 포만감이 3 감소한다. 2. 청결도가 5 상승한다. 3. 스트레스가 2 상승한다
		userPet.setSatiety(satiety -= 3); // 포만감
		userPet.setCleanliness(cleanliness += 5); // 청결도
		userPet.setStress(stress += 2); // 스트레스
	}
	
	public void Grooming() {
//		 * 상태변화
//		 1. 포만감이 3 감소한다. 2. 청결도가 3 상승한다. 3. 미모가 5 상승한다. 4. 스트레스가 2 상승한다
		userPet.setSatiety(satiety -= 3); // 포만감
		userPet.setCleanliness(cleanliness += 3); // 청결도
		userPet.setBeauty(beauty += 5); // 미모
		userPet.setStress(stress += 2); // 스트레스
	}
	
	public void Walk() {
//		 * 상태변화
//		 1. 포만감이 5 감소한다. 2. 청결도가 4 감소한다. 3. 미모가 3 감소한다. 4. 스트레스가 4 감소한다. 5. 호감도가 5 상승한다.
		userPet.setSatiety(satiety -= 5); // 포만감
		userPet.setCleanliness(cleanliness -= 5); // 청결도
		userPet.setBeauty(beauty -= 4); // 미모
		userPet.setStress(stress -= 4); // 스트레스
		userPet.setLiking(liking += 5); // 호감도
	}
	
//	public void Age() { // 시간에 따른 증가는 어떻게 만드나?
//		try {
//			Thread.sleep(5000);
//			userPet.setAge(age += 1);
//		} catch (InterruptedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		
//	}
	
}

 

4. PetType.java

package com.jangjihye.pettycoon.statics;

// 펫 종류는 고정되어 있음. > 상수 표현 가능!

public class PetType {
	// 상수 표현 수단: static
	
	public static final String DOG = "강아지";
	public static final String CAT = "고양이";
	public static final String PARROT = "앵무새";
	public static final String HAMSTER = "햄스터";
	
	// 성별 (랜덤: 난수 생성 시, seed를 가지고 생성)
	public static final String MAN = "남자";
	public static final String WOMAN = "여자";
	
}

** 스레드 이용해서 나이 계산하는 거 구현 !

728x90