Skip to content

Instantly share code, notes, and snippets.

@molayodecker
Last active December 11, 2016 11:15
Show Gist options
  • Save molayodecker/8530787cce382d22da1591ae912ae276 to your computer and use it in GitHub Desktop.
Save molayodecker/8530787cce382d22da1591ae912ae276 to your computer and use it in GitHub Desktop.
Recurse Pair Programming Interview tasks

Tic Tac Toe game

Playground

This project contains two files, Game.java and playGround.java The main class with public static void main function is Game.java and the subclass which contains and Constructor all the methods is playGround.java


This Game has been developed to use the Characters 'O' and 'X'to represent players so users need not create players. Also humans count from 1 so i have created the game for players to move from 1 - 3 eventhough machines and computers count from zero (0). Hence the first move to the first position of the two-dimensional array will be [0][0] but the user will have to enter [1][1] because humans count from 1.


As a player i should be presented with a menu to choice between playing with another human or playing against a computer.

As a player i should be able to quit the game if i do not want to play.


As a player i should be so be able to have turns in the game, so that my opponent can also make moves.


As a player i should be able to know when the Game has come to an end, so that i can know if the game was a draw or a win.


displayPlayGround() method is responsible for displaying the tic-tac-toe game. By creating horizonatal and vertical lines (Using dashes)


play() method is responsible for checking if the position the player is play is empty before playing that position


gameActive() method checks if the game is still active. Returns true is game is active and false if game is not


askPlayer() method is responsible for capturing row and col number(1-3) for the user


askComputer() method is responsible for capturing random rows and random cols number(1-3) for the computer


inValid() method checks if the rows and cols inputs are between number 1 - 3 and if positions are empty


isEmpty() method checks if the rows and cols positions are empty


checkWinner() method is responsible for checking if there is a Winner


playWithHuman() method is swtiches turns between two human players


playWithComputer() method is swtiches turns between a human and a Computer


promptMenu() method interates through the menu options and displays them to the user to select.


run() method uses a switch statement to choice between playing with a human or computer

import java.io.IOException;
/**
* Created by molayodecker on 28/11/2016.
* Welcome
* Before your interview, write a program that lets two humans play a game of Tic Tac Toe in a terminal.
* The program should let the players take turns to input their moves.
* The program should report the outcome of the game.
* During your interview, you will pair on adding support for a computer player to your game.
* You can start with random moves and make the AI smarter if you have time.
*
* Game : Tic Tac Toe game
* | |
* -----|-----|-----
* | |
* -----|-----|-----
* | |
*
*
*/
public class Game {
public static void main(String[] args) throws IOException {
playGround playground = new playGround();
System.out.println("Welcome to the Tic Tac Toe game");
System.out.println("Please follow the Menu to start the Game\n");
playground.run();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
/**
* Created by molayodecker on 28/11/2016.
* Welcome
* Before your interview, write a program that lets two humans play a game of Tic Tac Toe in a terminal.
* The program should let the players take turns to input their moves.
* The program should report the outcome of the game.
* During your interview, you will pair on adding support for a computer player to your game.
* You can start with random moves and make the AI smarter if you have time.
*
* Game : Tic Tac Toe game
* | |
* -----|-----|-----
* | |
* -----|-----|-----
* | |
*
*
*/
public class playGround {
private char[][] playground;
private boolean gameOngoing = true;
Map<String,String> tMenu;
BufferedReader rd;
public playGround() {
this.playground = new char[3][3];
rd = new BufferedReader(new InputStreamReader(System.in));
tMenu = new LinkedHashMap<>();
tMenu.put("Human", "Play with Human");
tMenu.put("Computer", "Play against Computer");
tMenu.put("Quit", "Give up, Exiting program......");
//Check to make sure all the rows are empty
for (int row = 0; row < playground.length; row++){
Arrays.fill(playground[row], ' ');
}
}
/*
* This method just displays the tictactoe playground
* */
public void displayPlayGround(){
for (int row = 0; row < playground.length; row++){
for(int col = 0; col < playground[0].length; col++){
System.out.print("\t" +playground[row][col]);
if(col == 0 || col == 1){
System.out.print("\t|");
}
}
if(row == 0 || row == 1) {
System.out.printf("%n-------------------------%n");
}
}
}
/*
This method checks if the row or col the player is trying to play is empty or filled.
if it's not empty return false else add the player in that position
* */
public boolean play(char player, int row, int col){
if(row >= 0 && row <= 2 && col >= 0 && col <= 2){
if(playground[row][col] != ' '){
return false;
}else {
playground[row][col] = player;
return true;
}
}
return false;
}// end of play
/*This method checks if the game is ongoing or still active
The default value for gameOngoing is true
So this method sets the gameActive method to true
* */
public boolean gameActive(){
return gameOngoing;
}
/*
* This method ask the player to enter the rows and columns he want to play.
* If the move is valid (Meaning if it has not been played) it plays that position
* */
public void askPlayer(char player){
Scanner stdin = new Scanner(System.in);
int row,col;
do{
System.out.printf("Player %s, please enter a row (1 - 3): ", player);
row = stdin.nextInt();
System.out.printf("Player %s, Please enter a column (1 - 3): ", player);
col = stdin.nextInt();
}while (inValid(row,col));
play(player,row-1,col-1);
}
public void askComputer(char player){
int row,col;
Random rand = new Random();
do{
row = rand.nextInt(3)+1;
col = rand.nextInt(3)+1;
}while (row != -1 && col != -1 && inValid(row,col) && isEmpty(row,col));
play(player,row-1,col-1);
System.out.printf("Computer has played (%s) %n", player);
System.out.println("Player's turn!");
//return ' ';
}
/* Invalid method checks to see if the move is between 1 - 3 and not empty.
If the move is valid return true if not return false
* */
public boolean inValid(int row, int col){
if(row > 3 || row < 1 || col > 3 || col < 1 || !isEmpty(row,col)){
return true;
}else{
return false;
}
}
public boolean isEmpty(int row, int col){
if(playground[row-1][col-1] == ' '){
return true;
}else {
System.out.println("Wrong move");
return false;
}
}
/*
The checkwinner() method checks to see if 'X' or 'O' has been able to form a straight horizontal, Vertical
or diagonal pattern.
* */
public boolean checkWinner(){
for(int row = 0; row < playground.length; row++){
if(playground[row][0] == playground[row][1] && playground[row][1] == playground[row][2] && playground[row][0] != ' '){
System.out.println("The winner is " + playground[row][0]);
gameOngoing = false;
}
}
for(int col = 0; col < playground.length; col++){
if(playground[0][col] == playground[1][col] && playground[1][col] == playground[2][col] && playground[0][col] != ' '){
System.out.println("The winner is " + playground[0][col]);
gameOngoing = false;
}
}
if(playground[0][0] == playground[1][1] && playground[1][1] == playground[2][2] && playground[0][0] != ' '){
System.out.println("The winner is " + playground[0][0]);
gameOngoing = false;
}
if(playground[0][2] == playground[1][1] && playground[1][1] == playground[2][0] && playground[0][2] != ' '){
System.out.println("The winner is " + playground[0][2]);
gameOngoing = false;
}
return false;
}
public void playWithHuman(){
displayPlayGround();
System.out.println("\n");
int counter = 1;
while (gameActive() && counter < 10){
if(counter % 2 == 0){
askPlayer('O');
}else {
askPlayer('X');
}
counter++;
displayPlayGround();
System.out.println("\n");
checkWinner();
System.out.println("\n");
if(counter == 10){
System.out.println("We have a draw!");
}
}
}
public void playWithComputer() {
System.out.println("\n");
int counter = 1;
while (gameActive() && counter < 10){
if(counter % 2 == 0){
askPlayer('O');
}else {
askComputer('X');
}
counter++;
displayPlayGround();
System.out.println("\n");
checkWinner();
System.out.println("\n");
if(counter == 10){
System.out.printf("We have a draw! %n%n");
}
}
}
public String promptMenu() throws IOException {
for(Map.Entry<String, String> options : tMenu.entrySet()){
System.out.printf("%s - %s %n%n", options.getKey(),options.getValue());
}
System.out.print(" What do you want to do : ");
String choice = rd.readLine();
System.out.printf("%n--------------------------- %n%n");
return choice.trim().toLowerCase();
}
public void run() throws IOException {
String choice = "";
do{
choice = promptMenu();
switch (choice){
case "human":
playWithHuman();
break;
case "computer":
playWithComputer();
break;
case "quit":
System.out.println("Goodbye...");
break;
default:
System.out.printf("Unknown choice: \"%s\" Choice, Please Try again! %n%n", choice);
break;
}
}while(!choice.equals("quit"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment