[go: up one dir, main page]

0% found this document useful (0 votes)
495 views15 pages

Oopm Mini Project Report

This document describes a Java mini project to create a Connect Four game. The aim is to learn core Java concepts and object-oriented programming principles through building a real-life game application. The game allows two players to take turns dropping discs into columns with the goal of connecting four of their own discs horizontally, vertically, or diagonally. The code provided implements the game structure, gameplay logic, and a graphical user interface.

Uploaded by

Harsh Vartak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
495 views15 pages

Oopm Mini Project Report

This document describes a Java mini project to create a Connect Four game. The aim is to learn core Java concepts and object-oriented programming principles through building a real-life game application. The game allows two players to take turns dropping discs into columns with the goal of connecting four of their own discs horizontally, vertically, or diagonally. The code provided implements the game structure, gameplay logic, and a graphical user interface.

Uploaded by

Harsh Vartak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

JAVA MINI PROJECT

AIM:
The basic aim of this project is to create awareness and enhance the knowledge in the
subject.By creating this mini project one could learn the core concepts involved in the subject
and the real life applications of OOPM.One can strengthen the concepts of oopm via this mini-
project.The prime aim of creating this game "Connect-Four" is that it covers major concepts in
the subject JAVA.It is like a checkpoint in the learning process. Creating this game safeguards
your knowledge in JAVA and builds in the confidence to learn further.

INTRODUCTION:

Connect-Four is a game for two persons.


Both players have 21 identical men. In the standard form of the game, one set of men is
yellow and the other set is red. The game is played on a vertical, rectangular board consisting of
7 vertical columns of 6 squares each. If a man is put in one of the columns, it will fall down to
the lowest unoccupied square in the column.
As soon as a column contains 6 men, no other man can be put in the column. Putting a
man in one of the columns is called: a move. The players make their moves in turn. There are
no rules stating that the player with, for instance, the yellow men should start. Since it is
confusing to have to identify for each new game the colour that started the game, we will
assume that the sets of men are coloured white and black instead of yellow and red. Like chess
and checkers (and unlike go) it is assumed that the player playing the white men will make the
first move.
Both players will try to get four connected men, either horizontally, vertically or
diagonally. The first player who achieves one such group of four connected men, wins the
game. If all 42 men are played and no player has achieved this goal, the game is drawn.

PROPOSE APPLICATION:

This game can be extended further by using knowledge of game theory.


Further research in is domain can help us make this game even better on all levels.
One can even extend this game to a level where the user can continue the game from he/she
has left.
This will make the game more advanced.We can even use front end frameworks to
enhance the outlook for the users.Making this game dynamic shall be the prime aim of the
creator. Further advancement and research in the knowledge of game theory more such
interesting and fun-loving games can be created in the future.

CONCLUSION:
Through this mini project work we learnt great concepts of Java used in a real life game
application.
We even learnt about-”Game Theory” and its application in this project.
This project has imbibed the knowledge of OOPM and real life application.Various
concepts of Java were learnt apart from the regular theoretical ones.This project was a huge
success and hence embedded coding for fun in our lives.

CODE:
Main.java:
package miniproject;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class Main extends Application {

private Controller controller;

@Override
public void start(Stage primaryStage) throws Exception {

FXMLLoader loader = new FXMLLoader(getClass().getResource("game.fxml"));


GridPane rootGridPane = loader.load();

controller = loader.getController();
controller.createPlayground();

MenuBar menuBar = createMenu();


menuBar.prefWidthProperty().bind(primaryStage.widthProperty());

Pane menuPane = (Pane) rootGridPane.getChildren().get(0);


menuPane.getChildren().add(menuBar);

Scene scene = new Scene(rootGridPane);

primaryStage.setScene(scene);
primaryStage.setTitle("Connect Four");
primaryStage.setResizable(false);
primaryStage.show();
}
private MenuBar createMenu() {

// File Menu
Menu fileMenu = new Menu("File");

MenuItem newGame = new MenuItem("New game");


newGame.setOnAction(event -> controller.resetGame());

MenuItem resetGame = new MenuItem("Reset game");


resetGame.setOnAction(event -> controller.resetGame());

SeparatorMenuItem separatorMenuItem = new SeparatorMenuItem();


MenuItem exitGame = new MenuItem("Exit game");
exitGame.setOnAction(event -> exitGame());

fileMenu.getItems().addAll(newGame, resetGame, separatorMenuItem, exitGame);

// Help Menu
Menu helpMenu = new Menu("Help");

MenuItem aboutGame = new MenuItem("About Connect4");


aboutGame.setOnAction(event -> aboutConnect4());

SeparatorMenuItem separator = new SeparatorMenuItem();


MenuItem aboutMe = new MenuItem("About Me");
aboutMe.setOnAction(event -> aboutMe());

helpMenu.getItems().addAll(aboutGame, separator, aboutMe);

MenuBar menuBar = new MenuBar();


menuBar.getMenus().addAll(fileMenu, helpMenu);

return menuBar;
}

private void aboutMe() {

Alert alert = new Alert(Alert.AlertType.INFORMATION);


alert.setTitle("About The Developer");
alert.setHeaderText("Harsh Vartak");
alert.setContentText("I love to play around with code and create games. " +
"Connect 4 is one of them. In free time " +
"I like to spend time trying to learn something new.");
alert.show();
}

private void aboutConnect4() {

Alert alert = new Alert(Alert.AlertType.INFORMATION);


alert.setTitle("About Connect Four");
alert.setHeaderText("How To Play?");
alert.setContentText("Connect Four is a two-player connection game in which the " +
"players first choose a color and then take turns dropping colored discs " +
"from the top into a seven-column, six-row vertically suspended grid. "+
"The pieces fall straight down, occupying the next available space within the column.
"+
"The objective of the game is to be the first to form a horizontal, vertical, " +
"or diagonal line of four of one's own discs. Connect Four is a solved game. " +
"The first player can always win by playing the right moves.");

alert.show();
}

private void exitGame() {

Platform.exit();
System.exit(0);
}

private void resetGame() {


// TODO
}

public static void main(String[] args) {


launch(args);
}
}
Controller.java:
package miniproject;

import javafx.animation.TranslateTransition;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Point2D;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.util.Duration;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Controller implements Initializable {

private static final int COLUMNS = 7;


private static final int ROWS = 6;
private static final int CIRCLE_DIAMETER = 80;
private static final String discColor1 = "#24303E";
private static final String discColor2 = "#4CAA88";

private static String PLAYER_ONE = "Player One";


private static String PLAYER_TWO = "Player Two";

private boolean isPlayerOneTurn = true;


private boolean isAllowedToEnter=true;

private Disc[][] insertedDiscArray=new Disc[ROWS][COLUMNS];//For structural changes

@FXML
public GridPane rootGridPane;

@FXML
public Pane insertedDiscsPane;

public Label playerNameLabel;

@FXML
public Button setNameButton;
@FXML
public TextField player1Name;

@FXML
public TextField player2Name;

public void createPlayground() {

Shape rectangleWithHoles = createGameStructuralGrid();


rootGridPane.add(rectangleWithHoles, 0, 1);

List<Rectangle> rectangleList=createClickableColumns();
for (Rectangle rectangle:rectangleList ) {
rootGridPane.add(rectangle,0,1);

private Shape createGameStructuralGrid() {

Shape rectangleWithHoles = new Rectangle((COLUMNS + 1) * CIRCLE_DIAMETER,


(ROWS + 1) * CIRCLE_DIAMETER);

for (int row = 0; row < ROWS; row++) {

for (int col = 0; col < COLUMNS; col++) {


Circle circle = new Circle();
circle.setRadius(CIRCLE_DIAMETER / 2);
circle.setCenterX(CIRCLE_DIAMETER / 2);
circle.setCenterY(CIRCLE_DIAMETER / 2);
circle.setSmooth(true);

circle.setTranslateX(col * (CIRCLE_DIAMETER + 5) + CIRCLE_DIAMETER / 4);


circle.setTranslateY(row * (CIRCLE_DIAMETER + 5) + CIRCLE_DIAMETER / 4);

rectangleWithHoles = Shape.subtract(rectangleWithHoles, circle);


}
}

rectangleWithHoles.setFill(Color.WHITE);

return rectangleWithHoles;
}

private List<Rectangle> createClickableColumns(){

List<Rectangle> rectangleList=new ArrayList<>();

for (int col=0;col<COLUMNS;col++) {


Rectangle rectangle = new Rectangle(CIRCLE_DIAMETER, (ROWS + 1) *
CIRCLE_DIAMETER);
rectangle.setFill(Color.TRANSPARENT);
rectangle.setTranslateX(col * (CIRCLE_DIAMETER + 5) + CIRCLE_DIAMETER / 4);

rectangle.setOnMouseEntered(event -> rectangle.setFill(Color.valueOf("#eeeeee26")));


rectangle.setOnMouseExited(event -> rectangle.setFill(Color.TRANSPARENT));

final int column=col;

rectangle.setOnMouseClicked(event -> {
if (isAllowedToEnter)
{
isAllowedToEnter=false;
insertDisc(new Disc(isPlayerOneTurn), column);
}

});

rectangleList.add(rectangle);
}
return rectangleList;
}

private void insertDisc(Disc disc,int column){

int row=ROWS-1;

while(row>=0){
if(getDiscIfPresent(row,column)==null){
break;
}
row--;
}
if (row<0){
return;
}

insertedDiscArray[row][column]=disc;
insertedDiscsPane.getChildren().add(disc);
disc.setTranslateX(column * (CIRCLE_DIAMETER + 5) + CIRCLE_DIAMETER / 4);

TranslateTransition translateTransition=new
TranslateTransition(Duration.seconds(0.6),disc);

translateTransition.setToY((row * (CIRCLE_DIAMETER + 5)) + (CIRCLE_DIAMETER / 4));

int currentRow= row;


translateTransition.setOnFinished(event -> {

isAllowedToEnter=true;
if(gameEnded(currentRow,column)){
gameOver();
return;
}
isPlayerOneTurn=!isPlayerOneTurn;
playerNameLabel.setText(isPlayerOneTurn?PLAYER_ONE:PLAYER_TWO);
});

translateTransition.play();

private boolean gameEnded(int row,int column){

List<Point2D> verticalPoints= IntStream.rangeClosed(row-3,row+3).


mapToObj(r->new Point2D(r,column)).
collect(Collectors.toList());

List<Point2D> horizontalPoints= IntStream.rangeClosed(column-3,column+3).


mapToObj(c->new Point2D(row,c)).
collect(Collectors.toList());

Point2D startPoint1=new Point2D(row-3,column+3);


List<Point2D>diagonal1points=IntStream.rangeClosed(0,6)
.mapToObj(i-> startPoint1.add(i,-i))
.collect(Collectors.toList());

Point2D startPoint2=new Point2D(row-3,column-3);


List<Point2D>diagonal2points=IntStream.rangeClosed(0,6)
.mapToObj(i-> startPoint2.add(i,i))
.collect(Collectors.toList());

boolean isEnded= checkCombinations(verticalPoints)||


checkCombinations(horizontalPoints)||
checkCombinations(diagonal1points)||
checkCombinations(diagonal2points);

return isEnded;
}

private boolean checkCombinations(List<Point2D> points) {


int chain=0;
for (Point2D point:points) {
int rowIndexArray= (int) point.getX();
int columnIndexArray=(int) point.getY();

Disc disc =getDiscIfPresent(rowIndexArray,columnIndexArray);

if (disc!=null&&disc.isPlayerOneMove==isPlayerOneTurn){
chain++;
if (chain==4){
return true;
}
}else {
chain=0;
}

}
return false;
}
private Disc getDiscIfPresent(int row,int column){
if (row>=ROWS||row<0||column>=COLUMNS||column<0)
return null;
return insertedDiscArray[row][column];
}
private void gameOver() {
String winner=isPlayerOneTurn?PLAYER_ONE:PLAYER_TWO;
System.out.println("Winner is "+winner);
Alert alert=new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Connect Four");
alert.setHeaderText("Winner is"+winner);
alert.setContentText("Want to play again");

ButtonType yesButton=new ButtonType("Yes");


ButtonType noButton=new ButtonType("No, Exit");

alert.getButtonTypes().setAll(yesButton,noButton);

Platform.runLater(()->{
Optional<ButtonType>clickedButton=alert.showAndWait();

if (clickedButton.isPresent()&&clickedButton.get()==yesButton){
resetGame();

}else{
exitGame();
}
});

public void resetGame() {

insertedDiscsPane.getChildren().clear();
for (int row=0;row< insertedDiscArray.length;row++){
for (int col=0;col<insertedDiscArray[row].length;col++){
insertedDiscArray[row][col]=null;
}
}
isPlayerOneTurn=true;
playerNameLabel.setText(PLAYER_ONE);

createPlayground();

private static class Disc extends Circle{


private final boolean isPlayerOneMove;
public Disc(boolean isPlayerOneMove){
this.isPlayerOneMove=isPlayerOneMove;
setRadius(CIRCLE_DIAMETER/2);
setCenterY(CIRCLE_DIAMETER/2);
setCenterX(CIRCLE_DIAMETER/2);
setFill(isPlayerOneMove? Color.valueOf(discColor1):Color.valueOf(discColor2));
}
}

public void exitGame() {

Platform.exit();
System.exit(0);
}

@Override
public void initialize(URL location, ResourceBundle resources) {
setNameButton.setOnAction(event -> {
PLAYER_ONE=player1Name.getText();
PLAYER_TWO=player2Name.getText();

});

}
}

game.fxml:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.Region?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.text.Font?>
<GridPane fx:id="rootGridPane" style="-fx-background-color: #D9F7F0;"
xmlns="http://javafx.com/javafx/8.0.221" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="miniproject.Controller">

<columnConstraints>
<ColumnConstraints />
<ColumnConstraints maxWidth="298.0" minWidth="225.0" prefWidth="225.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints minHeight="10.0" prefHeight="30.0" />
<RowConstraints />
</rowConstraints>

<children>
<Pane GridPane.columnSpan="2" />
<Pane fx:id="insertedDiscsPane" prefHeight="400.0" prefWidth="200.0"
GridPane.rowIndex="1" />
<VBox style="-fx-background-color: #2B3B4C;" GridPane.columnIndex="1"
GridPane.rowIndex="1">
<children>
<Pane prefHeight="141.0" prefWidth="302.0">
<children>
<TextField fx:id="player1Name" layoutX="21.0" layoutY="34.0" prefHeight="25.0"
prefWidth="185.0" promptText="Player 1 name" />
<TextField fx:id="player2Name" layoutX="22.0" layoutY="58.0" prefHeight="25.0"
prefWidth="185.0" promptText="Player 2 name" />
<Button fx:id="setNameButton" layoutX="22.0" layoutY="88.0"
mnemonicParsing="false" prefHeight="25.0" prefWidth="185.0" text="Set Name" />
</children>
</Pane>
<Region prefHeight="134.0" prefWidth="302.0" VBox.vgrow="ALWAYS" />
<Label fx:id="playerNameLabel" alignment="CENTER" prefHeight="35.0"
prefWidth="302.0" text="Player One" textFill="WHITE">
<font>
<Font name="System Bold" size="29.0" />
</font>
</Label>
<Label alignment="CENTER" prefHeight="31.0" prefWidth="301.0" text="Turn"
textFill="WHITE">
<font>
<Font size="26.0" />
</font>
</Label>
<Region prefHeight="200.0" prefWidth="200.0" VBox.vgrow="ALWAYS" />
</children>
</VBox>
</children>

</GridPane>
OUTPUT:

You might also like