Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public interface Player {
- public String getUserInput(Board Connect4) throws IOException;
- public boolean hasWon(Board Connect4);
- }
- public class HumanPlayer implements Player {
- private int boardColumn = 0;
- @Override
- public String getUserInput(Board Connect4) throws IOException {
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- //Player One Logic ----------------------------------------------------------------
- while (true) {
- System.out.println();
- System.out.println("Player 1, please select your column:");
- boardColumn = Integer.parseInt(br.readLine());
- if (Connect4.canMakeMove(boardColumn)) {
- break;
- } else
- System.out.println("Column " + boardColumn + " is already full!!");
- }
- return null;
- }
- @Override
- public boolean hasWon(Board Connect4) {
- if(Connect4.placeCounter(boardColumn, 1)){
- Connect4.printBoard();
- System.out.println("");
- System.out.println("Congratulations! Player 1 has won the game");
- return true;
- }
- return false;
- }
- }
- public class ComputerPlayer implements Player{
- private int boardColumn = 0;
- @Override
- public String getUserInput(Board Connect4) throws IOException {
- outer:
- while(true){
- System.out.println("");
- System.out.println("The Computer has selected a column and played a counter");
- System.out.println("");
- Random r = new Random();
- int num = r.nextInt(7);
- boardColumn = num;
- if(Connect4.canMakeMove(boardColumn)){
- break;
- }
- else
- System.out.println("Column "+boardColumn+" is already full!!");
- }
- return null;
- }
- @Override
- public boolean hasWon(Board Connect4) {
- if(Connect4.placeCounter(boardColumn, 2)){
- Connect4.printBoard();
- System.out.println("");
- System.out.println("Unlucky! The Computer has won this game");
- return true;
- }
- return false;
- }
- }
- public class Main {
- public static void main(String args[])throws IOException{
- Board Connect4 = new Board();
- HumanPlayer human = new HumanPlayer();
- ComputerPlayer computer = new ComputerPlayer();
- while(!human.hasWon(Connect4) && !computer.hasWon(Connect4)) {
- Connect4.printBoard();
- human.getUserInput(Connect4);
- computer.getUserInput(Connect4);
- }
- }
- public static void welcomeMessage() {
- System.out.println("Welcome to Connect 4");
- System.out.println("There are 2 players red and yellow");
- System.out.println("Player 1 is Red, Player 2 is Yellow");
- System.out.println("To play the game type in the number of the boardColumn you want to drop you counter in");
- System.out.println("A player wins by connecting 4 counters in a row - vertically, horizontally or diagonally");
- System.out.println("");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement