Commit 54c8cf45 authored by 刘家荣's avatar 刘家荣 💬
Browse files

Refactor(AppController,...): adapted future async paradigm

parent 865bb1f2
Loading
Loading
Loading
Loading
+1 −1

File changed.

Preview size limit exceeded, changes collapsed.

src/Main.java

deleted100644 → 0
+0 −7
Original line number Diff line number Diff line
import controller.AppController;

public class Main {
    public static void main(String[] args) {
        AppController.instance = new AppController();
    }
}
+177 −164
Original line number Diff line number Diff line
@@ -11,8 +11,13 @@ import network.Client;
import network.Server;
import network.dataType.OnlineStatus;
import view.Frame.AppFrame;
import view.Frame.AppFrameReturnType.goOffline;
import view.Frame.AppFrameReturnType.goRooms;
import view.Frame.ChessGameFrame;
import view.RoomFrame;
import view.Frame.FrameReturnType;
import view.Frame.GameFrameReturnType.exitGame;
import view.Frame.RoomFrame;
import view.Frame.RoomFrameReturnType.goOnline;

import javax.swing.*;
import java.awt.event.WindowAdapter;
@@ -22,68 +27,54 @@ import java.io.IOException;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;

/**
 * 负责全局工作,切换界面时引导相关Model初始化,也负责读写文存档
 */
public class AppController {
	public static Logger logger = Logger.getLogger("default-logger");

    public static AppController instance;
	private static History savedHistory;

    AppStatus status = AppStatus.START;
    
    private History savedHistory;
    
    private Game savedGame;
	private static Game savedGame;

	public static final String savePath = "res/save/save.json";

	public AppController() {
        try {
            read(savePath);
        } catch (IOException | JSONException e) {
            e.printStackTrace();
            savedGame = null;
            savedHistory = null;
        }

        SwingUtilities.invokeLater(() -> {
            AppFrame.instance = new AppFrame();
            AppFrame.instance.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    super.windowClosing(e);
                    
                }
            });
        });
	}

    public History getSavedHistory() {
	public static History getSavedHistory() {
		return savedHistory;
	}

    public Game getSavedGame() {
	public static Game getSavedGame() {
		return savedGame;
	}

    public void goRooms() {
	public static void goRooms() throws ExecutionException, InterruptedException {
		while(true) {
			CompletableFuture<FrameReturnType<RoomFrame>> roomFuture = new CompletableFuture<>();
			SwingUtilities.invokeLater(() -> {
            if (status == AppStatus.START)
                AppFrame.instance.dispose();
            else if (status == AppStatus.GAME)
                ChessGameFrame.instance.dispose();
            else return;
            RoomFrame.instance = new RoomFrame();
				RoomFrame.instance = new RoomFrame(roomFuture);
				RoomFrame.instance.setVisible(true);
            status = AppStatus.ROOM;
			});
			FrameReturnType<RoomFrame> result = roomFuture.get();
			RoomFrame.instance.setVisible(false);
			RoomFrame.instance.dispose();
			if (result instanceof goOnline result1) {
				goOnlineGame(result1.onlineMode, result1.room);
			}else return;
		}
	}

    public void goOfflineGame(boolean useSave, GameType type) {
        if (status == AppStatus.START) {
	public static void goOfflineGame(boolean useSave, GameType type) throws ExecutionException, InterruptedException {
		CompletableFuture<FrameReturnType<ChessGameFrame>> gameFuture = new CompletableFuture<>();
		SwingUtilities.invokeLater(() -> {
                AppFrame.instance.dispose();
                ChessGameFrame.instance = new ChessGameFrame();
			ChessGameFrame.instance = new ChessGameFrame(gameFuture);
			ChessGameFrame.instance.setVisible(true);
		});
		if (useSave) {
@@ -94,63 +85,47 @@ public class AppController {
			History.instance = new History(Game.instance.clone());
			write(savePath);
		}
            status = AppStatus.GAME;
        }
		gameFuture.get();
		ChessGameFrame.instance.setVisible(false);
		ChessGameFrame.instance.dispose();
	}

    public void goOnlineGame(OnlineStatus onlineMode, Room room) {
        if (status == AppStatus.ROOM) {
	public static void goOnlineGame(OnlineStatus onlineMode, Room room) throws ExecutionException, InterruptedException {
		CompletableFuture<FrameReturnType<ChessGameFrame>> gameFuture = new CompletableFuture<>();
		Game.instance = new Game(GameType.ONLINE);
		History.instance = new History(Game.instance.clone());
		if (onlineMode == OnlineStatus.SERVER_WAITING) {
			try {
                    RoomFrame.instance.dispose();
				Server.start();
                    ChessGameFrame.instance = new ChessGameFrame();
				ChessGameFrame.instance = new ChessGameFrame(gameFuture);
				ChessGameFrame.instance.setVisible(true);
			} catch (UnknownHostException e) {
				gameFuture.complete(new exitGame());
				JOptionPane.showMessageDialog(null, "房间创建失败", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
			}
		} else {
			boolean isPlayer = onlineMode == OnlineStatus.CLIENT_PLAYING;
                RoomFrame.instance.dispose();
			Client.connect(room.ip, isPlayer ? room.playerPort : room.watcherPort, isPlayer,
					() -> {
						SwingUtilities.invokeLater(() -> {
                            ChessGameFrame.instance = new ChessGameFrame();
							ChessGameFrame.instance = new ChessGameFrame(gameFuture);
							ChessGameFrame.instance.setVisible(true);
						});
						Game.instance = new Game(GameType.ONLINE);
						History.instance = new History(Game.instance.clone());
                        status = AppStatus.GAME;
					},
					() -> {
						gameFuture.complete(new exitGame());
						JOptionPane.showMessageDialog(null, "连接失败", "提示", JOptionPane.WARNING_MESSAGE);
                        goRooms();
					},
					() -> {
						gameFuture.complete(new exitGame());
						JOptionPane.showMessageDialog(null, "连接已断开", "提示", JOptionPane.WARNING_MESSAGE);
                        goRooms();
					});
		}
        }
    }
    
    public void backToStart() {
        if (status == AppStatus.ROOM) {
            RoomFrame.instance.dispose();
        } else if (status == AppStatus.GAME) {
		gameFuture.get();
		ChessGameFrame.instance.setVisible(false);
		ChessGameFrame.instance.dispose();
            if (Game.instance != null && Game.instance.gameType != GameType.ONLINE) {
                write(savePath);
            }
        } else return;
        SwingUtilities.invokeLater(() -> {
            AppFrame.instance = new AppFrame();
            AppFrame.instance.setVisible(true);
        });
        status = AppStatus.START;
	}

	/**
@@ -160,18 +135,18 @@ public class AppController {
	 * @throws IOException
	 * @throws JSONException
	 */
    public void read(String path) throws IOException, JSONException {
	public static void read(String path) throws IOException, JSONException {
		try {
			JSONObject jsonObject = JSONObject.parse(Files.readString(Path.of(path)));
			savedGame = JSON.parseObject(jsonObject.getJSONObject("Game").toString(), Game.class);
			savedHistory = JSON.parseObject(jsonObject.getJSONObject("History").toString(), History.class);
		} catch (JSONException | IOException | IllegalArgumentException e) {
            e.printStackTrace();
			logger.severe(e.getMessage());
			JOptionPane.showMessageDialog(null, "阿哦,自动读取存档失败:" + e.getMessage(), "提示", JOptionPane.WARNING_MESSAGE);
		}
	}

    public boolean write(String path) {
	public static boolean write(String path) {
		try {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("Game", Game.instance);
@@ -184,10 +159,48 @@ public class AppController {
			read(path);
			return true;
		} catch (IOException | JSONException e) {
            e.printStackTrace();
			logger.severe(e.getMessage());
			JOptionPane.showMessageDialog(null, "阿哦,保存时发生错误了:" + e.getMessage(), "提示", JOptionPane.WARNING_MESSAGE);
			return false;
		}
	}

	public static void main(String[] args) {
		try {
			read(savePath);
		} catch (IOException | JSONException e) {
			logger.severe(e.getMessage());
			savedGame = null;
			savedHistory = null;
		}

		try {

			while (true) {
				// AppFrame
				CompletableFuture<FrameReturnType<AppFrame>> appFuture = new CompletableFuture<>();
				SwingUtilities.invokeLater(() -> {
					AppFrame.instance = new AppFrame(appFuture);
					AppFrame.instance.addWindowListener(new WindowAdapter() {
						public void windowClosing(WindowEvent e) {
							super.windowClosing(e);
						}
					});
				});
				FrameReturnType<AppFrame> result = appFuture.get();
				AppFrame.instance.setVisible(false);
				AppFrame.instance.dispose();
				if (result instanceof goOffline result1) {
					goOfflineGame(result1.useSave, result1.gameType);
				} else if (result instanceof goRooms result1) {
					goRooms();
				} else break;
			}

		} catch (InterruptedException | ExecutionException e) {
			throw new RuntimeException(e);
		}

	}

}
+199 −0
Original line number Diff line number Diff line
package controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import model.History;
import model.Room;
import model.dataType.GameType;
import model.game.Game;
import network.Client;
import network.Server;
import network.dataType.OnlineStatus;
import view.Frame.AppFrame;
import view.Frame.ChessGameFrame;
import view.Frame.RoomFrame;

import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.logging.Logger;

/**
 * 负责全局工作,切换界面时引导相关Model初始化,也负责读写文存档
 */
public class AppController_old {
    
    public static AppController_old instance;
    public static Logger logger = Logger.getLogger("default-logger");
    
    AppStatus status = AppStatus.START;
    
    private History savedHistory;
    
    private Game savedGame;
    
    public static final String savePath = "res/save/save.json";
    
    public AppController_old() {
        try {
            read(savePath);
        } catch (IOException | JSONException e) {
            logger.severe(e.getMessage());
            savedGame = null;
            savedHistory = null;
        }
        
        SwingUtilities.invokeLater(() -> {
            AppFrame.instance = new AppFrame();
            AppFrame.instance.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    super.windowClosing(e);
                    
                }
            });
        });
    }
    
    public History getSavedHistory() {
        return savedHistory;
    }
    
    public Game getSavedGame() {
        return savedGame;
    }
    
    public void goRooms() {
        SwingUtilities.invokeLater(() -> {
            if (status == AppStatus.START)
                AppFrame.instance.dispose();
            else if (status == AppStatus.GAME)
                ChessGameFrame.instance.dispose();
            else return;
            RoomFrame.instance = new RoomFrame();
            RoomFrame.instance.setVisible(true);
            status = AppStatus.ROOM;
        });
    }
    
    public void goOfflineGame(boolean useSave, GameType type) {
        if (status == AppStatus.START) {
            SwingUtilities.invokeLater(() -> {
                AppFrame.instance.dispose();
                ChessGameFrame.instance = new ChessGameFrame();
                ChessGameFrame.instance.setVisible(true);
            });
            if (useSave) {
                Game.instance = savedGame;
                History.instance = savedHistory;
            } else {
                Game.instance = new Game(type);
                History.instance = new History(Game.instance.clone());
                write(savePath);
            }
            status = AppStatus.GAME;
        }
    }
    
    public void goOnlineGame(OnlineStatus onlineMode, Room room) {
        if (status == AppStatus.ROOM) {
            Game.instance = new Game(GameType.ONLINE);
            History.instance = new History(Game.instance.clone());
            if (onlineMode == OnlineStatus.SERVER_WAITING) {
                try {
                    RoomFrame.instance.dispose();
                    Server.start();
                    ChessGameFrame.instance = new ChessGameFrame();
                    ChessGameFrame.instance.setVisible(true);
                } catch (UnknownHostException e) {
                    JOptionPane.showMessageDialog(null, "房间创建失败", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
            } else {
                boolean isPlayer = onlineMode == OnlineStatus.CLIENT_PLAYING;
                RoomFrame.instance.dispose();
                Client.connect(room.ip, isPlayer ? room.playerPort : room.watcherPort, isPlayer,
                    () -> {
                        SwingUtilities.invokeLater(() -> {
                            ChessGameFrame.instance = new ChessGameFrame();
                            ChessGameFrame.instance.setVisible(true);
                        });
                        Game.instance = new Game(GameType.ONLINE);
                        History.instance = new History(Game.instance.clone());
                        status = AppStatus.GAME;
                    },
                    () -> {
                        JOptionPane.showMessageDialog(null, "连接失败", "提示", JOptionPane.WARNING_MESSAGE);
                        goRooms();
                    },
                    () -> {
                        JOptionPane.showMessageDialog(null, "连接已断开", "提示", JOptionPane.WARNING_MESSAGE);
                        goRooms();
                    });
            }
        }
    }
    
    public void backToStart() {
        if (status == AppStatus.ROOM) {
            RoomFrame.instance.dispose();
        } else if (status == AppStatus.GAME) {
            ChessGameFrame.instance.dispose();
            if (Game.instance != null && Game.instance.gameType != GameType.ONLINE) {
                write(savePath);
            }
        } else return;
        SwingUtilities.invokeLater(() -> {
            AppFrame.instance = new AppFrame();
            AppFrame.instance.setVisible(true);
        });
        status = AppStatus.START;
    }
    
    /**
     * 年度大无语事件之JSON能做的事JSONObject不能做
     *
     * @param path
     * @throws IOException
     * @throws JSONException
     */
    public void read(String path) throws IOException, JSONException {
        try {
            JSONObject jsonObject = JSONObject.parse(Files.readString(Path.of(path)));
            savedGame = JSON.parseObject(jsonObject.getJSONObject("Game").toString(), Game.class);
            savedHistory = JSON.parseObject(jsonObject.getJSONObject("History").toString(), History.class);
        } catch (JSONException | IOException | IllegalArgumentException e) {
            logger.severe(e.getMessage());
            JOptionPane.showMessageDialog(null, "阿哦,自动读取存档失败:" + e.getMessage(), "提示", JOptionPane.WARNING_MESSAGE);
        }
    }
    
    public boolean write(String path) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Game", Game.instance);
            jsonObject.put("History", History.instance);
            File save = new File(path);
            if (!save.exists()) {
                save.createNewFile();
            }
            Files.writeString(Path.of(path), JSON.toJSONString(jsonObject));
            read(path);
            return true;
        } catch (IOException | JSONException e) {
            logger.severe(e.getMessage());
            JOptionPane.showMessageDialog(null, "阿哦,保存时发生错误了:" + e.getMessage(), "提示", JOptionPane.WARNING_MESSAGE);
            return false;
        }
    }

    public static void main(String[] args) {
        AppController_old.instance = new AppController_old();
    }
    
}
Loading