d2jsp
Log InRegister
d2jsp Forums > Off-Topic > General Chat > User Blogs > Assignment Log
Prev123
Add Reply New Topic
Member
Posts: 20,928
Joined: Mar 18 2009
Gold: 435,910.13
May 20 2013 04:45am
C4

Code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

/*
* A 2 player connect4 game implemented with JFrame and java awt/swing.
*/
public class c4gui extends JApplet implements ActionListener{
int score1 = 0;
int score2 = 0;

String p1 = "Player 1";
String p2 = "Player 2";
int turn = 0;

boolean gamestate = false;//used to determine if start was pressed
boolean marker = false;//used for isFull method

JPanel container; //top level container used to hold everything

JPanel top; //holds elements in top part of gui
JPanel pIn;
JLabel tp1;
JTextField tf1;
JLabel tp2;
JTextField tf2;
JPanel score;
JLabel scoreT;
JLabel p1score;
JLabel p2score;

JTextPane gameM;//game message display area
JButton[] moves; //array of moves button
JButton[] board; //array of gamee board buttons
JPanel center;  //holds moves and board


JPanel bottom; //holds start and reset
JButton start;
JButton reset;

/*
 * Construct the gui.
 */
public c4gui(){
 
 container = new JPanel();
 container.setLayout(new BorderLayout());
 container.setPreferredSize(new Dimension(700,900));
 
 
 //top part of the gui------------------------------
 top = new JPanel();
 top.setLayout(new GridLayout(1,3));
 //left pane
 pIn = new JPanel();
 pIn.setLayout(new BoxLayout(pIn, BoxLayout.Y_AXIS));
 tp1 = new JLabel("Player 1 Name");
 tp1.setForeground(Color.RED);
 tp1.setFont(new Font("Serif", Font.PLAIN, 18));
 tf1 = new JTextField();
 tp2 = new JLabel("Player 2 Name");
 tp2.setForeground(Color.GREEN);
 tp2.setFont(new Font("Serif", Font.PLAIN, 18));
 tf2 = new JTextField();
 pIn.add(tp1);
 pIn.add(tf1);
 pIn.add(tp2);
 pIn.add(tf2);
 top.add(pIn);
 
 //middle pane
 score = new JPanel();
 score.setLayout(new BoxLayout(score, BoxLayout.Y_AXIS));
 scoreT = new JLabel("\t \t \t CURRENT \t SCORE:");
 scoreT.setFont(new Font("Serif", Font.BOLD, 18));
 p1score = new JLabel("\t \t \t " + p1 + "  : " + score1);
 p1score.setForeground(Color.RED);
 p1score.setFont(new Font("Serif", Font.PLAIN, 18));
 p2score = new JLabel("\t \t \t " + p2 + "  : " + score2);
 p2score.setForeground(Color.GREEN);
 p2score.setFont(new Font("Serif", Font.PLAIN, 18));
 score.add(scoreT);
 score.add(p1score);
 score.add(p2score);
 top.add(score);
 
 //right pane
 gameM = new JTextPane();
 gameM.setEditable(false);
 gameM.setText("Please ENTER player \nnames and press\nStart.");
 gameM.setFont(new Font("Serif", Font.PLAIN, 18));
 top.add(gameM);
 container.add(top, BorderLayout.PAGE_START);
 
 
 //center game board---------------------
 moves = new JButton[7];
 board = new JButton[42];
 center = new JPanel(new GridLayout(7,7));
 for(int x =0; x<moves.length; x++){
  moves[x] = new JButton();
  moves[x].setBackground(Color.YELLOW);
  moves[x].addActionListener(this);
  center.add(moves[x]);
 }
 for(int x =0; x<board.length; x++){
  board[x] = new JButton();
  board[x].setEnabled(false);
  center.add(board[x]);
 }
 
 container.add(center, BorderLayout.CENTER);
 
 
 //bottom part---------------------------
 bottom = new JPanel();
 bottom.setLayout(new BorderLayout());
 start = new JButton();
 reset = new JButton();
 start.addActionListener(this);
 start.setText("Start");
 start.setFont(new Font("Serif", Font.BOLD, 25));
 reset.setText("Reset");
 reset.addActionListener(this);
 reset.setFont(new Font("Serif", Font.BOLD, 25));
 bottom.add(start, BorderLayout.LINE_START);
 bottom.add(reset, BorderLayout.LINE_END);
 container.add(bottom, BorderLayout.PAGE_END);
}


/*uncomment if you want to turn into applet
public void init() {
   c4gui pad = new c4gui();
   this.setContentPane(pad.container);
   setSize(560, 700);
}
*/

/*
 * (non-Javadoc)
 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
 */
public void actionPerformed(ActionEvent ae){
 
 if(ae.getSource() == start){
  if(gamestate == false){
   gamestate = true;
   enableMoves();
   //players can't change their names after pressing start
   tf1.setEditable(false);
   tf2.setEditable(false);
   //deciding player names, default if nothing enteGREEN
   if(!tf1.getText().equals("")){
    //if name is too long trims it to 8 char
    if(tf1.getText().length() >= 8){
     tf1.setText(tf1.getText().substring(0,8));
     p1 = tf1.getText().substring(0,8);
    }
    else{
     p1 = tf1.getText();
    }
   }
   else{
    p1.equals("Player 1");
   }
   if(!tf2.getText().equals("")){
    if(tf2.getText().length() >= 8){
     tf2.setText(tf2.getText().substring(0,8));
     p2 = tf2.getText().substring(0,8);
     
    }
    else{
     p2 = tf2.getText();
    }
   }
   else{
    p2.equals("Player 2");
   }
   p1score.setText("\t \t \t " + p1 + "  : " + score1);
   p2score.setText("\t \t \t " + p2 + "  : " + score2);
   
   //random number generator to give each player 50% chance to go 1st
   Random numGen = new Random();
   turn = numGen.nextInt(2) + 1;
   //update game message
   if(turn == 1){
    gameM.setText(p1 + "'s \nmove.");
   }
   else{
    gameM.setText(p2 + "'s \nmove.");
   }
   
  }
  else{
   gamestate = true;
  }
 }
 
 
 //actionlistener for move squares
 for(int m =0; m<7; m++){
  //finds which column was selected
  if(ae.getSource() == (moves[m])){
   //only works after "Start" is clicked
   if(gamestate == true){
   
     for(int x = m + 35; x >= m; x -= 7){
      //if column full, do nothing
      if((board[m].getBackground()== Color.GREEN) || (board[m].getBackground()== Color.RED) ){
       return;
      }
           //check column, find the closes square to the bottom row that isn't coloGREEN
       //set its color according to which player made the move.
       if(((board[x].getBackground() != Color.GREEN) && (board[x].getBackground() != Color.RED)) ){
       marker = true;
       if(turn == 1){
        board[x].setBackground(Color.RED);
       
        if(checkWin(x, 1)){
         gameM.setText(p1 + " \nWINS!");
         score1+=1;
         p1score.setText("\t \t \t " + p1 + "  : " + score1);
         disableMoves();
         return;
        }
        if(isFull()){
         gameM.setText("It's a TIE!");
         disableMoves();
         return;
        }
        break;
       }
       //turn = 2
       else{
        board[x].setBackground(Color.GREEN);
       
        if(checkWin(x, 2)){
         gameM.setText(p2 + " \nWINS!");
         score2+=1;
         p2score.setText("\t \t \t " + p2 + "  : " + score2);
         disableMoves();
         return;
        }
        if(isFull()){
         gameM.setText("It's a TIE!");
         disableMoves();
         return;
        }
        break;
       }
       
      }
     
     
    }
    //Update game message for the next move
   
    if(turn == 1){
     turn = 2;
     gameM.setText(p2 + "'s \nmove.");
     
    }
    else{
     turn = 1;
     gameM.setText(p1 + "'s \nmove.");
    }
   
   }
  }
 }
 //After "Reset" is clicked
 if(ae.getSource() == reset){
  gamestate = false;
  p1score.setText("\t \t \t " + p1 + "  : " + score1);
  p2score.setText("\t \t \t " + p2 + "  : " + score2);
  //revert all squares to colorless
  for(int x = 0; x < board.length; x++){
   board[x].setBackground(null);
  }
  gameM.setText("Press Start when ready.\nA new game will begin.");
  turn = 0;
 }
 
}
/*
 * Enable all Move buttons.
 */
private void enableMoves(){
 for(int x = 0; x < moves.length; x+=1){
  moves[x].setEnabled(true);
 }
}
/*
 * Disable all Move buttons.
 */
private void disableMoves(){
 for(int x = 0; x < moves.length; x+=1){
  moves[x].setEnabled(false);
 }
}
/*
 * Check to see if there are any valid moves left.
 * @return true if no valid moves left.
 */
private boolean isFull(){
 for(int x = 0; x <board.length; x+=1){
  if( (board[x].getBackground() != Color.RED) && (board[x].getBackground() != Color.GREEN) ){
   return false;
  }
 }
 return true;
}
/*
 * Checks if there is a win for the player that made the last move
 * This is an overview of the board[p] button positions relative to the game board
    0 1 2 3 4 5 6
  7 8 9 10 11 12 13
  14 15 16 17 18 19 20
  21 22 23 24 25 26 27
  28 29 30 31 32 33 34
  35 36 37 38 39 40 41
 methods checks for wins in the vertical, horizontal and both diagonal directions
    based on the last move's position i.e. 26
 * @param move The number representation of the last move made.
 * @param color The color of the last move made
 * @return true is there is a win state
 */
private boolean checkWin(int move, int color){
 //Counter to record number consecutive block, 4+ is win
 int h = 1;// "-" counter
 int v = 1;// "|" counter
 int d1 = 1;// "\" counter
 int d2 = 1;// "/" counter
 //ArrayLists holding the numbers of the outer edges of the game board, used to tell the computer
 //to stop checking for consecutive colors when arrive at the edge row/column.
 ArrayList<Integer> tBound = new ArrayList<Integer>();//0,1,2,3,4,5,6
 for(int x = 0; x <= 6; x+=1){
  tBound.add(x);
 }
 ArrayList<Integer> bBound = new ArrayList<Integer>();//35,36,37,38,39,40,41
 for(int x = 35; x <= 41; x+=1){
  bBound.add(x);
 }
 ArrayList<Integer> lBound = new ArrayList<Integer>();//0,7,14,21,28,35
 for(int x = 0; x <= 35; x+=7){
  lBound.add(x);
 }
 ArrayList<Integer> rBound = new ArrayList<Integer>();//6,13,20,27,34,41
 for(int x = 6; x <= 41; x+=7){
  rBound.add(x);
 }
 
 //check horizontally (check in -> direction)
 int p = move; //reference the current square being examined, initially the latest move
 int count = 0;
 //if reach blank square or board edge, stop loop
 while((board[p].getBackground() == Color.GREEN) || (board[p].getBackground() == Color.RED) ){
  //if last move was made by p1
  if(color == 1){
   //incriment appropriate counter for each square of the same color, break otherwise
   if(board[p].getBackground() == Color.RED){
    if(count>0){//does not count the first square being examined as it's already known what color it is
     h += 1;//increment the
    }
    if(rBound.contains(p)){
     break;
    }
    p += 1;//move to the next square to examine in this case in the -> direction
   }
   else{
    break;
   }
  }
  //if last move was made by p2
  if(color == 2){
   if(board[p].getBackground() == Color.GREEN){
    if(count>0){
     h += 1;
    }
    if(rBound.contains(p)){
     break;
    }
    p += 1;
   }
   else{
    break;
   }
  }
  count+=1;
 }
 //check horizontal (check in <- direction)
 p = move;
 count = 0;
 while((board[p].getBackground() == Color.GREEN) || (board[p].getBackground() == Color.RED) ){
  if(color == 1){
   if(board[p].getBackground() == Color.RED){
    if(count>0){
    h += 1;
    }
    if(lBound.contains(p)){
     break;
    }
   
    p -= 1;
   }
   else{
    break;
   }
  }
  if(color == 2){
   if(board[p].getBackground() == Color.GREEN){
    if(count>0){
     h += 1;
    }
    if(lBound.contains(p)){
     break;
    }
    p -= 1;
   }
   else{
    break;
   }
  }
  count+=1;
 }
 
 //check vertical (check for wins in this | direction)
 p = move;
 count = 0;
 while( (board[p].getBackground() == Color.GREEN) || (board[p].getBackground() == Color.RED)){
  if(color == 1){
   if(board[p].getBackground() == Color.RED){
    if(count>0){
     v += 1;
    }
    if(bBound.contains(p)){
     break;
    }
    p += 7;
   }
   else{
    break;
   }
  }
  if(color == 2){
   if(board[p].getBackground() == Color.GREEN){
    if(count>0){
     v += 1;
    }
    if(bBound.contains(p)){
     break;
    }
    p += 7;
   }
   else{
    break;
   }
  }
  count+=1;
 }
 
 //check diagonal 1(check for wins in this \ direction)
 p = move;
 count = 0;
 while((board[p].getBackground() == Color.GREEN) || (board[p].getBackground() == Color.RED) ){
  if(color == 1){
   if(board[p].getBackground() == Color.RED){
    if(count>0){
     d1 += 1;
    }
    if( (bBound.contains(p)) ||(rBound.contains(p)) ){
     break;
    }
    p += 8;
   }
   else{
    break;
   }
  }
  if(color == 2){
   if(board[p].getBackground() == Color.GREEN){
    if(count>0){
     d1 += 1;
    }
    if( (bBound.contains(p)) ||(rBound.contains(p)) ){
     break;
    }
    p += 8;
   }
   else{
    break;
   }
  }
  count+=1;
 }
 
 p = move;
 count = 0;
 while((board[p].getBackground() == Color.GREEN) || (board[p].getBackground() == Color.RED) ){
  if(color == 1){
   if(board[p].getBackground() == Color.RED){
    if(count>0){
     d1 += 1;
    }
    if( (tBound.contains(p)) || (lBound.contains(p)) ){
     break;
    }
    p -= 8;
   }
   else{
    break;
   }
  }
  if(color == 2){
   if(board[p].getBackground() == Color.GREEN){
    if(count>0){
     d1 += 1;
    }
    if((tBound.contains(p))||(lBound.contains(p))){
     break;
    }
    p -= 8;
   }
   else{
    break;
   }
  }
  count+=1;
 }
 
 //check diagonal 2 (check for wins in this / direction)
 p = move;
 count = 0;
 while( (board[p].getBackground() == Color.GREEN) || (board[p].getBackground() == Color.RED) ){
  if(color == 1){
   if(board[p].getBackground() == Color.RED){
    if(count>0){
     d2 += 1;
    }
    if( (bBound.contains(p))||(lBound.contains(p)) ){
     break;
    }
    p += 6;
   }
   else{
    break;
   }
  }
  if(color == 2){
   if(board[p].getBackground() == Color.GREEN){
    if(count>0){
     d2 += 1;
    }
    if( (bBound.contains(p))||(lBound.contains(p)) ){
     break;
    }
    p += 6;
   }
   else{
    break;
   }
  }
  count+=1;
 }
 
 p = move;
 count = 0;
 while( (board[p].getBackground() == Color.GREEN) || (board[p].getBackground() == Color.RED) ){
  if(color == 1){
   if(board[p].getBackground() == Color.RED){
    if(count>0){
     d2 += 1;
    }
    if( (tBound.contains(p)) ||(rBound.contains(p)) ){
     break;
    }
    p -= 6;
   }
   else{
    break;
   }
  }
  if(color == 2){
   if(board[p].getBackground() == Color.GREEN){
    if(count>0){
     d2 += 1;
    }
    if( (tBound.contains(p)) ||(rBound.contains(p)) ){
     break;
    }
    p -= 6;
   }
   else{
    break;
   }
  }
  count+=1;
 }
 //if there are 4 or more same colors in a row return true otherwise false
 if((h>=4)||(v>=4)||(d1>=4)||(d2>=4)){
  return true;
 }
 return false;
}
}


Code
import javax.swing.*;

public class connect4 {

/**
 * @param args
 */
public static void main(String[] args) {
 c4gui c4 = new c4gui();
 
 JFrame window = new JFrame("Connect 4");
 window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 window.setContentPane(c4.container);
 window.pack();
 window.setVisible(true);
 

}

}


This post was edited by bakalolo on May 20 2013 04:47am
Member
Posts: 20,928
Joined: Mar 18 2009
Gold: 435,910.13
May 20 2013 04:47am
:blink:
Member
Posts: 20,928
Joined: Mar 18 2009
Gold: 435,910.13
Go Back To User Blogs Topic List
Prev123
Add Reply New Topic