마무리 1차 수정- MySQL연동

Main

Main.class

package main;

import java.util.*;


import character.CharacterDate;
import character.CharacterVO;
import monster.MonsterVO;
import sql.Test;
import monster.MonsterDate;
import user.Login;

import user.Login;
import user.Register;
import user.UserDateSet;
public class Main {
	 static Scanner sc = new Scanner(System.in);
	 static String name;
	public static void main(String[] args) {
		UserDateSet.userListSet();
		System.out.println("천규`s Game에 오신걸 환영합니다");
		String n = input("회원이시면 1번 아니시면 2번을 입력해주세요");
		if(n.equals("1")) {
			Login.login();
		}
		else {
			Register.register();
			Login.login();
		}
		CharacterDate.characterlistset();
		MonsterDate.Monsterlistset();
		SelectCharacter();
		while(true){
			System.out.println("=======원하는 메뉴를 선택해주세요 ======");
			String a =input("1. 전투 2.케릭터 정보 창 3.케릭터 선택 창 4. 회복 5.저장, 6.로그아웃 : ");
			if(a.equals("1")) Fight();
			if(a.equals("2")) System.out.println(CharacterDate.characterlist.get(name));
			if(a.equals("3")) SelectCharacter();
			if(a.equals("4")) Heal();
			if(a.equals("5")) sql.Test.savaDate(name); 
			if(a.equals("6")) {
				System.out.println("게임이 종료되었습니다");
				break;
			}
		}
		
		
		
		
		
	}
	//전투
	
	public static void Fight() {
		
		CharacterVO ch_vo = CharacterDate.characterlist.get(name); //ch_vo에 해당 케릭터 정보 대입
		MonsterVO mn_vo = MonsterDate.MonsterList.get(rd(2)); // mn_vo에 랜덤 몬스터 정보 대입
		//몬스터를 만났다고 가정
		System.out.println(name+"이 "+mn_vo.getName() +" 를 만났습니다.");
		int mn_hp = mn_vo.getHp();
		while(true) {
			int ch_hp = ch_vo.getHp();
			
			ch_hp-=mn_vo.getPower();
			mn_hp-=ch_vo.getPower();
			ch_vo.setHp(ch_hp);
			System.out.println(name+"가 "+mn_vo.getPower()+"의 피해를 입었습니다.");
			System.out.println(name+" 남은 hp는 "+ch_hp+ "입니다");
			System.out.println(mn_vo.getName()+"가 "+ch_vo.getPower()+"의 피해를 입었습니다.");
			System.out.println(mn_vo.getName()+" 남은 hp는 "+mn_hp+ "입니다");
			
			if(ch_hp <0) {
				System.out.println("전투에서 패 하셨습니다.");
				break;
			}
			else if(mn_hp<0) {
				System.out.println("전투에서 승리 하셨습니다." +mn_vo.getExp()+"의 경험치를 획득하였습니다.");
				ch_vo.setExp(ch_vo.getExp()+mn_vo.getExp());
				if(ch_vo.getExp() >=100) {
					ch_vo.setLevel(ch_vo.getLevel()+1);
					System.out.println("레벨업!");
				}
				ch_vo.setGold(ch_vo.getGold()+mn_vo.getGold());
				break;
			}
	
		}
	
	

	// 케릭터 선택 창
	}
	public static void SelectCharacter() {
		String a = input("케릭터 접속은 1번 신규 케릭터 생성은 2번을 입력해주세요. : ");
		if(a.equals("1"))
		{
			System.out.println("==========케릭터 선택 창입니다.===========");
			System.out.println("==========케릭터 목록 입니다.===========");
			Test.showDate();
	        System.out.println();
	        
	        while(true) {
				String ch_name = input("원하시는 케릭터를 이름을 입력 해주세요 : ");
				if(!Test.ch_name.contains(ch_name)) {
					System.out.println("존재하지 않는 케릭터입니다 다시 입력해주세요");
				}
				else {
					System.out.println(ch_name+ " 케릭터에 접속 하였습니다");
					name = ch_name;
					Test.SetDate(name);
					break;
				}	
			}
		}
		else if(a.equals("2")) {
			
			String newName = input("케릭터 이름을 입력해주세요 : ");
			if(Test.ch_name.contains(newName)){
				input("이미 있는 이름입니다 다시 입력해주세요 : ");
				}
			else {
				Test.makeCharacter(newName);
				SelectCharacter();
			}
		}
		else {
			input(" 잘못 입력하셨습니다. 다시 입력해주세요 : ");
		}
		
	
	}
	
	//체력 회복 부분
	public static void Heal() {
		
		CharacterVO ch_vo = CharacterDate.characterlist.get(name);
		if(ch_vo.getGold()>=3) {
			System.out.println("hp가 회복되었습니다 hp  : "+ch_vo.getHp());
			ch_vo.setHp(ch_vo.getHp()+10);
			ch_vo.setGold(ch_vo.getGold()-3);
		}
		else System.out.println("골드가 부족합니다.");
		
	}
	//몬스터 랜덤 난수 발생
	public static String rd(int n) {
		Random random = new Random();
		return Integer.toString(random.nextInt(n)+1);
	}
	
	//입출력 함수
	public static String input(String meg) {
		System.out.print(meg);
		return sc.next();
	}
}

Character

CharacterVO

package character;

public class CharacterVO {

	private String name;
	private int hp;
	private int power;
	private int exp;
	private int gold;
	private int level;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getHp() {
		return hp;
	}
	public void setHp(int hp) {
		this.hp = hp;
	}
	public int getPower() {
		return power;
	}
	public void setPower(int power) {
		this.power = power;
	}
	public int getExp() {
		return exp;
	}
	public void setExp(int exp) {
		this.exp = exp;
	}
	public int getGold() {
		return gold;
	}
	public void setGold(int gold) {
		this.gold = gold;
	}
	public int getLevel() {
		return level;
	}
	public void setLevel(int level) {
		this.level = level;
	}
	
	public CharacterVO(String name, int hp, int power, int exp, int gold, int level) {
		super();
		this.name = name;
		this.hp = hp;
		this.power = power;
		this.exp = exp;
		this.gold = gold;
		this.level = level;
	}
	@Override
	public String toString() {
		return " [닉네임=" + name + "]"+"hp = "+hp+ " gold = "+gold+" level = "+level;
	}
	
	
	
	
}


CharacterDate


package character;
import java.util.*;
public class CharacterDate {

	public static HashMap<String, CharacterVO> characterlist =  new HashMap<>();
	
	public static void characterlistset() {
	}
	
}

Monster

MonsterVO


package monster;

public class MonsterVO {
	

	private String name;
	private int hp;
	private int power;
	private int exp;
	private int gold;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getHp() {
		return hp;
	}
	public void setHp(int hp) {
		this.hp = hp;
	}
	public int getPower() {
		return power;
	}
	public void setPower(int power) {
		this.power = power;
	}
	public int getExp() {
		return exp;
	}
	public void setExp(int exp) {
		this.exp = exp;
	}
	public int getGold() {
		return gold;
	}
	public void setGold(int gold) {
		this.gold = gold;
	}
	
	public MonsterVO(String name, int hp, int power, int exp, int gold) {
		super();
		this.name = name;
		this.hp = hp;
		this.power = power;
		this.exp = exp;
		this.gold = gold;
	}
	
	
}

MonsterDate


package monster;

import java.util.HashMap;

public class MonsterDate {
	
	public static HashMap<String,MonsterVO> MonsterList = new HashMap<>();
	
	
	public static void Monsterlistset() {
		
		MonsterList.put("1", new MonsterVO("고블린",1,1,20,1));
		MonsterList.put("2", new MonsterVO("오크",2,2,40,2));
		MonsterList.put("3",  new MonsterVO("하이오크",3,3,50,3));
	
	
	}
	

}

User

Login


package user;

import main.Main;

public class Login {

	public static void login() {
		
		int cnt = 0;
		
		System.out.println("========= 로그인 창입니다.==========");
		while(true){
			
			String id= Main.input("아이디를 입력해주세요. : ");
		    String password =Main.input("비밀번호를 입력해주세요.: ");
		    if(!UserDateSet.userList.containsKey(id)) System.out.println("존재하지 않는 아이디입니다");
		    else {
		    	
		    
			if(UserDateSet.userList.get(id).getPassword().equals(password)) {
				System.out.println("로그인에 성공하였습니다.");
				break;
			}
			else {
				System.out.println("로그인에 실패하였습니다 다시한번 입력해주세요");
				cnt++;
			}
			if(cnt ==3) {
				System.out.println("로그인에 3번 실패하였습니다. 회원가입창으로 넘어갑니다");
				Register.register();
			}
			
		}
		}
	
		
	}


}

Register


package user;

import main.Main;

public class Register {

	public static  void register() { 
		System.out.println("========= 회원가입 창입니다.==========");
		while(true) {
			String id = Main.input("아이디를 입력해주세요. : ");
			if(UserDateSet.userList.containsKey(id)) {
				System.out.println("이미 사용 중인 아이디 입니다. ");
				continue;
			}
			else {
				String password = Main.input("비밀번호를 입력해주세요. : ");
				System.out.println("회원가입에 성공하셨습니다");
				UserDateSet.userList.put(id,new UserVO(id,password));
				break;
			}
			
		}
	
	}
}

UserVO


package user;

public class UserVO {
	private String id;
	private String password;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
		
		
	}
	public UserVO(String id, String password) {
		super();
		this.id = id;
		this.password = password;
	}
	
	
	
}

UserDateSet


package user;

import java.util.*;
public class UserDateSet {
	
	public static HashMap<String,UserVO> userList = new HashMap<>();

	public static void userListSet() {
		
		userList.put("1", new UserVO("1","1"));
		userList.put("2", new UserVO("2","2"));
		userList.put("3", new UserVO("3","3"));
		
	}


}

Sql클래스

package sql;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;

import character.CharacterDate;
import character.CharacterVO;
public class Sql {

	static Connection con =null; //커넥터 설정
	static Statement stmt = null;
	static ResultSet rs = null; 
	static String className ="com.mysql.cj.jdbc.Driver";
	static String url = "jdbc:mysql://localhost:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=euckr";
	static String user = "root";
	static String passwd ="sangmi517!";
	public static ArrayList<String> ch_name = new ArrayList<>();
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		CharacterDate.characterlistset();
		showDate();
		
		
}
	
    //데이터를 characterList에 저장시키기
	public static void SetDate(String name) {

		try {
				Class.forName(className);
				con = DriverManager.getConnection(url, user, passwd);
				System.out.println("Connect Success!");
				stmt = con.createStatement();
				rs = stmt.executeQuery("select * from ch_tb where name ='"+name+"'");
				while(rs.next()) {
					CharacterDate.characterlist.put(name,new CharacterVO(rs.getString("name"),rs.getInt("hp"),rs.getInt("power"),rs.getInt("exp"),rs.getInt("gold"),rs.getInt("level")));
				}
		}catch(Exception e) {
			System.out.println("Connect Failed");
			e.printStackTrace();
		} finally {
					try {
						   if(con != null && !con.isClosed()) {
							   	con.close();
						   }
				    } catch(Exception e) {
					e.getStackTrace();
				       }
		}
	}
	// 케릭터 선택 창에서 db에 있는 케릭터 보여주기
	public static void showDate() {

		try {
			Class.forName(className);
			con = DriverManager.getConnection(url, user, passwd);
			System.out.println("Connect Success!");
			stmt = con.createStatement();
			rs = stmt.executeQuery("select name,level from ch_tb" );
			while(rs.next()) {
			ch_name.add(rs.getString(1));
			System.out.println("닉네임 : "+"["+rs.getNString(1)+"] "+" 레벨 : " +"["+rs.getString(2)+"]");
			}
		
		}catch(Exception e) {
			System.out.println("Connect Failed");
			e.printStackTrace();
		} finally {
					try {
						   if(con != null && !con.isClosed()) {
							   	con.close();
						   }
				} catch(Exception e) {
					e.getStackTrace();
				}
		}
	}
	
    //게임 진행 후 바뀐 케릭터 정보를 db에 올림
    
	public static void savaDate(String name) {
		
		try {
			CharacterVO vo = CharacterDate.characterlist.get(name);
			Class.forName(className);
			con = DriverManager.getConnection(url, user, passwd);
			System.out.println("Connect Success!");
			
			stmt = con.createStatement();
			stmt.executeUpdate("update ch_tb set name ='"+name+"', hp="+vo.getHp()+",power = "
					+vo.getPower()+",exp = "+vo.getExp()+",gold ="+vo.getGold()+",level = "+vo.getLevel()+" where name ='"+name+"'" );
		
		}catch(Exception e) {
			System.out.println("Connect Failed");
			e.printStackTrace();
		} finally {
					try {
						   if(con != null && !con.isClosed()) {
							   	con.close();
						   }
				} catch(Exception e) {
					e.getStackTrace();
				}
		}	
	}

// 케릭터 추가하기

	public static void makeCharacter(String name) {
		
		try {
			Class.forName(className);
			con = DriverManager.getConnection(url, user, passwd);
			System.out.println("Connect Success!");
			stmt = con.createStatement();
			stmt.executeUpdate("insert into ch_tb (name) value('"+name+"')");
			rs = stmt.executeQuery("select * from ch_tb where name = '"+name+"'");
			System.out.println("넘어갔습니당");
			while(rs.next()) {
				CharacterDate.characterlist.put(name,new CharacterVO(rs.getString("name"),rs.getInt("hp"),rs.getInt("power"),rs.getInt("exp"),rs.getInt("gold"),rs.getInt("level")));
			}
	}catch(Exception e) {
		System.out.println("Connect Failed");
		e.printStackTrace();
	} finally {
				try {
					   if(con != null && !con.isClosed()) {
						   	con.close();
					   }
			    } catch(Exception e) {
				e.getStackTrace();
			       }
	}
		
		
		
	}
}

앞으로 추가 해야 할 것

  1. db연동해서 데이터 저장기능 넣기(완성)
  2. 케릭터 추가 기능 넣기(완성)
  3. db 연동 부분 간략하게 하기

좋은 웹페이지 즐겨찾기