Skip to content
Snippets Groups Projects
Forked from Bariatti Francesco / pingouins
77 commits behind the upstream repository.
UpdateThread.java 2.22 KiB
package controller;

import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import model.GameState;
import model.Player;
import model.Tile;
import view.TileView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class UpdateThread extends Thread
{
	BufferedReader reader;
	GameState gameState;
	Tile[] board;
	TileView[] boardView;

	public UpdateThread(Process program, GameState gameState, Tile[] board, TileView[] boardView)
	{
		this.reader = new BufferedReader(new InputStreamReader(program.getInputStream()));
		this.gameState = gameState;
		this.board = board;
		this.boardView = boardView;
	}
	

	public void run()
	{
		boolean gameRunning = true;
		while (gameRunning)
		{
			try
			{
				String line = reader.readLine();
				System.out.println(line);
				if (line == null)
				{
					gameRunning = false;
				}
				else if (line.contains("{")) //Line contains JSON
				{
					//UPDATE MODEL
					gameState.update(line.substring(line.indexOf("{"), line.lastIndexOf("}") + 1)); //Extract JSON string
					for (int i = 0; i < board.length; i++)
					{
						board[i].setNbFish(gameState.getNbFish(i));
						board[i].setPenguinPresence(Tile.PenguinPresence.NO_PENGUIN);
					}
					for (int i = 0; i < 4; i++)
					{
						board[gameState.getPenguinPos(i, Player.Red)].setPenguinPresence(Tile.PenguinPresence.RED_PENGUIN);
						board[gameState.getPenguinPos(i, Player.Blue)].setPenguinPresence(Tile.PenguinPresence.BLUE_PENGUIN);
					}

					//UPDATE VIEW
					for (int i = 0; i < boardView.length; i++)
						boardView[i].updateFromModel();
				}
			}
			catch (IOException e)
			{
				gameRunning = false;
				Platform.runLater(() ->
				{
					Alert alert = new Alert(Alert.AlertType.ERROR, "Error during reading from penguin program!", ButtonType.FINISH);
					alert.showAndWait();
					e.printStackTrace();
					Platform.exit();
				});
			}
			catch (Throwable e)
			{
				gameRunning = false;
				Platform.runLater(() -> {
					Alert alert = new Alert(Alert.AlertType.ERROR, "Unhandled exception in update thread: " + e.getMessage(), ButtonType.FINISH);
					alert.showAndWait();
					e.printStackTrace();
					Platform.exit();
				});
			}
		}
	}
}