Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Observable;
- import java.util.Observer;
- import javafx.application.Application;
- import javafx.event.EventHandler;
- import javafx.geometry.Insets;
- import javafx.scene.Scene;
- import javafx.scene.control.Alert;
- import javafx.scene.control.Alert.AlertType;
- import javafx.scene.input.MouseEvent;
- import javafx.scene.layout.TilePane;
- import javafx.scene.paint.Color;
- import javafx.scene.shape.Circle;
- import javafx.stage.Stage;
- public class Connect4View extends Application implements Observer
- {
- Circle[][] slots = new Circle[6][7];
- Scene scene;
- public static void main(String[] args)
- {
- launch(args);
- }
- @Override
- public void start(Stage stage)
- {
- Connect4View view = new Connect4View();
- Connect4Controller controller = new Connect4Controller(view);
- TilePane tilePane = new TilePane(8, 8);
- tilePane.setPrefRows(6);
- tilePane.setPrefColumns(7);
- tilePane.setPadding(new Insets(8));
- for(int i = 0;i < view.slots.length;i++)
- {
- for(int j = 0;j < view.slots[i].length;j++)
- {
- view.slots[i][j] = new Circle(20, Color.WHITE);
- tilePane.getChildren().add(view.slots[i][j]);
- }
- }
- tilePane.setOnMouseClicked(new EventHandler<MouseEvent>()
- {
- @Override
- public void handle(MouseEvent e)
- {
- int x = (int) e.getX();
- int col;
- if(x <= 52)
- col = 0;
- else if(x > 52 && x <= 100)
- col = 1;
- else if(x > 100 && x <= 148)
- col = 2;
- else if(x > 148 && x <= 196)
- col = 3;
- else if(x > 196 && x <= 244)
- col = 4;
- else if(x > 244 && x <= 292)
- col = 5;
- else
- col = 6;
- try
- {
- controller.humanTurn(col);
- if(controller.isGameEnded())
- {
- new Alert(AlertType.INFORMATION, "You won!").showAndWait();
- tilePane.setDisable(true);
- }
- else
- {
- controller.computerTurn();
- if(controller.isGameEnded())
- {
- new Alert(AlertType.INFORMATION, "You lost!").showAndWait();
- tilePane.setDisable(true);
- }
- }
- }
- catch(InvalidColumnException exception)
- {
- new Alert(AlertType.ERROR, "Column full, pick somewhere else!").showAndWait();
- }
- }
- });
- scene = new Scene(tilePane, Color.BLUE);
- stage.setTitle("Connect 4");
- stage.setScene(scene);
- stage.show();
- }
- public void update(Observable o, Object arg)
- {
- slots[((Connect4MoveMessage) arg).row][((Connect4MoveMessage) arg).col].setFill(((Connect4MoveMessage) arg).color);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement