JAVA 프로젝트 (1) : 테니스 계수기 프로그램

yy9356·2022년 1월 14일
0

JAVA

목록 보기
1/2

1. 테니스 계수기

- 테니스 규칙?

나의 역할?
팀 이름 : 다형성


- print (화면) 출력

package TenisProject;

import java.util.ArrayList;

class Print {
	public static void printMain() {

		System.out.println("====================================");
		System.out.println("                                        테니스 게임");
		System.out.println("====================================");
		System.out.println("                                                           Made by 다형성 ");
		System.out.println();
		System.out.println("\t1. 게임 시작");
		System.out.println("\t2. 새로운 플레이어 리스트 작성");
		System.out.println("\t3. 종료");
		System.out.print("\n\t입력 : ");
	}

	public static void printRuleSelect() {
		System.out.println("\n\n\n\n\n\n\n\n");
		System.out.println("===========================");
		System.out.println("                       경기 규칙을 선택해주세요!");
		System.out.println("===========================");
	}

	public static void printScoreBoard(ArrayList<Player> team1, ArrayList<Player> team2, 
			MatchPoint t1, MatchPoint t2) {

		String[] scores = {"00", "15", "30", "40", "Win"};
		System.out.println("\n----------------------------------------------------------------------------");
		if(team1.size() == 1) System.out.println("\t\t\t\tSCORE\tGAME \tSET");
		else System.out.println("\t\t\t\t\tSCORE\tGAME \tSET");
		System.out.println("----------------------------------------------------------------------------");

		if(team1.size() == 1) System.out.printf("\tA조 %s\t", team1.get(0).getName() );
		else System.out.printf("\tA조 %s,%s\t", team1.get(0).getName(), team1.get(1).getName()); 

		System.out.printf("\t%s\t\t%02d\t\t%02d\t 듀스:%d\n", scores[t1.getScore()], t1.getGame(), t1.getSet(), t1.getDeuceScore()); 

		if(team2.size() == 1) System.out.printf("\tB조 %s\t", team2.get(0).getName() );
		else System.out.printf("\tB조 %s,%s\t", team2.get(0).getName(), team2.get(1).getName()); 

		System.out.printf("\t%s\t\t%02d\t\t%02d\t 듀스:%d\n", scores[t2.getScore()], t2.getGame(), t2.getSet(), t2.getDeuceScore()); 
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	

	public static void printPlayerNumberCheck(String gender, int size, int i) {
		if(size < i) {
			System.out.printf("현재 선수목록에 %s선수가 %d명밖에 존재하지  않습니다.\n", gender, size);
			System.out.println("프로그램 시작 메뉴에서 선수를 추가해주세요!");
			System.exit(0);
		}
	}
}

- 팀 선택 출력

package TenisProject;

import java.util.ArrayList;
import java.util.Scanner;

class TeamSelection{

	public static int teamDataInput(int rule, 
			ArrayList<Player> players, 
			ArrayList<Player> team1, ArrayList<Player> team2) {

		Scanner scanner = new Scanner(System.in);

		String gender = "";
		String input = "";

		if(rule == 1) {	//단식 선택
			boolean flag = false;
			do {
				if(flag == true) System.out.println("잘못 선택하셨습니다.");
				Print.printRuleSelect();
				System.out.print("\t\t1. 남성 단식 / 2. 여성 단식\n선택 : ");
				input = scanner.next();
			} while (flag = !((input+"").matches("[1-2]")));
			rule = Integer.valueOf(input);

			gender = (rule == 1) ? "남자" : "여자";
			FileManager.readTennisMember(players, gender);
			Print.printPlayerNumberCheck(gender, players.size(), 2);

			System.out.println("\n\n\n\n1 팀원 선택");
			teamSelect(players, gender, team1);
			System.out.println("\n\n\n\n2 팀원 선택" );
			teamSelect(players, gender, team2);

		}else if(rule == 2){
			boolean flag = false;
			do {
				if(flag == true) System.out.println("잘못 선택하셨습니다.");
				Print.printRuleSelect();
				System.out.print("\t1. 남성 복식 / 2. 여성 복식 / 3. 혼합 복식\n선택 : ");
				input = scanner.next();
			} while (flag = !((input+"").matches("[1-3]")));
			rule = Integer.valueOf(input);

			if(rule == 1 || rule == 2) {
				gender = (rule == 1) ? "남자" : "여자";

				FileManager.readTennisMember(players, gender);
				Print.printPlayerNumberCheck(gender, players.size(), 4);
				System.out.println("\n\n\n\n1 팀원 선택");
				teamSelect(players, gender, team1);
				teamSelect(players, gender, team1);

				System.out.println("\n\n\n\n\n2 팀원 선택");
				teamSelect(players, gender, team2);
				teamSelect(players, gender, team2);

			}else if(rule == 3) {
				gender = "남자";
				FileManager.readTennisMember(players, gender);
				Print.printPlayerNumberCheck(gender, players.size(), 2);
				System.out.println("\n\n\n\n1 팀 남성 선택");
				teamSelect(players, gender, team1);
				System.out.println("\n\n\n\n\n2팀 남성 선택");
				teamSelect(players, gender, team2);

				System.out.println();

				gender = "여자";
				FileManager.readTennisMember(players, gender);
				Print.printPlayerNumberCheck(gender, players.size(), 2);
				System.out.println("\n\n\n\n1 팀 여성 선택");
				teamSelect(players, gender, team1);
				System.out.println("\n\n\n\n\n2 팀 여성 선택");
				teamSelect(players, gender, team2);
			}
		}

		System.out.println("1팀 : " + team1);
		System.out.println("2팀 : " + team2);

		//남성단식, 남성복식일때 5세트, 여성 참가시 3세트
		return (rule == 1) ? 5 : 3;
	}



	private static Player selectList(ArrayList<Player> players, int select) {
		return players.remove(select-1);
	}

	private static void teamSelect(ArrayList<Player> players, String gender, ArrayList<Player> team) {
		Scanner scanner = new Scanner(System.in);

		String input = "";
		boolean flag = false;
		int playersSize = players.size();
		String regex = String.format("[1-%d]", playersSize);
		do {
			if(flag == true) System.out.println("잘못 선택하셨습니다.");
			int idx = 1;
			System.out.println("============");
			for (int i = 0; i < players.size(); i++) {
				if(players.get(i).getGender().equals(gender)) {
					System.out.printf("%d : %s\n", idx++, players.get(i));
				}
			}
			System.out.println("============");
			System.out.print("팀원 선택 : ");
			input = scanner.next();
		} while (flag = !((input+"").matches(regex)));

		int select = Integer.valueOf(input);
		team.add(selectList(players, select));
	}
}

- 플레이어 정보 출력

package TenisProject;

import java.io.Serializable;

class Player implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1425821168775014880L;
	private String name;
	private String gender;

	Player(String name, String gender){
		this.name = name;
		this.gender = gender;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}

	@Override
	public String toString() {
		return this.name + " / " + this.gender;
	}

}

- FileManager 출력

package TenisProject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Scanner;

class FileManager {

	private static final String path = ".\\src\\TenisProject\\tenisMember.txt";

	//반환형 void 변환, 매개변수값 없애고 메서드 내에 경로값 저장해둠
	public static void writeTennisMember() {

		File f=new File(FileManager.path);
		char con='y';
		ArrayList<Player>plist=new ArrayList<Player>();

		do {		
			Scanner scanner=new Scanner(System.in);
			System.out.print("이름 입력 : ");
			String name=scanner.next();
			int genNum = 0;

			boolean flag = false;
			String input = "";
			do {
				if(flag == true) System.out.println("잘못 선택하셨습니다.");
				System.out.print("1. 남성 / 2. 여성\n선택 : ");
				input = scanner.next();
			} while (flag = !(input.matches("[1-2]")));
			genNum = Integer.valueOf(input);
			String gender = (genNum == 1) ? "남자" : "여자";
			plist.add(new Player(name, gender));

			System.out.println("계속할래?");

			try {
				con=(char) System.in.read();
				System.in.skip(System.in.available());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}while(con=='y' );

		//파일생성

		try(FileOutputStream fos=new FileOutputStream(f);
				ObjectOutputStream oos=new ObjectOutputStream(fos);
				) {
			oos.writeObject(plist);	
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//ArrayList를 반환하지 않고, 매개변수로 가져온 ArrayList에 추가하도록 변경
	//성별에 따라 리스트를 가져오도록 하여 매개변수에 gender 추가
	//gender로 입력받은 성별의 Player 객체만 리스트에 추가시킨다.
	public static void readTennisMember(ArrayList<Player> players, String gender)  {
		ArrayList<Player>plist=null;
		players.clear();
		File f = new File(FileManager.path);

		try(FileInputStream fis=new FileInputStream(f);
				ObjectInputStream ois=new ObjectInputStream(fis);
				) {
			plist=(ArrayList<Player>)ois.readObject();
			for (int i = 0; i < plist.size(); i++) {
				if(plist.get(i).getGender().equals(gender)) {
					players.add(plist.get(i));
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}		
	}

	public static void newFile() {

		System.out.println("새로운 플레이어 리스트를 작성하시겠습니까? (y/n)");
		System.out.println("(기존의 리스트는 삭제됩니다)");
		try {
			char con = (char)System.in.read();
			System.in.skip(System.in.available());

			if(Character.toUpperCase(con) == 'Y') {
				FileManager.writeTennisMember();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

- 테니스 규칙 출력

package TenisProject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;

public class TenisGame {

	public static void main(String[] args) {

		ArrayList<Player> players = new ArrayList<>();
		ArrayList<Player> team1 = new ArrayList<>();
		ArrayList<Player> team2 = new ArrayList<>();

		Scanner scanner = new Scanner(System.in);
		int startMenu = 0;
		while(true) {
			Print.printMain();			
			startMenu = scanner.nextInt();

			if(startMenu == 1) break; //게임시작
			else if(startMenu == 2) FileManager.newFile(); //리스트생성
			else if(startMenu == 3) System.exit(0) b //게임종료

		}

		boolean flag = false;
		String input = "";
		do {
			if(flag == true) System.out.println("잘못 선택하셨습니다.");
			Print.printRuleSelect();
			System.out.print("\t\t   1. 단식 / 2. 복식\n선택 : ");
			input = scanner.next();
		} while (flag = !(input.matches("[1-2]")));
		int rule = Integer.valueOf(input);

		int SetValue = TeamSelection.teamDataInput(rule, players, team1, team2);
		int winSet =	(SetValue / 2) + 1;

		MatchPoint t1 = new MatchPoint();
		MatchPoint t2 = new MatchPoint();

		**//여기서부터 로직**
		Random rnd = new Random();

		flag=false;
		do {
			if(flag == true) System.out.println("잘못 선택하셨습니다.");
			Print.printRuleSelect();
			System.out.print("   1. 타이브레이크 적용 / 2. 타이브레이크 미적용\n선택 : ");
			input = scanner.next();
		} while (flag = !(input.matches("[1-2]")));
		boolean tie = false;
		if(input.equals("1")) tie = true; 
		
		
		while (t1.getSet()<winSet && t2.getSet()<winSet) {
			t1.setScore(0); t2.setScore(0);
			t1.setGame(0); t2.setGame(0);
			t1.setDeuceScore(0);t2.setDeuceScore(0);

			while (t1.getGame()<6 && t2.getGame()<6) {
				t1.setScore(0); t2.setScore(0);
				t1.setDeuceScore(0); t2.setDeuceScore(0);
				while (t1.getScore()<4 &&t2.getScore()<4) {
					try {
						Thread.sleep(100);
					}catch (InterruptedException e) {
						e.printStackTrace();
					}
					t1.setDeuceScore(0); t2.setDeuceScore(0);
					
					int n = rnd.nextInt(2);
					if (n==0) t1.plusScore();
					else t2.plusScore();
					Print.printScoreBoard(team1, team2, t1, t2); //★★★★★출력

					if (t1.getScore()==4) {
						t1.plusGame();
						Print.printScoreBoard(team1, team2, t1, t2); //★★★★★출력
						if (t1.getGame()==6) {
							t1.plusSet();
							Print.printScoreBoard(team1, team2, t1, t2); //★★★★★출력
						}
						if (t1.getSet()==winSet) {
							System.out.println("team1 승리");
						}
					}else if (t2.getScore()==4) {
						t2.plusGame();
						Print.printScoreBoard(team1, team2, t1, t2); //★★★★★출력
						if (t2.getGame()==6) {
							t2.plusSet();
							Print.printScoreBoard(team1, team2, t1, t2); //★★★★★출력
						} 
						if (t2.getSet()==winSet) {
							System.out.println("team2 승리");
						}
					}//else if


					**//듀스조건_scoreDeuce**
					if(t1.getScore()==3 && t2.getScore()==3) {
						while (Math.abs(t1.getDeuceScore() - t2.getDeuceScore())<2) {
							n = rnd.nextInt(2);
							if (n==0) {
								t1.plusDeuceScore();
							} else t2.plusDeuceScore();
							Print.printScoreBoard(team1, team2, t1, t2); //★★★★★출력
							if (t1.getDeuceScore()==t2.getDeuceScore()) {
								t1.setDeuceScore(0); t2.setDeuceScore(0);
								Print.printScoreBoard(team1, team2, t1, t2); //★★★★★출력
							}
							if (t1.getDeuceScore() - t2.getDeuceScore() ==2) {
								t1.plusGame();
								t1.setScore(0); t2.setScore(0);
								Print.printScoreBoard(team1, team2, t1, t2); //★★★★★출력
							}else if ( t2.getDeuceScore() - t1.getDeuceScore() ==2) {
								t2.plusGame();
								t1.setScore(0); t2.setScore(0);
								Print.printScoreBoard(team1, team2, t1, t2); //★★★★★출력
							}
						}
					}

					**//듀스조건_gameDuece**
					if (t1.getGame()==5 && t2.getGame()==5) {
						while (Math.abs(t1.getGame()-t2.getGame())<2) {
							t1.setDeuceScore(0); t2.setDeuceScore(0);
							n = rnd.nextInt(2);
							if (n==0) t1.plusScore();
							else t2.plusScore();
							Print.printScoreBoard(team1, team2, t1, t2); //★★★★★출력

							if (t1.getScore()==4) {
								t1.plusGame();
								t1.setScore(0); t2.setScore(0);
								Print.printScoreBoard(team1, team2, t1, t2); //★★★★★출력
							}else if (t2.getScore()==4) {
								t2.plusGame();
								t1.setScore(0); t2.setScore(0);
								Print.printScoreBoard(team1, team2, t1, t2); //★★★★★출력
							}

							if (t1.getGame() - t2.getGame() ==2) {
								t1.plusSet();
								t1.setScore(0); t2.setScore(0);
								t1.setGame(0); t2.setGame(0);
								Print.printScoreBoard(team1, team2, t1, t2); //★★★★★출력
								break;
							}else if ( t2.getGame() - t1.getGame() ==2) {
								t2.plusSet();
								t1.setScore(0); t2.setScore(0);
								t1.setGame(0); t2.setGame(0);
								Print.printScoreBoard(team1, team2, t1, t2); //★★★★★출력
								break;
							}
						}//while

					}//gameDeuce

					**//Tie-Break**
					if (tie) {
						if(t1.getGame()==6 && t2.getGame()==6) {
							t1.setDeuceScore(0); t2.setDeuceScore(0);
							Print.printScoreBoard(team1, team2, t1, t2); //★★★★★출력
							while (t1.getDeuceScore()<7 && t2.getDeuceScore()<7) {
								n = rnd.nextInt(2);
								if (n==0) {
									t1.plusDeuceScore();
								} else {
									t2.plusDeuceScore();
								}
								Print.printScoreBoard(team1, team2, t1, t2); //★★★★★출력
								if (t1.getDeuceScore()==7) {
									t1.plusSet();
									t1.setScore(0); t2.setScore(0);
									t1.setGame(0); t2.setGame(0);
									Print.printScoreBoard(team1, team2, t1, t2); //★★★★★출력
								}else if (t2.getDeuceScore()==7) {
									t2.plusSet();
									t1.setScore(0); t2.setScore(0);
									t1.setGame(0); t2.setGame(0);
									Print.printScoreBoard(team1, team2, t1, t2); //★★★★★출력
								}
							}
						}
					}   

				}//while_score
			}//while_game
		}//while_set
		
	}//main
}//class

- 매치 포인트 출력

package TenisProject;

class MatchPoint {
	private int score;   //기본값 0
	private int game;   //기본값 0
	private int set;   //기본값 0
	private int deuceScore;

	//이겼을 때 점수, 게임, 세트 증가시켜주는 메서드들
	public void plusScore() {
		this.score++;
	}

	public void plusGame() {
		this.game++;
	}

	public void plusSet() {
		this.set++;
	}
	public int getScore() {
		return score;
	}
	public void setScore(int score) {
		this.score = score;
	}
	public int getGame() {
		return game;
	}
	public void setGame(int game) {
		this.game = game;
	}
	public int getSet() {
		return set;
	}
	public void setSet(int set) {
		this.set = set;
	}
	public int getDeuceScore() {
		return deuceScore;
	}
	public void setDeuceScore(int deuceScore) {
		this.deuceScore = deuceScore;
	}
	public void plusDeuceScore() {
		this.deuceScore++;
	}
}

View

profile
§ back-end 공부 중§

0개의 댓글