교수님이 쓰라고 하셔서 쓰는 그런데 은근 재밌는 듯

JAVA

[마피아] Message

shinyunha 2025. 12. 2. 00:23

채팅 기능은 걱정과 달리 수월하게 구현되었다. 아마 Server/Client가 이미 구조를 잘 짜뒀기 때문일 것이다. 

 

1. View에서 message를 입력받아 Client로 보낸다. 

inputField.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        JTextField input = (JTextField) e.getSource();
        String inputString = input.getText();
        clientManager.sendMessage("Message:" + inputString);
        System.out.println("뷰에서 메세지 보냄:" + inputString);// 디버그용
        input.setText("");
        input.requestFocus();
    }
});

View

 

2. ClientManager -> ClientThread -> OutputThread -> ServerThread를 거쳐서 CommandManager에 도착하면  CommandManager는 AllChatCommand를 실행한다. AllChatCommand는 받은 message에 보낸 사람 닉네임을 붙여서  BroadCasting한다. 

public class AllChatCommand implements ICommand {
	private CommandManager networkBrain;
	private 사회자 logicBrain;
	public AllChatCommand(CommandManager cm, 사회자 logic) {
		this.networkBrain = cm;
		this.logicBrain=logic;
	}

	@Override
	public void execute(ServerThread sender, String payload, IState currentState) {
		// TODO Auto-generated method stub
		// 토론 상태일 때만 실행됨.
		if(currentState instanceof 토론) {					
			if(sender.getPlayer().is_alive) {
				networkBrain.broadcastAll("Message:"+sender.getPlayer().nickname + ": " + payload);
			} 
		} else {
			sender.sendMessage("채팅은 살아있는 사람만 토론 상태에서만 할 수 있습니다.");
		}
	}
}

AllChatCommand

 

3. BroadCasting된 message를 받은 ClientManager는 View의 allChat함수를 호출하여 화면에 message를 띄운다.

// Case 4: 채팅 메시지 등 그 외 처리
else if (message.startsWith("Message:")){
    String chatMessage = message.substring(8);
    lobby.getView().allChat(chatMessage);
}

ClientManager

public void allChat(String message) {
    chatArea.append(message + '\n');
    chatArea.setCaretPosition(chatArea.getDocument().getLength());

    contentPane.repaint();
}

View

 

+ 토론은 3분간 진행된다

public class 토론 implements IState{

	public void execute(사회자 매니저) {
		매니저.getCommandManager().broadcastAll("System:"+"DAY "+(매니저.dayCount+1)+" 토론이 시작되었습니다. 토론시간은 3분 주어집니다");
		
		try {
			Thread.sleep(180000);//3분
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
        System.out.println("(여기서 플레이어들이 자유롭게 토론합니다...)");
	}
}

토론

'JAVA' 카테고리의 다른 글

[마피아] 투표  (0) 2025.12.02
[마피아] 밤  (0) 2025.12.02
[마피아] Role  (0) 2025.12.01
[JAVA] Spring Boot - 2  (0) 2025.11.25
[마피아] Start Sequence  (0) 2025.11.21