본문 바로가기

JAVA Console Game/JAVA Text RPG

JAVA 입문자 Text RPG 만들기 6일차

6일차 

 

import java.io.IOException;

public class Start {

	public static void main(String[] args) throws IOException {
		Choice ch = new Choice();

			ch.Choice_Start();


	}

}

Main claas 간결하게 적고 나머지는 클래스로 만들어서 사용할생각이예요.

 

 

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class Choice {

	public Choice(){

	}
	public void Choice_Start() throws IOException{ // 시작 선택
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

		while(true){
			System.out.println("\n\nNew World");
			System.out.print("\n1.Start\n2.Exit\nCh : ");

			String StartCh = bf.readLine(); // 시작 선택
			if(StartCh.equals("1")){
				Choice_Player();

			}else if(StartCh.equals("2")){ // 첫번째 종료
				Exit();
				return;
			}else{
				System.out.println("RE");
			}
		}
	}

	public void Choice_Player() throws IOException{ // 플레이어 선택
		List_P_M List = new List_P_M();
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		while(true){
			System.out.print("\n\n1.New Start\n2.Save\n3.Exit\nCh : ");
			String PlayCh = bf.readLine();
			if(PlayCh.equals("1")){ // new world
				List.List_P_M(PlayCh);
				Main();
			}else if(PlayCh.equals("2")){ // save
				List.List_P_M(PlayCh);
				Main();
			}else if(PlayCh.equals("3")){ // exit
				Exit();
				return;
			}else{
				System.out.println("RE");
			}
		}
	}


	public void Main() throws IOException{ // 선택 후 계속 보일 메뉴
		State State = new State(); // 정보창
		Adventure Adventure =  new Adventure(); // 모험 및 전투
		Point Point =  new Point(); // 스탯분배
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		while(true){
			System.out.print("\n\n1.State\n2.Adventure\n3.Point\n4.Exit\nCh : ");
			String MainCh = bf.readLine();
			if(MainCh.equals("1")){
				State.State();
			}else if(MainCh.equals("2")){
				Adventure.Adventure();
			}else if(MainCh.equals("3")){
				Point.Point();
			}else if(MainCh.equals("4")){
				Exit();
				return;
			}else{
				System.out.println("RE");
			}
		}
	}



	static void Exit(){ // 종료시 저장
		File player = new File("C:/Users/user/Desktop/js 공부/Player.txt");
		String result = List_P_M.Playerchoice.get(0);
		for(int i = 1; i < List_P_M.Playerchoice.size(); i++){
			result = result+","+List_P_M.Playerchoice.get(i);
		}
		List_P_M.Playerlist.add(result);
			try{
				FileWriter fw = new FileWriter(player, false);
				for(int i = 0; i < List_P_M.Playerlist.size(); i++){
					fw.write(List_P_M.Playerlist.get(i)+"\n");
				}
				fw.close();
			} catch (Exception e){
				e.getStackTrace();
			}
			System.out.println("Save Success");
	}
}

선택을 해야하는 경우의 메소드들을 한 클래스 안에 모아놨어요.

(시작메뉴 , 플레이어 선택 , 메인메뉴 , 종료시) 등 

 

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class List_P_M {
	 static ArrayList<String> Playerlist = new ArrayList<String>(); //save된 모든 플레이어 목록
	  static ArrayList<String> Playerchoice = new ArrayList<String>(); // 선택한 플레이어의 정보
	  static ArrayList<String> Monsterlist = new ArrayList<String>(); // 몬스터 목록
	public List_P_M(){

	}

	public String List_P_M(String Ch) throws IOException{
		Monster();
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		String result = "";
		File player = new File("C:/Users/user/Desktop/js 공부/Player.txt");
		if(Ch.equals("1")){
			System.out.println("Player Name : ");
			String name = bf.readLine();
			String LV = "1";
			String Exp = "50";
			String Hp = "100";
			String Atk = "10";
			String Def = "10";
			String money = "0";
			String point = "0";
			Playerlist.add(name+","+LV+","+Exp+","+Hp+","+Atk+","+Def+","+money+","+point);
			try{
				FileWriter fw = new FileWriter(player, true);
				fw.write("\n"+name);
				fw.write(","+LV);
				fw.write(","+Exp);
				fw.write(","+Hp);
				fw.write(","+Atk);
				fw.write(","+Def);
				fw.write(","+money);
				fw.write(","+point);
				fw.close();
			} catch (Exception e){
				e.getStackTrace();
			}
			String str[] = Playerlist.get(0).split(",");
			System.out.println("Name : "+str[0]);
			System.out.println("Lv : "+str[1]);
			System.out.println("Exp : "+str[2]);
			System.out.println("Hp : "+str[3]);
			System.out.println("ATK : "+str[4]);
			System.out.println("DEF : "+str[5]);
			System.out.println("Money : "+str[6]);
			System.out.print("Point : "+str[7]);
			for(int i = 0; i < str.length; i++){ // 선택한 플레이어 저장
				Playerchoice.add(str[i]);
			}
			result = "1";
			return result;
		}else{
			try{
				if(checkBeforeFile(player)){
			        //FileReader를 인자로 하는 BufferedReader 객체 생성
			        BufferedReader br = new BufferedReader(new FileReader(player));
					BufferedReader brr = new BufferedReader(new FileReader(player));
			        //파일을 한 문장씩 읽어온다.
			        String str[] = br.readLine().split(","); // 스탯을 위해 잘라줌
			        Playerlist.add(brr.readLine());
			        int count = 0;
			        //EOF는 null문자를 포함하고 있다.
			        while(str[0] != null){
			          //읽은 문자열을 출력한다.
			          System.out.println((count+1)+". "+str[0]);
			          //다음 문자열을 가르켜준다.
			          str = br.readLine().split(",");
			          Playerlist.add(brr.readLine());
			          count++;
			        }
					//FileReader와는 다르게 사용 후 꼭 닫아주어야 한다.
			        br.close();
			      }else{
			        System.out.println("error");
			      }
			} catch (NullPointerException e){
				e.getStackTrace();
			} catch (FileNotFoundException e){
				e.getStackTrace();
			} catch (IOException e){
				e.getStackTrace();
			}
			System.out.print("\nCh : ");
			String PlayerCh = bf.readLine();
			int CK = CKtrue(PlayerCh);
			while(true){
				if(CK == 0 || CK > Playerlist.size()){
					System.out.println("RE\n");
					System.out.print("\nCh : ");
					PlayerCh = bf.readLine();
					CK = CKtrue(PlayerCh);
				}else{
					break;
				}
			}


			String str[] = Playerlist.get((CK-1)).split(",");
			System.out.println("Name : "+str[0]);
			System.out.println("Lv : "+str[1]);
			System.out.println("Exp : "+str[2]);
			System.out.println("Hp : "+str[3]);
			System.out.println("ATK : "+str[4]);
			System.out.println("DEF : "+str[5]);
			System.out.println("Money : "+str[6]);
			System.out.print("Point : "+str[7]);
			for(int i = 0; i < str.length; i++){ // 선택한 플레이어 저장
				Playerchoice.add(str[i]);
			}
			Playerlist.remove(CK-1);
			result = "1";
			return result;
		}
	}


	static void Monster(){ // 몬스터 목록 불러오기
		File Monster = new File("C:/Users/user/Desktop/js 공부/Monster.txt");
		try{
	        BufferedReader br = new BufferedReader(new FileReader(Monster));
	        String CK = br.readLine();
	        while(CK != null){
	        	Monsterlist.add(CK);
	        	CK = br.readLine();
	        }
	        br.close();
		} catch (NullPointerException e){
			e.getStackTrace();
		} catch (FileNotFoundException e){
			e.getStackTrace();
		} catch (IOException e){
			e.getStackTrace();
		}
	}


	static int CKtrue(String Ch){ // 문자열 및 없는 플레이어 번호 선택 시
		int CK = 0;
		try{
			int ck = Integer.parseInt(Ch);
			CK = ck;
			if(CK > Playerlist.size()){
				CK = 0;
			}else if(CK == 0){
				CK = 0;
			}else if(CK <= Playerlist.size()){
				return CK;
			}
		} catch(NumberFormatException e){
			CK = 0;
		}
		return CK;
	}



	static boolean checkBeforeFile(File file){ //파일 여부 확인
	    //파일이 존재하고
	    if(file.exists()){
	    	//그 파일이 파일이고, 읽을 수 있다면 true를 리턴한다.
	      if(file.isFile() && file.canRead()){
	        return true;
	      }
	    }
	    return false;
	}
}

새로운 플레이어 생성과 저장된 플레이어 불러오기 , 몬스터 불러오기 등

메모장에서 읽어와서 ArrayList에 저장하는 클래스입니다.

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;

public class Adventure {

	public Adventure(){

	}

	public void Adventure() throws IOException{

		for(int i = 0; i < 3; i++){
			try { // 찾는중을 표현하기 위한 지연함수
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if(i == 2){
				System.out.println("!!!");
			}else{
				System.out.print("...");
			}
		}
		Random rd = new Random(); // 몬스터를 랜덤으로 선택하기 위한 랜덤함수
		int MonsterSize = List_P_M.Monsterlist.size();
		int MonsterCK = rd.nextInt(MonsterSize);
		String MonsterName[] = List_P_M.Monsterlist.get(MonsterCK).split(",");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("Name : ["+MonsterName[0]+"] Lv : ["+MonsterName[1]+"] Fight!!");
		String result = String.valueOf(MonsterCK);
		Battle(result);
	}


	public void Battle(String Ch) throws IOException{ // 전투 메소드
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		int CK = Integer.parseInt(Ch);

		System.out.print("\n1.Fight\n2.Run\nCh : ");
		String F_Ch = bf.readLine();
		if(F_Ch.endsWith("1")){
			String MonsterState[] = List_P_M.Monsterlist.get(CK).split(",");

			int PlayerHp = Integer.parseInt(List_P_M.Playerchoice.get(3));
			int PlayerAtk = Integer.parseInt(List_P_M.Playerchoice.get(4));
			int PlayerDef = Integer.parseInt(List_P_M.Playerchoice.get(5));

			int MonsterHp = Integer.parseInt(MonsterState[3]);
			int MonsterAtk = Integer.parseInt(MonsterState[4]);
			int MonsterDef = Integer.parseInt(MonsterState[5]);

			while(true){
				System.out.println(List_P_M.Playerchoice.get(0)+" Hp["+PlayerHp+"]");
				System.out.println(MonsterState[0]+" Hp["+MonsterHp+"]");
				Random rd = new Random();

				int P_Atk_Rd = rd.nextInt(PlayerAtk)+1;
				int P_Def_Rd = rd.nextInt(PlayerDef)+1;
				System.out.print("\n1.Atk\n2.Def\nCh : ");
				String P_Ch = bf.readLine();

				int M_Atk_Rd = rd.nextInt(MonsterAtk)+1;
				int M_Def_Rd = rd.nextInt(MonsterDef)+1;
				int M_Ch = rd.nextInt(2)+1; // 자동전투를 위한 공격&방어

				if(P_Ch.equals("1") && M_Ch == 1){ // 둘다 공격일때
					System.out.println(List_P_M.Playerchoice.get(0)+" Atk["+P_Atk_Rd+"]!!");
					System.out.println(MonsterState[0]+" Atk["+M_Atk_Rd+"]!!");
					PlayerHp -= M_Atk_Rd ;
					MonsterHp -= P_Atk_Rd;
				}else if(P_Ch.equals("1") && M_Ch == 2){ // 플레이어는 공격이고 몬스터는 방어일때
					System.out.println(List_P_M.Playerchoice.get(0)+" Atk["+P_Atk_Rd+"]!!");
					System.out.println(MonsterState[0]+" Def["+M_Def_Rd+"]!!");
					if(P_Atk_Rd <= M_Def_Rd){
						System.out.println(MonsterState[0]+" Defense!");
						System.out.println(MonsterState[0]+" CounterAttack!");
						PlayerHp -= M_Def_Rd - P_Atk_Rd;
						MonsterHp -= P_Atk_Rd/2;
					}else{
						System.out.println(MonsterState[0]+" Defense Fall..");
						MonsterHp -= P_Atk_Rd - M_Def_Rd;
					}
				}else if(P_Ch.equals("2") && M_Ch == 1){ // 몬스터는 공격이고 플레이어는 방어일때
					System.out.println(List_P_M.Playerchoice.get(0)+" Def["+P_Def_Rd+"]!!");
					System.out.println(MonsterState[0]+" Atk["+M_Atk_Rd+"]!!");
					if(M_Atk_Rd <= P_Def_Rd){
						System.out.println(List_P_M.Playerchoice.get(0)+" Defense!");
						System.out.println(List_P_M.Playerchoice.get(0)+" CounterAttack!");
						MonsterHp -= P_Def_Rd - M_Atk_Rd;
						PlayerHp -= M_Atk_Rd/2;
					}else{
						System.out.println(List_P_M.Playerchoice.get(0)+" Defense Fall..");
						PlayerHp -= M_Atk_Rd - P_Def_Rd;
					}
				}else if(P_Ch.equals("2") && M_Ch == 2){ // 둘다 방어일때
					System.out.println(List_P_M.Playerchoice.get(0)+" Atk["+P_Def_Rd+"]!!");
					System.out.println(MonsterState[0]+" Atk["+M_Def_Rd+"]!!");
					System.out.println("Drow..");
				}else{
					System.out.println("RE");
				}
				if(PlayerHp <= 0){
					System.out.println(MonsterState[0]+" Win!");
					return;
				}else if(MonsterHp <= 0){
					System.out.println(List_P_M.Playerchoice.get(0)+" Win!");
					Exp ex = new Exp();
					ArrayList<String> result = ex.Exp_1(List_P_M.Playerchoice.get(1),List_P_M.Playerchoice.get(2),MonsterState[2],List_P_M.Playerchoice.get(6),MonsterState[6]);
					if(result.get(0).equals("1")){
						List_P_M.Playerchoice.set(1, result.get(2)); // LV UP
						List_P_M.Playerchoice.set(2, result.get(1)); // EXP
						List_P_M.Playerchoice.set(6, result.get(3)); // Money
						List_P_M.Playerchoice.set(7, result.get(4)); // Point
					}else{
						List_P_M.Playerchoice.set(2, result.get(1)); // EXP
						List_P_M.Playerchoice.set(6, result.get(2)); // Money
					}
					return;
				}
			}
		}else if(F_Ch.equals("2")){
			return;
		}else{
			System.out.println("RE");
		}
	}


}

모험을 선택시 전투를 하는 클래스입니다.

 

import java.util.ArrayList;

public class Exp {
	static int total = 0;
	static int P_exp = 0;
	static String result = "";
	static int Lv = 0;
	static int money = 0;
	static String point = "5";

	public Exp(){

	}

	public static ArrayList<String> Exp_1(String LV, String Exp , String M_Exp , String Money , String M_Money){
		P_exp = Integer.parseInt(Exp) + Integer.parseInt(M_Exp);
		money = Integer.parseInt(Money) + Integer.parseInt(M_Money);
//		System.out.println("LV : " + LV);
//		System.out.println("EXP : " + Exp);
//		System.out.println("M_Exp " + M_Exp);
		ArrayList<String> P_Ex = new ArrayList<String>();
		int exp = 25*Integer.parseInt(LV);
		total = 0;
		if(exp <= P_exp){
			total = P_exp - exp;
			Lv = Integer.parseInt(LV)+1;
			System.out.println("\nLV UP!!");
			result = "1";
			P_Ex.add(result);
			P_Ex.add(Integer.toString(total));
			P_Ex.add(Integer.toString(Lv));
			P_Ex.add(Integer.toString(money));
			P_Ex.add(point);
			return P_Ex;
		}else{
			result = "2";
			P_Ex.add(result);
			P_Ex.add(Integer.toString(P_exp));
			P_Ex.add(Integer.toString(money));
			return P_Ex;

		}
	}
}

전투를 이겼을 경우 경험치 , 돈 을 얻어 레벨업을 하는 클래스입니다.

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Point{


	public void Point() throws IOException{
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
			int Point = Integer.parseInt(List_P_M.Playerchoice.get(7));
		while(true){
			if(Point == 0){
				System.out.println("Point Null!");
				List_P_M.Playerchoice.set(7, Integer.toString(Point));
				return;
			}
			System.out.print("Point : "+Point+"\n1.Hp(+5)\n2.Atk(+2)\n3.Def(+2)\n4.Exit\nCh : ");
			String Ch = bf.readLine();
			if(Ch.equals("1")){
				int Hp = Integer.parseInt(List_P_M.Playerchoice.get(3));
				Hp += 5;
				System.out.println("\n\nHp : "+List_P_M.Playerchoice.get(3)+" -> Hp : "+Hp);
				List_P_M.Playerchoice.set(3, Integer.toString(Hp));
				Point--;
			}else if(Ch.equals("2")){
				int Atk = Integer.parseInt(List_P_M.Playerchoice.get(4));
				Atk += 2;
				System.out.println("\n\nAtk : "+List_P_M.Playerchoice.get(4)+" -> Atk : "+Atk);
				List_P_M.Playerchoice.set(4, Integer.toString(Atk));
				Point--;
			}else if(Ch.equals("3")){
				int Def = Integer.parseInt(List_P_M.Playerchoice.get(5));
				Def += 2;
				System.out.println("\n\nDef : "+List_P_M.Playerchoice.get(5)+" -> Def : "+Def);
				List_P_M.Playerchoice.set(5, Integer.toString(Def));
				Point--;
			}else if(Ch.equals("4")){
				System.out.println("RE Main");
				return;
			}else{
				System.out.println("RE");
			}
		}
	}

}

레벨업을 해서 얻은 포인트로 스탯을 올릴 수 있는 클래스 입니다. (새로추가!)

 

public class State {
	public State(){

	}

	public void State(){
		System.out.println("\n\nName : "+List_P_M.Playerchoice.get(0));
		System.out.println("Lv : "+List_P_M.Playerchoice.get(1));
		System.out.println("Exp : "+List_P_M.Playerchoice.get(2));
		System.out.println("Hp : "+List_P_M.Playerchoice.get(3));
		System.out.println("ATK : "+List_P_M.Playerchoice.get(4));
		System.out.println("DEF : "+List_P_M.Playerchoice.get(5));
		System.out.println("Money : "+List_P_M.Playerchoice.get(6));
		System.out.print("Point : "+List_P_M.Playerchoice.get(7));
		}
	}

현재 플레이어 정보창을 보여주는 클래스입니다.

 

 

 

메인 클래스가 너무 지저분해서 비슷한 메소들끼리 묶어서 클래스화 했는데 코드가 적어서 그런지 금방했네요.

 

클래스로 바꾼 이유는 보기도 지저분하고 아무리 주석으로 설명을 써놨어도 에러부분을 찾기 어렵더라구요.

지금이야 코드가 적으니 금방 찾아냈지만 앞으로 만들다보면 메인 클래스 하나에서 찾아다니기 힘들거같아서..ㅎ

 

처음에는 일기장 처럼 저혼자 볼생각으로 만들었는데 다른분들이 보러오셔서 구경하시고 피드백도 해주시면 괜찮을거같아 말투?도 바꿨어요.

 

캡쳐로 남기는 방식은 나중에 제가 다시볼때도 좋은거같지는 않아서 검색해보니 코드블럭이란것도 있더라구요.

나중에 보기도 훨씬 좋아진거같아 오늘은 뭔가 기분이 좋네요.

 

SNS에 돌아다니는 글을보면 코딩은 조건과 반복이 끝이다 라고 했는데 저는 정말 조건과 반복만 사용하고있어서 허허;;

 

내일은 레벨별 사냥터? 모험구역을 만들어볼까 합니다.