You are on page 1of 20

Connect Four Game

Project report submitted to


Guru Jambheshwar University of Science and Technology, Hisar

For the partial award of the degree Of

Bachelor of Technology in Computer Science & Engineering

PREPARED BY – Pooja

ROLL NO - 200010140040

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


GURU JAMBHESHWAR UNIVERSITY OF
SCIENCE & TECHNOLOGY, HISAR
CONTENTS
S. No Topic Remarks
1 Declaration

2 Acknowledgement

3 Introduction

4 Implementation

5 Result

6 Conclusion

7 References
DECLARATION

I certify that

a. The work in this report is original and has been done by me under
the guidance of my supervisor(s).
b. The work has not been submitted to any other institute for any
degree or diploma.
c. I have followed the guidelines provided by the institute in preparing the
report.
d. I have confirmed to the norms and guidelines given in the Ethical
code of conduct of the institute.
e. Whenever I have used materials (data, theoretical analysis,
figures, and text) from other sources, I have given due credit to
them by citing them in the text of the report and giving their
details in the references. Further, I have taken permission from
the copyright owners of the sources, whenever necessary.

Pooja
ACKNOWLEDGEMENT
In the present world of competition there is a race of existence in
which those are having will to come forward succeed. Project is like a
bridge between theoretical and practical working. With this willing I
joined this particular project. First of all, I would like to thank the
supreme power the Almighty God who is obviously the one has
always guided me to work on the right path of life. Without his grace
this project could not become a reality. Next to him are my parents,
whom I am greatly indebted for me brought up with love and
encouragement to this stage. I am feeling oblige in taking the
opportunity sincerely thanks to Prof. B. R. Kamboj (Vice Chancellor of
GJUS&T, Hisar). Moreover, I am highly obliged in taking the
opportunity to sincerely thanks to all the staff members of computer
department for their generous attitude and friendly behavior. At last,
but not least I am thankful to all my teachers and friends who have
been always helping and encouraging me though out the year. I have
no valuable words to express my thanks, but my heart is still full of
the favors received from every person.
INTRODUCTION
ABOUT PROJECT

This project is a Connect Four game. Connect Four is 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.

Tkinter Components

Tkinter is the most commonly used library for developing GUI (Graphical
User Interface) in Java. It is a standard Java interface to the Tk GUI toolkit
shipped with Java. As Tk and Tkinter are available on most of the Unix
platforms as well as on the Windows system, developing GUI applications
with Tkinter becomes the fastest and easiest.

WIDGETS:

Tkinter supports the below mentioned core widgets – 

Widgets Description
Label It is used to display text or image on the screen
Button It is used to add buttons to your application
It is used to draw pictures and others layouts like texts,
Canvas graphics etc.
It contains a down arrow to select from list of available
ComboBox options
It displays a number of options to the user as toggle buttons
CheckButton from which user can select any number of options.
Radio It is used to implement one-of-many selection as it allows
Button only one option to be selected
Entry It is used to input single line text entry from user
Frame It is used as container to hold and organize the widgets
It works same as that of label and refers to multi-line and
Message non-editable text
It is used to provide a graphical slider which allows to select
Scale any value from that scale
It is used to scroll down the contents. It provides a slide
Scrollbar controller.
SpinBox It is allows user to select from given set of values
It allows user to edit multiline text and format the way it has
Text to be displayed
Menu It is used to create all kinds of menu used by an application

Implementation
 Main.Java
package com.pooja.ConnectFour;

import javafx.application.Application;

import javafx.application.Platform;

import javafx.beans.value.ObservableValue;

import javafx.event.Event;

import javafx.fxml.FXMLLoader;

import javafx.scene.Parent;

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();


MenuBar menubar = createMenubar();

menubar.prefWidthProperty().bind((ObservableValue<? extends Number>)


primaryStage.widthProperty());

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

menuPane.getChildren().addAll(menubar);

controller = loader.getController();

controller.createPlayground();

Scene scene = new Scene(rootGridPane);

primaryStage.setScene(scene);

primaryStage.setTitle("Connect Four");

primaryStage.setResizable(false);

primaryStage.show();

private MenuBar createMenubar() {

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("Pooja Goyal");

alert.setContentText("I love to play with code and game around ,so i start learn to develop
game." +

".This is my first game which is created by me." );

alert.show();

private void aboutConnect4() {

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

alert.setTitle("About Connect4 Game");

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() {

public static void main(String[] args) {

launch(args);

Controller.java
package com.pooja.ConnectFour;

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 sun.security.provider.SHA;

import java.net.URL;

import java.util.*;

import java.util.concurrent.atomic.AtomicReference;

import java.util.stream.Collectors;

import java.util.stream.IntStream;

public class Controller implements Initializable {

private static final int Rows = 6;

private static final int Column = 7;

private static final int Circle_Diameter = 100;

private static final String Discolor1 = "#24303E";

private static final String Discolor2 = "#4CAA88";

private static String Player_One = "Player one";

private static String Player_Two = "Player two";

private boolean isPlayerOneTurn = true;

@FXML

public GridPane rootGridPane;


@FXML

public Pane insertDiscPane;

@FXML

public Button setNamebutton;

@FXML

public TextField player_OneTextField;

@FXML

public TextField player_TwoTextField;

@FXML

public Label playerNameLabel;

private boolean isAllowedToInsert=true;

public void createPlayground() {

Shape rectangleWithHole=createGameStructureGrid();

rootGridPane.add(rectangleWithHole, 0, 1);

List<Rectangle> rectangleList=createClickableColumns();

for (Rectangle rectangle:rectangleList) {

rootGridPane.add(rectangle,0,1);

setNamebutton.setOnAction(event -> {

Player_One=player_OneTextField.getText();

Player_Two=player_TwoTextField.getText();

playerNameLabel.setText(isPlayerOneTurn?Player_One:Player_Two);
});

private Shape createGameStructureGrid(){

Shape rectangleWithHole = new Rectangle((Column+1) * Circle_Diameter, (Rows+1) *


Circle_Diameter);

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

for (int col = 0; col < Column; 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);

rectangleWithHole = Shape.subtract(rectangleWithHole, circle);

rectangleWithHole.setFill(Color.WHITE);

return rectangleWithHole ;

private List<Rectangle> createClickableColumns(){

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

for(int col =0;col<Column;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(isAllowedToInsert) {

isAllowedToInsert=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;

insertDiscPane.getChildren().add(disc);

disc.setTranslateX(column*(Circle_Diameter+5)+Circle_Diameter / 4);

int currentRow=row;
TranslateTransition translateTransition=new TranslateTransition(Duration.seconds(0.5),disc);

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

translateTransition.setOnFinished(event -> {

isAllowedToInsert=true;

if(gameEnded(currentRow,column)){

gameOver();

return;

isPlayerOneTurn =!isPlayerOneTurn;

playerNameLabel.setText(isPlayerOneTurn? Player_One:Player_Two);

});

translateTransition.play();

private Disc[][] insertedDiscArray = new Disc[Rows][Column];

private boolean gameEnded(int row,int column){

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

.mapToObj(r ->new Point2D(r,column))

.collect(Collectors.toList());

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

.mapToObj(col -> new Point2D(row, col))

.collect(Collectors.toList());

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

List<Point2D> diagonal1Point =IntStream.rangeClosed(0,6)

.mapToObj(i ->startPoint1.add(i,-i))

.collect(Collectors.toList());

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

List<Point2D> diagonal2Point =IntStream.rangeClosed(0,6)

.mapToObj(i ->startPoint2.add(i,i))
.collect(Collectors.toList());

boolean isEnded=checkCombination(verticalPoints) || checkCombination(horizontalPoints)

||checkCombination(diagonal1Point) ||checkCombination(diagonal2Point);

return isEnded;

private boolean checkCombination(List<Point2D> points) {

int chain=0;

for (Point2D point:points) {

int rowIndexForArray=(int) point.getX();

int columnIndexForArray=(int) point.getY();

Disc disc= getDiscIfPresent(rowIndexForArray,columnIndexForArray);

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>=Column ||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("The Winner is"+winner);

alert.setContentText("Want to play again");

ButtonType yesBtn =new ButtonType("Yes");

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

alert.getButtonTypes().setAll(yesBtn,noBtn);

Platform.runLater(() ->{

Optional<ButtonType> btnClicked =alert.showAndWait();

if(btnClicked.isPresent() && btnClicked.get()==yesBtn){

resetGame();

}else{

Platform.exit();

System.exit(0);

});

public void resetGame() {

insertDiscPane.getChildren().clear();
for(int row=0;row < insertedDiscArray.length;row++){

for(int col=0;col < insertedDiscArray.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);

setFill(isPlayerOneMove? Color.valueOf(Discolor1): Color.valueOf(Discolor2));

setCenterX(Circle_Diameter/2);

setCenterY(Circle_Diameter/2);

@Override

public void initialize(URL location, ResourceBundle resources) {

RESULT
CONCLUSION
This project has been very informative and it helped me to learn about
many interesting concepts of Java.
I learned how to create a Connect four game. And gained a lot of
knowledge about how to handle data and click event in Java. It gave
me motivation to create more such gaming projects.
It was fun to create and play the game and I am looking forward to
add more features to it to make it more interesting.

You might also like