In: Computer Science
How do I get the computerPlayer to play as the other character? This is a connect4 game that has to use the the connect4ComputerPlayer to play as the other character when playing connect4 in the text console. How can i achieve this?
Programming language is java.
import java.util.Random;
import ui.Connect4TextConsole;
public class Connect4ComputerPlayer {
public static void ComputerPlayer(){
int counter = 1;
Random rand = new Random();
int computerMove = rand.nextInt(5)
+ 1;
int column = computerMove;
while(true){
if(column >
Connect4.width){
System.out.println("Invalid column
Input.");
break;
}
if
(Connect4.board[Connect4.widthMinus][column] == '|') {
Connect4.board[Connect4.widthMinus][column] =
'X';
break;
}
else
if(Connect4.board[Connect4.widthMinus][column] == 'X' ||
Connect4.board[Connect4.widthMinus][column] == 'O'){
if(Connect4.board[Connect4.widthMinus -
counter][column] == '|'){
Connect4.board[Connect4.widthMinus - counter][column] = 'X';
break;
}
}
counter +=
1;
}
}
}
---------------------------------------------------------------------------------------------------------------------
import java.util.Scanner;
import core.Connect4ComputerPlayer;
import core.Connect4;
public class Connect4TextConsole {
public static void main(String[] args) {
Connect4 game = new
Connect4();
boolean go = true; //true player O,
false player X
Scanner keyboard = new
Scanner(System.in); //creates a new scanner, used for console
input.
do {
go = !go;
game.boardLayout();
char
player;
if(go) {
//alternates who goes with player X going first.
player = 'O';
}else {
player =
Connect4ComputerPlayer.ComputerPlayer('X');
}
System.out.print("\nPlayer"+player+" - your turn. Choose a column
number from 1-7.");
boolean valid =
false;
while(!valid)
{ //Checks if it can place a disk and if not prompts
invalid move
valid = game.dropDisk(player,
keyboard.nextInt());
if(!valid) {
System.out.print("Invalid move");
}
}
} while(!game.draw() &
!game.winCondition()); //Checks if game is either a draw or any of
the 4 win conditions are met.
game.boardLayout();
if(game.winCondition()) {
System.out.printf("Player %s Won the game", (go?"O":"X")); //prints
which player wins the game, depends on the turn that it ended
on.
}
keyboard.close(); //stop resource
leak
}
}
-----------------------------------------------------------------------------------------------------------
public class Connect4 {
static char[][] board;
final static int width = 6;
final static int height = 7;
final static int widthMinus = width - 1;
public Connect4() {
board = new
char[width][height]; //42 spots to fill size of board,
creates board.
for(int i=0; i
for(int j=0; j
board[i][j] = ' ';
}
}
}
/* public char get(int i, int j) {
return board[i][j];
} */
public void boardLayout() { //creates layout for the
board and where | go.
for(int i=0; i
System.out.printf("|");
for(int j=0; j
System.out.printf("%c|", board[i][j]);
}
System.out.println();
}
}
public boolean dropDisk(char player, int
verticalWin) { //drops disk or X/O into selected slot
verticalWin--;
boolean drop =
false;
for(int i=board.length -
1; i >= 0; i--) {
if(board[i][verticalWin] == ' ') {
board[i][verticalWin] = player;
drop = true;
break;
}
}
return drop;
}
public boolean draw() { //if the game ends in a draw,
no more spaces to fill
for(int i=0; i
if(board[0][i] == ' ')
{
return false;
}
}
return true;
}
public boolean winCondition() { //Our method called
winCondition that uses boolean values for each time a player may
win.
//if the win condition can be met,
if not then continues game. Done so by having them set as false, if
one of them turns true then game ends.
boolean horizontalWin =
false;
boolean verticalWin =
false;
boolean diagonal1Win =
false;
boolean diagonal2Win =
false;
for (int row = 0; row
< board.length; row++) { //horizontalWin if four spots are
filled with correct character horizontally
for (int col = 0; col < board[0].length - 3; col++) {
if (board[row][col] != ' '
&& board[row][col] == board[row][col +
1]
&& board[row][col] == board[row][col +
2]
&& board[row][col] == board[row][col +
3]) {
horizontalWin = true;
}
}
}
for (int col =0; col
< board[0].length; col++) { //verticalWin if four spots are
filled with correct character vertically
for (int row = 0; row < board.length - 3; row++) {
if (board[row][col] != ' '
&& board[row][col] == board[row +
1][col]
&& board[row][col] == board[row +
2][col]
&& board[row][col] == board[row +
3][col]) {
verticalWin = true;
}
}
}
for (int row = 0; row
<= 2; row++) { //diagonal1win if four spots are filled with
correct character from top right to bottom left
for (int col = 3; col <= 6; col++) {
if (board[row][col] != ' '
&& board[row][col] == board[row + 1][col
- 1]
&& board[row][col] == board[row + 2][col
- 2]
&& board[row][col] == board[row + 3][col
- 3]) {
diagonal1Win = true;
}
}
}
for (int row = 0; row
<= 2; row++) { //diagonal2win if four spots are filled with
correct character from top left to bottom right
for (int col = 0; col <= 3; col++) {
if (board[row][col] != ' '
&& board[row][col] == board[row + 1][col
+ 1]
&& board[row][col] == board[row + 2][col
+ 2]
&& board[row][col] == board[row + 3][col
+ 3]) {
diagonal2Win = true;
}
}
}
if (horizontalWin |
verticalWin | diagonal1Win | diagonal2Win) //checks if any of them
are true, if so then game ends, if not then game continues
return true;
else
return false;
}
}
----------------------------------------------------------------------------------------------------
Connect4TextConsole.java
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import java.util.InputMismatchException;
public class Connect4TextConsole {
static Scanner scan = new Scanner(System.in);
static Connect4 game = new Connect4();
private static int p1Tokens = 21;
private static int p2Tokens = 21;
private static int totalTokens = 42;
private static boolean computerPlays = false;
private static char pChoice = 's';
private static char selection = 's';
/**
* Main method is the text console that the user interfaces with to
participate in the game.
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
game.displayBoard();
System.out.println();
System.out.println("Please enter 'C' if you would like to play
Connect4 using the text console; enter 'G' to play with the
GUI.");
selection = scan.next().charAt(0);
System.out.println();
if(selection == 'C') {
System.out.println("Begin Game. Enter 'P' if you want to play
against another player; enter 'C' to play against
computer.");
pChoice = scan.next().charAt(0);
computerPlays = evaluatePlayerChoice(pChoice);
//System.out.println("It is your turn. Choose a column number from
1-7.");
if (pChoice == 'C') {
while(totalTokens >0) {
playerXTurn();
computerTurn();
totalTokens = totalTokens - 2;
}
}
if(pChoice =='P') {
while(totalTokens >0) {
playerXTurn();
playerOTurn();
totalTokens = totalTokens - 2;
}
}
}
if(selection == 'G'){
try {
new Connect4GUI();
}catch (Exception e) {
e.printStackTrace();
System.out.println("Follow the instructions below if you want to
use the client/server interface.");
System.out.println("1. Select and run the Connect4Server.java
file.");
System.out.println("2. Select and run the Connect4Client.java
file.");
System.out.println("3. Select and run the Connect4Client.java file
again to play against another player.");
}
}
if((selection != 'C') &&(selection != 'G')) {
System.out.println("Invalid input!");
}
}
/**
* PlayerXTurn defines what occurs during playerX's turn.
*
* No return
*/
public static void playerXTurn() { //exception handling
try{
System.out.println("PlayerX - your turn. Choose a column number
from 1-7.");
int move1 = scan.nextInt();
Connect4.placeToken("X", move1, p1Tokens);
System.out.println();
game.displayBoard();
System.out.println();
}catch (InputMismatchException e){
System.out.println("Invaild Input!");
System.exit(0);
}
}
/**
* PlayerOTurn defines what occurs during playerO's turn.
*
* No return
*/
public static void playerOTurn() { //exception handling
try{
System.out.println("PlayerO - your turn. Choose a column number
from 1-7.");
int move1 = scan.nextInt();
game.placeToken("O", move1, p2Tokens);
System.out.println();
game.displayBoard();
System.out.println();
}catch (InputMismatchException e){
System.out.println("Invaild Input!");
System.exit(0);
}
}
/**
* computerTurn defines what occurs during the computer's
turn.
*
* No return
*/
public static void computerTurn() {
System.out.println("Computers turn.");
Connect4ComputerPlayer.chooseColumn();
System.out.println();
game.displayBoard();
System.out.println();
}
/**
* evaluates the users input to make sure the input is a viable
option
* @param userInput
* @return
*/
public static boolean evaluatePlayerChoice(char userInput) {
//false input handled
if(userInput == 'P') {
System.out.println("Start game against player.");
computerPlays = false;
}
if(userInput == 'C') {
System.out.println("Start game against computer.");
computerPlays = true;
}
if((userInput != 'P')&&(userInput != 'C')){
System.out.println("Invalid input!");
}
return computerPlays;
}
}
Connect4.java
import java.awt.Component;
public class Connect4 {
private int rows = 6;
private int columns = 7;
private static int totalTokens = 42;
private static int p1Tokens = 21;
private static int p2Tokens = 21;
public static String[] row1 = new String[] {"|"," " ,"|"," ","|","
","|"," ","|"," ","|"," ","|"," ","|"};
public static String[] row2 = new String[] {"|"," " ,"|"," ","|","
","|"," ","|"," ","|"," ","|"," ","|"};
public static String[] row3 = new String[] {"|"," " ,"|"," ","|","
","|"," ","|"," ","|"," ","|"," ","|"};
public static String[] row4 = new String[] {"|"," " ,"|"," ","|","
","|"," ","|"," ","|"," ","|"," ","|"};
public static String[] row5 = new String[] {"|"," " ,"|"," ","|","
","|"," ","|"," ","|"," ","|"," ","|"};
public static String[] row6 = new String[] {"|"," " ,"|"," ","|","
","|"," ","|"," ","|"," ","|"," ","|"};
/**Description of clearBoard()
*
* Starts new game by displaying a clear board.
*
*/
public void clearBoard() {
row1 = new String[] {"|"," " ,"|"," ","|"," ","|"," ","|"," ","|","
","|"," ","|"};
System.out.println(row1);
row2 = new String[] {"|"," " ,"|"," ","|"," ","|"," ","|"," ","|","
","|"," ","|"};
System.out.println(row2);
row3 = new String[] {"|"," " ,"|"," ","|"," ","|"," ","|"," ","|","
","|"," ","|"};
System.out.println(row3);
row4 = new String[] {"|"," " ,"|"," ","|"," ","|"," ","|"," ","|","
","|"," ","|"};
System.out.println(row4);
row5 = new String[] {"|"," " ,"|"," ","|"," ","|"," ","|"," ","|","
","|"," ","|"};
System.out.println(row5);
row6 = new String[] {"|"," " ,"|"," ","|"," ","|"," ","|"," ","|","
","|"," ","|"};
System.out.println(row6);
}
/** Description of remainingTokens
*
* Keeps track of how many tokens are left in the game by
* decrementing the remaining tokens total after each turn.
* @param tokens
*/
public static void remainingTokens(int tokens) {
tokens = tokens - 1;
}
public static int getP1Tokens() {
return p1Tokens;
}
public static int getP2Tokens() {
return p2Tokens;
}
/**
* Places the token in the location specified by the user
input.
* This method also keeps track of how many tokens each player has
left
* along with the total amount of tokens.
* @param token, column, playerTokens
*
*/
public static void placeToken(String token, int column, int
playerTokens) {
int columnIndex = getIndex(column);
int rowC = checkRow(columnIndex);
switch(rowC) {
case 1:
row1[columnIndex] = token;
remainingTokens(playerTokens);
remainingTokens(totalTokens);
break;
case 2:
row2[columnIndex] = token;
remainingTokens(playerTokens);
remainingTokens(totalTokens);
break;
case 3:
row3[columnIndex] = token;
remainingTokens(playerTokens);
remainingTokens(totalTokens);
break;
case 4:
row4[columnIndex] = token;
remainingTokens(playerTokens);
remainingTokens(totalTokens);
break;
case 5:
row5[columnIndex] = token;
remainingTokens(playerTokens);
remainingTokens(totalTokens);
break;
case 6:
row6[columnIndex] = token;
remainingTokens(playerTokens);
remainingTokens(totalTokens);
break;
case 99:
}
}
/**
* transforms the row1 array into a string
* @return board
*/
public static String getRow1() {
String board = "";
for(int a = 0; a<row1.length; a++) {
board = board +row1[a];
}
return board;
}
/**
* transforms the row2 array into a string
* @return board
*/
public static String getRow2() {
String board = "";
for(int a = 0; a<row2.length; a++) {
board = board +row2[a];
}
return board;
}
/**
* transforms the row3 array into a string
* @return board
*/
public static String getRow3() {
String board = "";
for(int a = 0; a<row3.length; a++) {
board = board +row3[a];
}
return board;
}
/**
* transforms the row4 array into a string
* @return board
*/
public static String getRow4() {
String board = "";
for(int a = 0; a<row4.length; a++) {
board = board +row4[a];
}
return board;
}
/**
* transforms the row5 array into a string
* @return board
*/
public static String getRow5() {
String board = "";
for(int a = 0; a<row5.length; a++) {
board = board +row5[a];
}
return board;
}
/**
* transforms the row6 array into a string
* @return board
*/
public static String getRow6() {
String board = "";
for(int a = 0; a<row6.length; a++) {
board = board +row6[a];
}
return board;
}
/**
* Description of displayBoard()
*
* This method displays the board and the tokens that have been
played thus far.
*/
public static void displayBoard() {
for(int a = 0; a<row1.length; a++) {
System.out.print(row1[a]);
}
System.out.println();
for(int a = 0; a<row2.length; a++) {
System.out.print(row2[a]);
}
System.out.println();
for(int a = 0; a<row3.length; a++) {
System.out.print(row3[a]);
}
System.out.println();
for(int a = 0; a<row4.length; a++) {
System.out.print(row4[a]);
}
System.out.println();
for(int a = 0; a<row5.length; a++) {
System.out.print(row5[a]);
}
System.out.println();
for(int a = 0; a<row6.length; a++) {
System.out.print(row6[a]);
}
}
/**Description of getIndex(int col)
*
* @param col
* @return returns index corresponding to the selected column
*/
public static int getIndex(int col) {
int columnIndex = (col * 2) - 1;
return columnIndex;
}
/**
* verifies that the column index of the row is empty so the token
can be placed at the lowest unfilled position in the column
* @param columnIndex
* @return int
*/
public static int checkRow(int columnIndex) {
String blank = " ";
if(row6[columnIndex] == blank) {
return 6 ;
}else {
if(row5[columnIndex] == blank) {
return 5 ;
}else
if(row4[columnIndex] == blank) {
return 4 ;
}else {
if(row3[columnIndex] == blank) {
return 3 ;
}else
if(row2[columnIndex] == blank) {
return 2 ;
}else {
if(row1[columnIndex] == blank) {
return 1 ;
}
}
}
}
return 99;
}
}
Connect4GUI.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.EventQueue;
public class Connect4GUI extends JFrame implements ActionListener
{
private JFrame frame;
private JPanel messagePanel, displayPanel, inputPanel,
startPanel;
private JButton userButton, computerButton, playerButton,
doneButton, nextButton, update;
private int column;
private JTextField textField;
private int cClicked = 0;
private int pClicked = 0;
private int turnCount = 1;
private boolean pT = false ;
private boolean uT = false;
/**
* The constructor that constructs the GUI
*/
Connect4GUI() {
frame = new JFrame("Connect4 GUI");
messagePanel = new JPanel (new FlowLayout());
displayPanel = new JPanel (new FlowLayout());
inputPanel = new JPanel (new FlowLayout());
startPanel = new JPanel (new FlowLayout());
JLabel row1 = new JLabel(Connect4.getRow1());
JLabel row2 = new JLabel(Connect4.getRow2());
JLabel row3 = new JLabel(Connect4.getRow3());
JLabel row4 = new JLabel(Connect4.getRow4());
JLabel row5 = new JLabel(Connect4.getRow5());
JLabel row6 = new JLabel(Connect4.getRow6());
JLabel inputDirection = new JLabel("Please insert the selected
column number (between 0-7) in the provided text field.");
textField = new JTextField("",20);
computerButton = new JButton("Computer");
computerButton.addActionListener(this);
playerButton = new JButton("Player");
playerButton.addActionListener(this);
userButton = new JButton("User");
userButton.addActionListener(this);
doneButton = new JButton("Done");
doneButton.addActionListener(this);
nextButton = new JButton("Next");
nextButton.addActionListener(this);
update = new JButton("Update");
update.addActionListener(this);
startPanel.add(computerButton);
startPanel.add(playerButton);
inputPanel.add(inputDirection);
inputPanel.add(textField);
inputPanel.add(doneButton);
messagePanel.add(nextButton);
displayPanel.setLayout(new BoxLayout(displayPanel,
BoxLayout.Y_AXIS));
row1.setText(Connect4.getRow1());
displayPanel.add(row1);
row1.setAlignmentX(Component.CENTER_ALIGNMENT);
row2.setText(Connect4.getRow2());
displayPanel.add(row2);
row2.setAlignmentX(Component.CENTER_ALIGNMENT);
row3.setText(Connect4.getRow3());
displayPanel.add(row3);
row3.setAlignmentX(Component.CENTER_ALIGNMENT);
row4.setText(Connect4.getRow4());
displayPanel.add(row4);
row4.setAlignmentX(Component.CENTER_ALIGNMENT);
row5.setText(Connect4.getRow5());
displayPanel.add(row5);
row5.setAlignmentX(Component.CENTER_ALIGNMENT);
row6.setText(Connect4.getRow6());
displayPanel.add(row6);
row6.setAlignmentX(Component.CENTER_ALIGNMENT);
displayPanel.add(nextButton);
nextButton.setAlignmentX(Component.CENTER_ALIGNMENT);
frame.add(startPanel);
frame.setSize(500,300);
frame.setResizable(false);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
/**
* this method is called when actions (buttons are clicked) and then
performs the necessary functions that need to occur when the button
is clicked
*/
@Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
switch (action) {
case "Computer":
JOptionPane.showMessageDialog(null, "Computer's turn.");
turnCount ++;
cClicked = cClicked + 1;
Connect4ComputerPlayer.chooseColumn();
//Connect4.displayBoard();
frame.setContentPane(displayPanel);
frame.invalidate();
frame.validate();
break;
case "Player":
JOptionPane.showMessageDialog(null, "Player's turn.");
pT = true;
turnCount++;
pClicked = pClicked + 1;
frame.setContentPane(inputPanel);
frame.invalidate();
frame.validate();
break;
case "User":
JOptionPane.showMessageDialog(null, "Your turn.");
uT = true;
turnCount++;
frame.setContentPane(inputPanel);
frame.invalidate();
frame.validate();
break;
case "Done":
frame.setContentPane(displayPanel);
column = Integer.parseInt(textField.getText());
if(pT == true) {
Connect4.placeToken("X", column, Connect4.getP1Tokens());
pT = false;
}
if(uT == true) {
Connect4.placeToken("O", column, Connect4.getP2Tokens());
uT = false;
}
//Connect4.displayBoard();
frame.invalidate();
frame.validate();
break;
case "Next":
int remainder = turnCount%2;
if(cClicked > 0 && remainder != 0) {
JOptionPane.showMessageDialog(null, "Computer's turn.");
turnCount++;
Connect4ComputerPlayer.chooseColumn();
frame.setContentPane(displayPanel);
frame.invalidate();
frame.validate();
}
if(pClicked > 0 && remainder != 0) {
JOptionPane.showMessageDialog(null, "Player's turn.");
turnCount++;
frame.setContentPane(inputPanel);
frame.invalidate();
frame.validate();
}
if(remainder == 0) {
JOptionPane.showMessageDialog(null, "Your turn.");
turnCount++;
frame.setContentPane(inputPanel);
frame.invalidate();
frame.validate();
}
break;
case "Update":
break;
}
}
}
Connect4ComputerPlayer.java
package project2;
import java.util.Random;
public class Connect4ComputerPlayer extends Connect4{
private static boolean filled = false;
private static int computersTokens = 21;
private static String token = "O";
/**
* ChooseColumn is a method that automatically determines where to
put
* the token when playing against the computer.The return value is
the
* column that has been selected for token placement.
*/
public static void chooseColumn() {
Random rand = new Random();
int column;
column = rand.nextInt(7)+1; //choose a random number between 1 and
7
while (columnFull(column) == true) {
column = rand.nextInt(7)+1;
}
placeToken(token, column,computersTokens);
}
/**
* column full checks to see if the column selected is full. If it
is, the
* method will return true and if the column is not full then the
method will
* return true.
* @param col
* @return booleanResult
*/
public static boolean columnFull(int col) {
int index = getIndex(col);
int check = checkRow(index);
if (check == 99) {
filled = true;
}else {
filled = false;
}
return filled;
}
}