Skip to content

Instantly share code, notes, and snippets.

@cbilson
Last active May 12, 2017 17:03
Show Gist options
  • Save cbilson/ae20c61b199fd734f566a3758bce5ecc to your computer and use it in GitHub Desktop.
Save cbilson/ae20c61b199fd734f566a3758bce5ecc to your computer and use it in GitHub Desktop.
import java.util.Scanner;
public class BoardMatrix {
static char[][] matrix = new char[3][3];
public static void main(String[] args) {
BoardMatrix.assignMatrix();
boolean gameOver = false;
Scanner scanner = new Scanner(System.in);
while (!gameOver) {
System.out.println("What's your move X?");
int row = scanner.nextInt();
int col = scanner.nextInt();
placeMark(row, col, 'X');
printMatrix();
if (detectWinner('X')) {
gameOver = true;
System.out.println("Congrats X!");
continue;
}
System.out.println("What's your move O?");
row = scanner.nextInt();
col = scanner.nextInt();
placeMark(row, col, 'O');
printMatrix();
if (detectWinner('O')) {
gameOver = true;
System.out.println("Congrats O!");
continue;
}
}
}
public static boolean detectWinner(char player) {
// check for a row all the same
for (char[] row : matrix) {
int matches = 0;
for (char c : row) {
if (c == player)
matches++;
}
if (matches == 3) return true;
}
// check for a column all the same
for (int col = 0; col < 3; col++) {
int count = 0;
for (char[] row : matrix)
if (row[col] == player)
count++;
if (count == 3) return true;
}
// left diagonal
int count = 0;
for (int rowCol = 0; rowCol < 3; rowCol++) {
if (matrix[rowCol][rowCol] == player)
count++;
}
if (count == 3) return true;
// right diagonal
for (int row = 0; row < 3; row++) {
int matches = 0;
int col = 2 - row;
if (matrix[row][col] == player)
matches++;
if (matches == 3) return true;
}
// must not be a winner
return false;
}
public static boolean isOccupied(int row, int col) {
return matrix[row][col] != '-';
}
public static void placeMark(int row, int col, char who){
if (!isOccupied(row, col))
matrix[row][col] = who;
}
//====================================================
//Create a 3 X 3 matrix
public static void assignMatrix()
{
for (int r=0; r<matrix.length; r++){
for(int c=0; c<matrix[0].length; c++){
matrix[r][c]='-';
}
}
}
//===========================================
//Printing a 3 X 3 matrix
public static void printMatrix()
{
for (int r=0; r<matrix.length; r++){
for(int c=0; c<matrix[0].length; c++){
System.out.print(matrix[r][c]+" ");
}
System.out.println();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment