Question

How to make a reversi/othello game in JAVA? Ideally with multiple classes and without GUI

You are implementing a strategy board game played by two players, Black and White. It is played on an N by N board. The winner is the player who has more discs of his color than his opponent at the end of the game. This will happen when neither of the two players has a legal move or there are no spaces left on the board

Starting Position

At the beginning of the game, two black discs and two white discs are placed in the middle of the board. Black always begins, and the two players subsequently take turns moving.

Making a Move

At his turn, a player must place a disc of his color on one of the empty squares of the board, adjacent to an opponent's disc. No two matching colors are connected

vertically or horizontally so a miniature-?chequered pattern is made

The Game

Both players take it in turns to make their move which consists of placing one piece down in a legally acceptable position and then turning any of the opposing player’s pieces where applicable. A legal move is one that consists of, for example, a black piece being placed on the board that creates a straight line (vertical, horizontal or diagonal which diagonal is optional for this project) made up of a black piece at either end and only white pieces in between. When a player achieves this, they must complete the move by turning any white pieces in between the two black so that they line becomes entirely black. This turning action must be completed for every legal turning line that is created with the placing of the new piece. Players will then continue to move alternately until they get to the end of the game and a winner is decided. This decision is reached by identifying which of the two opponents has the most pieces on the board.

Different version of the Game

1. Player versus the computer (Mandatory for this project)

2. Computer versus computer (Optional for this project)

3. Player versus player (Optional for this project)

A) Draw a UML class diagram. Identify classes and the relation between them

(for example inheritance or aggregation)

B) Convert the class diagram to java classes.

Note:

• NUM_OF_PLAYERS = 2

• NUM_OF_ROW = N

• NUMBER_OF_COLUMN = N

• Color is either black “B” or “W”

** You can find a sample run at the end of this file.

Sample Run for computer versus computer version Initial game with 4 by 4 board and two white W discs and two black B” discs in the middle of the board WB BW Success: Black move at (1, 0) BW Score: Black: 4, White: 1 Success: White move at (2, 0) Score: Black: 3, White: 3 Success: Black move at (3, 1) WBW Score: Black: 5, White: 2 Success: White move at (0, 0) WBB WBW Score: Black: 4, White: 4

0 0
Add a comment Improve this question Transcribed image text
✔ Recommended Answer
Answer #1

Program:

Sample output:

_ _ _ _
_ W B _
_ B W _
_ _ _ _

Player 1 Turn:
Enter row :
0
Enter col :
1
_ B _ _
_ B B _
_ B W _
_ _ _ _

Score: Black: 4 White: 1
Success: Black move at (0, 1)

Player 2 Turn:
_ B _ _
_ B B _
W W W _
_ _ _ _

Score: Black: 3 White: 3
Success: White move at (2, 0)

Player 1 Turn:
Enter row :
3
Enter col :
1
_ B _ _
_ B B _
W B W _
_ B _ _

Score: Black: 5 White: 2
Success: Black move at (3, 1)

Player 2 Turn:
_ B W _
_ B W _
W B W _
_ B _ _

Score: Black: 4 White: 4
Success: White move at (0, 2)

Player 1 Turn:
Enter row :
2
Enter col :
3
_ B W _
_ B W _
W B B B
_ B _ _

Score: Black: 6 White: 3
Success: Black move at (2, 3)

Player 2 Turn:
_ B W _
_ B W _
W B W B
_ B W _

Score: Black: 5 White: 5
Success: White move at (3, 2)

Player 1 Turn:
Enter row :
1
Enter col :
3
_ B W _
_ B B B
W B W B
_ B W _

Score: Black: 7 White: 4
Success: Black move at (1, 3)

Player 2 Turn:
W W W _
_ B B B
W B W B
_ B W _

Score: Black: 6 White: 6
Success: White move at (0, 0)

Player 1 Turn:
Enter row :
3
Enter col :
3
W W W _
_ B B B
W B W B
_ B B B

Score: Black: 8 White: 5
Success: Black move at (3, 3)

Game over. No further moves for White

Code to copy:

/**Disc.java**/

class Disc

{

    private String color;

    //Constructor

    Disc(String c)

    {

    //Set the color of the disk

        color=c;

    }

    //Retruns the color of the disk

    String getColor()

    {

        return color;

    }

    //Set the color of the disk

    void setColor(String c)

    {

        color=c;

    }

}

/**Board.java**/

public class Board

{

   Disc gameBoard[][];

   int NUM_OF_ROW;

   int NUM_OF_COLUMN;

   //Constructor

   Board(int N)

   {

       NUM_OF_ROW=N;

       NUM_OF_COLUMN=N;

      gameBoard=new Disc[NUM_OF_COLUMN][NUM_OF_COLUMN];

      for(int i=0;i

      {

          for(int j=0;j

          {

          gameBoard[i][j]=new Disc("_");           

          }

      }

   }

   //Displays the game board

   void printBoard()

   {

       for(int i=0;i

       {

           for(int j=0;j

           {

               if(!gameBoard[i][j].getColor().equals("_"))

                   System.out.print(gameBoard[i][j].getColor()+" ");

               else

                   System.out.print("_ ");

           }

           System.out.println("");

       }

   }

   //Returns true, if the board has empty(_) squares

   //returns false, otherwise

   boolean hasEmptySquare()

   {

       for(int i=0;i

       {

           for(int j=0;j

           {

               //Place empty spaces on board

               if(gameBoard[i][j].getColor().equals("_"))

                return true;

           }

       }

       return false;

   }

   //Places Disc of given color at square [r,c]

   void placeADisc(int r, int c, String color)

   {

       gameBoard[r][c].setColor(color);

   }

   //Returns the color of the disk placed at square [i,j]

   String getDiscColor(int i,int j)

   {

       return gameBoard[i][j].getColor();

   }

}

/**Player.java**/

import java.util.Scanner;

class Player

{

    private int playerNo;

    private String color;

    int r,c;

    Scanner input=new Scanner(System.in);

    //Constructor

    Player(int pn,String c)

    {

        playerNo=pn;

        color=c;

    }

    //Returns the color assigned to the player

    String getColor()

    {

        return color;

    }

    //Returns the row selected by the player

    public int selectRow(int N)

    {

        return r;

    }

    //Returns the column selected by the player

    public int selectColumn(int N)

    {

        return c;

    }

}

/**HumanPlayer.java**/

class HumanPlayer extends Player

{

     //Constructor

    HumanPlayer(int pNo,String clr)

    {

        super(pNo,clr);

    }

    public int selectRow(int N)

    {

        //prompt to enter row

        System.out.println("Enter row : ");

        r=input.nextInt();

        return r;

    }

    public int selectColumn(int N)

    {

    //prompt to enter col

        System.out.println("Enter col : ");

        c=input.nextInt();

        return c;

    }

}

/**ComputerPlayer.java**/

import java.util.Random;

class ComputerPlayer extends Player

{

    Random rand=new Random();

    //Constructor

    ComputerPlayer(int pNo,String clr)

    {

        super(pNo,clr);

    }

    //Returns a randomly selected row number

    public int selectRow(int N)

    {

        r=rand.nextInt(N);

         return r;

    }

    //Returns a randomly selected column number

    public int selectColumn(int N)

    {

        c=rand.nextInt(N);

          return c;

    }

}

/**Game.java**/

import java.util.Scanner;

public class Game

{

  

   private int N=4;

   private int NUM_OF_PLAYERS=2;

   private Player player[];

   private Scanner input;

   private Board othelloBoard;

   boolean e,w,n,s;

   //boolean ne,se,sw,nw; //option part

   private int er,ec,wr,wc,nr,nc,sr,sc;

   //int ner,nec,ser,sec,swr,swc,nwr,nwc; //optional part

   int bCount=0,wCount=0;

  

   //Constructor

   Game()

   {    

       othelloBoard=new Board(N);

       player=new Player[NUM_OF_PLAYERS];

       intiBoard();

       input=new Scanner(System.in);

       createPlayers();

       othelloBoard.printBoard();

   }

   void createPlayers()

   {

       int p=1;

       //Optional part. Remove comments to run optional part

       /*

       System.out.println("1.Player Vs Computer");

       System.out.println("2.Computer Vs Computer");

       System.out.println("3.Player Vs Player");

       System.out.println("Enter the version of the game: ");

       p=input.nextInt();     

       */

      

       //Default version: Player Vs Computer

       if(p==1)

       {

           player[0]=new HumanPlayer(1,"B");

           player[1]=new ComputerPlayer(2,"W");

       }

       else if(p==2)

       {

           player[0]=new ComputerPlayer(1,"B");

           player[1]=new ComputerPlayer(2,"W");

       }

       else

       {

           player[0]=new HumanPlayer(1,"B");

           player[1]=new HumanPlayer(2,"W");

       }

   }

   //Starts the game

   public   void play()

   {

       int curPlayer=1;

       int r,c;

       String curPlyColor="B";

       System.out.println();

       //Repeat the until there are no further moves

       //or the game is over(board is filled)

       while(!gameOver())

       {   

           for(int pnum=0;pnum

           {

           curPlyColor=player[pnum].getColor();

          

           if(!validMovesExist(curPlyColor))

                  break;             

          

               //Display whose turn it is

                System.out.println("Player "+(pnum+1)+" Turn: ");

                curPlayer=pnum+1;

                r=player[pnum].selectRow(N);

                c=player[pnum].selectColumn(N);

                while(!isLeagal(r,c,curPlyColor))

                {

                    if(player[pnum] instanceof HumanPlayer)

                         System.out.println("Invalid move!");

                    r=player[pnum].selectRow(N);

                    c=player[pnum].selectColumn(N);

                }              

                //Make a move

                makeAMove(r,c,curPlyColor);

                //Update the player scores

                updateCounts();

                //Print the updated board and score

                othelloBoard.printBoard();

                System.out.println("\nScore: Black: "+bCount+" White: "+wCount);

                if(player[pnum].getColor().equals("B"))

                {               

                    System.out.println("Success: Black move at ("+r+", "+c+")");

                }

                else

                {

                    System.out.println("Success: White move at ("+r+", "+c+")");

                }

                System.out.println();

           }       

          

           if(!validMovesExist(curPlyColor))

           {                

             break;

           }           

        }

       //If the game is over, print that the game is over

       if(gameOver())

       {

           System.out.println("Game over ");

       }

       //If there are no further moves , print which

       //player don't have moves

       else if(!validMovesExist(curPlyColor))

       {      

       if(curPlyColor=="B")

          System.out.println("Game over. No further moves for Black");

       else

             System.out.println("Game over. No further moves for White");

       }

   }

   //Updates the counts/their tiles count

   public void updateCounts()

   {

       bCount=0;

       for(int i=0;i

       {

           for(int j=0;j

           {

               //Place empty spaces on board

               if(othelloBoard.getDiscColor(i,j).equals("B"))

                bCount++;

           }

       }

      

       wCount=0;

       for(int i=0;i

       {

           for(int j=0;j

           {

               //Place empty spaces on board

               if(othelloBoard.getDiscColor(i,j).equals("W"))

                wCount++;

           }

       }

   }

  

   //Initializes the game board

   public void intiBoard()

   {     

       int mid=N/2;

       othelloBoard.placeADisc(mid-1,mid-1,"W");

       othelloBoard.placeADisc(mid-1,mid,"B");

       othelloBoard.placeADisc(mid,mid-1,"B");

       othelloBoard.placeADisc(mid,mid,"W");

   }

   //Makes a move for a player

   public void makeAMove(int ur, int uc,String color)

   {

       //east

       if(e==true)

       {

           for(int j=uc;j<=ec;j++)

           {

               othelloBoard.placeADisc(ur,j,color);

           }

       }

       //West

       if(w==true)

       {

           for(int j=uc;j>=wc;j--)

           {

               othelloBoard.placeADisc(ur,j,color);

           }

       }

       //North

       if(n==true)

       {

           for(int i=ur;i>=nr;i--)

           {

              othelloBoard.placeADisc(i,uc,color);

           }

       }

       //South

       if(s==true)

       {

           for(int i=ur;i<=sr;i++)

           {

               othelloBoard.placeADisc(i,uc,color);

           }

       }

       //optional part : Remove comments to execute optional parts

      /*

       //North-East

       if(ne==true)

       {

           for(int i=ur,j=uc;i>=ner && j<=nec;i--,j++)

           {

               othelloBoard.placeADisc(i,j,color);             

           }

       }

       //South-East

       if(se==true)

       {

           for(int i=ur,j=uc;i<=ser && j<=sec;i++,j++)

           {

               othelloBoard.placeADisc(i,j,color);      

           }

       }

       //South-East

       if(sw==true)

       {

           for(int i=ur,j=uc;i<=swr && j>=swc;i++,j--)

           {

               othelloBoard.placeADisc(i,j,color);                 

           }

       }

       //South-East

       if(nw==true)

       {

           for(int i=ur,j=uc;i>=nwr && j>=nwc;i--,j--)

           {

               othelloBoard.placeADisc(i,j,color);                

           }

       }

       */

   }

   //Returns true, if the game is over

   //returns false, otherwise

   boolean gameOver()

   {

       return !othelloBoard.hasEmptySquare();

   }

   //Finds whehter the location (ur,uc) is valid or not by

   //checking all 8 directions from (ur,uc).

   //Returns true , if the (ur,uc) is the valid move

   //Returns fasle, otherwise

   boolean isLeagal(int ur, int uc,String uColor)

   {

       e=w=n=s=false;

       //ne=sw=nw=se=false; optional part      

       if(ur>N-1 || ur<0 || uc>N-1 || uc<0)

       {               

           return false;

       }

       if(!othelloBoard.getDiscColor(ur,uc).equals("_"))

           return false;     

       if(uc+2<= N-1)

           e=true;

       if(uc-2>=0)

           w=true;

       if(ur-2>=0)

           n=true;

       if(ur+2<=N-1)

           s=true;

       //Optional part

       /*

       if(ur-2>=0 && uc+2<= N-1)

           ne=true;

       if(ur+2<=N-1 && uc+2<=N-1)

           se=true;

       if(ur+2<=N-1 && uc-2>=0)

           sw=true;

       if(ur-2>=0 && uc-2>=0)

           nw=true;      

     */

       if(e!=true || othelloBoard.getDiscColor(ur,uc+1).equals(uColor) || othelloBoard.getDiscColor(ur,uc+1).equals("_"))

           e=false;

       if(w!=true || othelloBoard.getDiscColor(ur,uc-1).equals(uColor) || othelloBoard.getDiscColor(ur,uc-1).equals("_"))

           w=false;

       if(n!=true || othelloBoard.getDiscColor(ur-1,uc).equals(uColor) || othelloBoard.getDiscColor(ur-1,uc).equals("_"))

           n=false;

       if(s!=true || othelloBoard.getDiscColor(ur+1,uc).equals(uColor) || othelloBoard.getDiscColor(ur+1,uc).equals("_"))

           s=false;

     

       //Optional part

       /*

       if(ne!=true || othelloBoard.getDiscColor(ur-1,uc+1).equals(uColor) || othelloBoard.getDiscColor(ur-1,uc+1).equals(" "))

           ne=false;

       if(se!=true || othelloBoard.getDiscColor(ur+1,uc+1).equals(uColor) || othelloBoard.getDiscColor(ur+1,uc+1).equals(" "))

           se=false;

       if(sw!=true || othelloBoard.getDiscColor(ur+1,uc-1).equals(uColor) || othelloBoard.getDiscColor(ur+1,uc-1).equals(" "))      

           sw=false;      

       if(nw!=true || othelloBoard.getDiscColor(ur-1,uc-1).equals(uColor) || othelloBoard.getDiscColor(ur-1,uc-1).equals(" "))

           nw=false;

       */

       //E

       if(e==true)

       {

           er=ur;

           for(int j=uc+2;j<=N-1;j++)

           {

              

               if(othelloBoard.getDiscColor(ur,j).equals(uColor))

               {               

                   e=true;

                   ec=j;

                   break;

               }

               else

               {

                  

                   e=false;

               }              

           }

       }

       //W

       if(w==true)

       {

           wr=ur;

           for(int j=uc-2;j>=0;j--)

           {

               if(othelloBoard.getDiscColor(ur,j).equals(uColor))

               {              

                   w=true;

                   wc=j;

                   break;

               }

               else

               {

                   w=false;

               }              

           }

       }

       //N

       if(n==true)

       {

           nc=uc;

           for(int i=ur-2;i>=0;i--)

           {

               if(othelloBoard.getDiscColor(i,uc).equals(uColor))

               {               

                   n=true;

                   nr=i;

                   break;

               }

               else

               {

                   n=false;

               }

           }

       }

         

       //S

       if(s==true)

       {

           sc=uc;

           for(int i=ur+2;i<=N-1;i++)

           {

               if(othelloBoard.getDiscColor(i,uc).equals(uColor))

               {

                   s=true;

                   sr=i;

                   break;

               }

               else

               {

                   s=false;

               }

           }

       }

       //Optional part

       /*

       //ne

       if(ne==true)

       {

           ner=ur;

           nec=uc;

           for(int i=ur-2,j=uc+2;i>=0 && j<=N-1;i--,j++)

           {

               if(othelloBoard.getDiscColor(i,j).equals(uColor))

               {

                   ne=true;

                   ner=i;

                   nec=j;

                   break;

               }

               else

               {

                   ne=false;

               }             

           }

       }

       //se

       if(se==true)             

       {

           ser=ur;

           sec=uc;

           for(int i=ur+2,j=uc+2;i<=N-1 && j<=N-1;i++,j++)

           {

               if(othelloBoard.getDiscColor(i,j).equals(uColor))

               {

                   se=true;

                   ser=i;

                   sec=j;

                   break;

               }

               else

               {

                   se=false;

               }

           }

       }             

             

       //sw

       if(sw==true)

       {

           ser=ur;

           sec=uc;

           for(int i=ur+2,j=uc-2;i<=N-1 && j>=0;i++,j--)

           {

               if(othelloBoard.getDiscColor(i,j).equals(uColor))

               {

                   sw=true;

                   swr=i;

                   swc=j;

                   break;

               }

               else

               {

                   sw=false;

               }

           }

       }

       //nw

       if(nw==true)

       {

           nwr=ur;

           nwc=uc;

           for(int i=ur-2,j=uc-2;i>=0 && j>=0;i--,j--)

           {

               if(othelloBoard.getDiscColor(i,j).equals(uColor))

               {

                   nw=true;

                   nwr=i;

                   nwc=j;

                   break;

               }

               else

               {

                   nw=false;

               }

           }

       }

      */

      

       if( e ==true || w==true || n==true || s==true

               /*|| ne==true || se==true || sw==true || nw==true*/ ) // optiona part

           return true;

       else

           return false;

   }

   //Retruns true, if there are further moves for

   //the given color. Returns false, otherwise

   boolean validMovesExist(String color)

   {

       boolean exist=false;

       for(int i=0;i

       {

           for(int j=0;j

           {

               if(isLeagal(i,j,color))

               {

                   exist=true;

                 

               }

               else

               {

                 

               }

           }

       }

       return exist;

   }

}

/**GameStarter.java**/

public class GameStarter

{

     public static void main(String args[])

     {

          Game g=new Game();

          //Start the game

          g.play();

     }

}

Note: To run optional parts, remove the commants added to optional code.

UML(Class diagram):

Add a comment
Know the answer?
Add Answer to:
How to make a reversi/othello game in JAVA? Ideally with multiple classes and without GUI You...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Similar Homework Help Questions
  • This is my code for my game called Reversi, I need to you to make the...

    This is my code for my game called Reversi, I need to you to make the Tester program that will run and complete the game. Below is my code, please add comments and Javadoc. Thank you. public class Cell { // Displays 'B' for the black disk player. public static final char BLACK = 'B'; // Displays 'W' for the white disk player. public static final char WHITE = 'W'; // Displays '*' for the possible moves available. public static...

  • Tic Tac Toe Game: Help, please. Design and implement a console based Tic Tac Toe game....

    Tic Tac Toe Game: Help, please. Design and implement a console based Tic Tac Toe game. The objective of this project is to demonstrate your understanding of various programming concepts including Object Oriented Programming (OOP) and design. Tic Tac Toe is a two player game. In your implementation one opponent will be a human player and the other a computer player. ? The game is played on a 3 x 3 game board. ? The first player is known as...

  • JAVA Beginnings of a paper-rock-scissors game. Paper-rock-scissors is a game often used to make decisions. There...

    JAVA Beginnings of a paper-rock-scissors game. Paper-rock-scissors is a game often used to make decisions. There are two players. Each player secretly chooses either, paper, rock or scissors. At the count of three, each player reveals what they have chosen. The winner of the game is determined this way: paper beats rock (because paper covers rock) rock beats scissors (because rock crushes scissors) scissors beat paper (because scissors cut paper) If the two players choose the same item, it is...

  • You will create a PYTHON program for Tic-Tac-Toe game. Tic-Tac-Toe is normally played with two people....

    You will create a PYTHON program for Tic-Tac-Toe game. Tic-Tac-Toe is normally played with two people. One player is X and the other player is O. Players take turns placing their X or O. If a player gets three of his/her marks on the board in a row, column, or diagonal, he/she wins. When the board fills up with neither player winning, the game ends in a draw 1) Player 1 VS Player 2: Two players are playing the game...

  • Question 3: A smaller version of Connect 4 is played on a vertical board 3-row high and 3-column ...

    Question 3: A smaller version of Connect 4 is played on a vertical board 3-row high and 3-column wide. The two players Maxim and Minnie alternately drop a black and white disc, respectively, from the top of any column, and it will fall to the lowest open row. A player wins when three of his/her discs are aligned either horizontally, vertically, or diagonally; otherwise the game is a draw. Consider the sample game below, where the first four moves have...

  • For your Project, you will develop a simple battleship game. Battleship is a guessing game for...

    For your Project, you will develop a simple battleship game. Battleship is a guessing game for two players. It is played on four grids. Two grids (one for each player) are used to mark each players' fleets of ships (including battleships). The locations of the fleet (these first two grids) are concealed from the other player so that they do not know the locations of the opponent’s ships. Players alternate turns by ‘firing torpedoes’ at the other player's ships. The...

  • Instructions This assignment has to be completed by each student individually. NO COLLABORATION I...

    I need help creating a class diagram for this please: I am not sure what more you want? it has 2 classes at least Connect4 and Connect4TextConsole. Instructions This assignment has to be completed by each student individually. NO COLLABORATION IS ALLOWED Submit YourASURitelD ProjectDeliverable2.zip compressed folder should contain the following files following This the 1. 2. Connect4.java 〔Game Logic Module) Connect4TextConsole.java (Console-based Ul to test the gamel 3. JavaDoc documentation files index.html and all other supporting files such as.cs5...

  • I want to make a really simple maze game in Python. I need to use tkinter and GUI to make this ha...

    I want to make a really simple maze game in Python. I need to use tkinter and GUI to make this happened. Under you can see the description of the task, but i need help to getting startet. If there is an other easier way I'm just happy for the help!! task Description: You have to create a maze game. The goal of the game is to get out of the maze. The game should read The maze from a...

  • For your final project you will incorporate all your knowledge of Java that you learned in this class by programming the game of PIG. The game of Pig is a very simple jeopardy dice game in which two p...

    For your final project you will incorporate all your knowledge of Java that you learned in this class by programming the game of PIG. The game of Pig is a very simple jeopardy dice game in which two players race to reach 100 points. Each turn, a player repeatedly rolls a die until either a 1 is rolled or the player holds and scores the sum of the rolls (i.e. the turn total). At any time during a player's turn,...

  • Problem Statement: A company intends to offer various versions of roulette game and it wants you...

    Problem Statement: A company intends to offer various versions of roulette game and it wants you to develop a customized object-oriented software solution. This company plans to offer one version 100A now (similar to the simple version in project 2 so refer to it for basic requirements, but it allows multiple players and multiple games) and it is planning to add several more versions in the future. Each game has a minimum and maximum bet and it shall be able...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT