새소식

Daily Record

5월 10일 학습 내용 정리

 

 

 

GUI 구현 테스트 / 파일 복사

 

1. 파일 복사

 - 텍스트 복사

public class TextCopy {
	public static void main(String[] args) {
		File src = new File("C:/Windows/system.ini"); // 원본파일에 접근할 객체
		File copy = new File("C:/temp/system.txt"); // 복사본
		FileReader reader = null;
		FileWriter writer = null;
		try {
			reader = new FileReader(src);
			writer = new FileWriter(copy);
			while (true) {
				int data = reader.read();
				if (data == -1) {
					break;
				}
				writer.write((char)data);
			}
			System.out.println("파일 복사 완료");
			reader.close(); // reader와 writer를 닫지 않으면 파일은 생성되나 내용이 없음
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

 - 바이너리 복사

public class BinaryCopy {
	public static void main(String[] args) {
		File src = new File("G:/workspace/java/ch10/images/image2.jpg");
		File copy = new File("G:/workspace/java/ch10/images/image2_copy.jpg");
		FileInputStream input = null;
		FileOutputStream output = null;
		try {
			input = new FileInputStream(src);
			output = new FileOutputStream(copy);
			while (true) {
				int data = input.read();
				if (data == -1) break;
				output.write(data);
			}
			input.close();
			output.close();
			System.out.println("파일 복사 완료");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

2. GUI 구현 테스트 - 1부터 100까지의 숫자를 5회 안에 맞추는 게임을 제시된 조건에 맞게 구현

public class NumGameFrame extends JFrame implements ActionListener {

	Container c = getContentPane();

	JPanel pnlNorth = new JPanel();
	JPanel pnlSouth = new JPanel();
	TimeTickingPanel pnlTime = new TimeTickingPanel();
	JTextArea taMessage = new JTextArea();
	JTextField tfInput = new JTextField(6);
	JTextField tfScore = new JTextField(6);
	JTextField tfChance = new JTextField(5);
	JButton btnInput = new JButton("입력");
	JButton btnNewGame = new JButton("새게임");

	String heart = "";
	static long startTime;
	static long endTime;
	long previousScore;
	long currentScore;
	ArrayList<Byte> records = new ArrayList<>();

	NumGameManager manager = NumGameManager.getInstance();

	public NumGameFrame() {
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setTitle("NumGame");
		setSize(450, 250);
		setUI();

		setVisible(true);

		MyThread th = new MyThread();
		th.start();
	}

	private void setUI() {
		MyMouseListener listener = new MyMouseListener();

		tfInput.setEnabled(false);
		btnInput.setEnabled(false);
		tfScore.setEditable(false);
		tfChance.setEditable(false);

		tfInput.addActionListener(this);
		btnInput.addMouseListener(listener);
		btnNewGame.addMouseListener(listener);

		pnlNorth.setBackground(Color.MAGENTA);

		pnlNorth.add(new JLabel("입력:"));
		pnlNorth.add(tfInput);
		pnlNorth.add(btnInput);
		pnlNorth.add(new JLabel("기록:"));
		pnlNorth.add(tfScore);
		pnlNorth.add(btnNewGame);

		taMessage.setFont(new Font("맑은 고딕", Font.BOLD, 20));
		taMessage.setEditable(false);

		pnlTime.setOpaque(true);

		pnlSouth.setBackground(Color.CYAN);
		pnlSouth.add(new JLabel("남은횟수:"));
		pnlSouth.add(tfChance);
		pnlSouth.add(pnlTime);

		c.add(pnlNorth, BorderLayout.NORTH);
		c.add(new JScrollPane(taMessage));
		c.add(pnlSouth, BorderLayout.SOUTH);
	}

	private synchronized void init() {
		manager.initChance();
		taMessage.setText("1부터 100 사이의 숫자를 맞춰보세요. \n");
		manager.setAnswer();
		showHeart();
		tfInput.setEnabled(true);
		btnInput.setEnabled(true);
		tfInput.setText("");
		startTime = System.currentTimeMillis();
		notify();
	}

	private class MyMouseListener extends MouseAdapter {
		public void mouseClicked(MouseEvent e) {
			Object obj = e.getSource();
			if (obj == btnInput || obj == tfInput) {
				setGame();
			} else if (obj == btnNewGame) {
				init();
			}
		}
	}

	public void setGame() {
		String userText = tfInput.getText();
		try {
			int userVal = Integer.parseInt(userText);
			int result = manager.judge(userVal);
			switch (result) {
			case 0:
				taMessage.append("입력한 숫자보다 작습니다. \n");
				checkChance();
				break;
			case 1:
				taMessage.append("입력한 숫자보다 큽니다. \n");
				checkChance();
				break;
			case 2:
				endTime = System.currentTimeMillis();
				long gameTime = endTime - startTime;
				taMessage.append("정답입니다.\n");
				taMessage.append("걸린 시간: " + gameTime);
				tfInput.setEnabled(false);
				btnInput.setEnabled(false);
				showMessage("정답입니다.");
				checkScore();
			}
		} catch (Exception e) {
			taMessage.append("올바른 값이 아닙니다. 숫자를 다시 입력해주세요. \n");
		}
		showHeart();
	}

	public static long[] getGameTime() {
		long[] gameTime = {startTime, endTime};
		return gameTime;
	}

	public void checkScore() {
		String score = manager.setScore();
		switch (score) {
		case "new" :
			tfScore.setText(String.valueOf(manager.getScore()));
			showMessage("새로운 기록 달성");

			records.add((byte)(endTime - startTime));
			String path = System.getProperty("user.dir");
			System.out.println(path);
			FileOutputStream fos = null; 
			try {
				fos = new FileOutputStream(path + "/record.dat");
				for (int i = 0; i < records.size(); i++) {
					fos.write(records.get(i));
				}
				fos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println("저장 완료");
			break;
		case "no update" :
			break;
		}
	}

	private void checkChance() {
		int chance = manager.getChance();
		if (chance == 0) {
			tfInput.setEnabled(false);
			btnInput.setEnabled(false);
			showMessage("기회를 모두 사용하였습니다.");
			return;
		}
	}

	private void showMessage(String text) {
		JOptionPane.showMessageDialog(c, text,
				"Message", JOptionPane.INFORMATION_MESSAGE);
	}

	private void showHeart() {
		heart = "";
		int chance = manager.getChance();
		for (int i = 0; i < chance; i++) {
			heart += "♥";
		}
		System.out.println("남은횟수:" + chance);
		tfChance.setText(heart);
	}
    
	public void actionPerformed(ActionEvent e) {
		setGame();
		repaint();
	}

	public class TimeTickingPanel extends JPanel {

		public TimeTickingPanel() {
			setBackground(Color.YELLOW);
			setSize(100, 30);
		}
        
		protected void paintComponent(Graphics g) {
			super.paintComponent(g);
			g.setColor(Color.GREEN);
			g.fillRect(0, 0, 100, 20);
		}
	}

	class MyThread extends Thread {
		public synchronized void run() {
			while (true) {
				try {
					checkChance();
					if (manager.getChance() == 0) {
						wait();
					}
					Thread.sleep(5000);
					manager.reduceChance();
					showHeart();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static int notifyTime() {
		return 0;
	}

	public static void main(String[] args) {
		new NumGameFrame();
	}
}

 

public class NumGameManager {
	private static int chance = 5;
	private int answer = 0;
	private long score = 30000;
	public final static int LOW = 0;
	public final static int HIGH = 1;
	public final static int CORRECT = 2;
	long[] gameTime = NumGameFrame.getGameTime();

	private static NumGameManager instance = new NumGameManager();

	private NumGameManager() {}

	public static NumGameManager getInstance() {
		return instance;
	}

	public void setAnswer() {
		answer = (int)(Math.random() * 100) + 1;
		System.out.println(answer);
	}

	public int judge(int userVal) {
		--chance;
		if (userVal > answer) {
			return LOW;
		} else if (userVal < answer) {
			return HIGH;
		} 
		return CORRECT;
	}

	public int getChance() {
		return chance;
	}

	public int getAnswer() {
		return answer;
	}

	public long getScore() {
		return score;
	}

	public String setScore() {
		long currentScore = gameTime[1] - gameTime[0];
		if (currentScore < score) {
			score = currentScore;
			return "new";
		} else {
			return "no update";
		}
	}

	public void reduceChance() {
		if (chance == 0) return;
		chance--;
	}

	public void initChance() {
		chance = 5;
	}
}

예상대로 작동하지 않는 기능이 있어 복습이 필요함(JFrame의 Layout, paintComponent, Thread 등)

'Daily Record' 카테고리의 다른 글

5월 12일 학습 내용 정리  (0) 2023.05.13
5월 11일 학습 내용 정리  (0) 2023.05.11
5월 9일 학습 내용 정리  (0) 2023.05.09
5월 8일 학습 내용 정리  (0) 2023.05.08
5월 1주차 학습 내용 정리  (0) 2023.05.07
Contents

Copied URL!

Liked this Posting!