Created
September 18, 2015 17:30
-
-
Save rbreslow/e858445f1266b2d6806f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// name: TicTacToe | |
// date: Friday, September 18th, 2015 | |
// desc: CLI TicTacToe game | |
import java.util.Scanner; | |
public class TicTacToe { | |
public static char[][] board; | |
public static void main(String[] args) { | |
board = new char[3][3]; | |
for(int i = 0; i < board.length; i++) { | |
for(int j = 0; j < board[i].length; j++) { | |
board[i][j] = '-'; | |
} | |
} | |
// the game loop | |
Scanner s = new Scanner(System.in); | |
boolean inGame = true; | |
boolean turn = false; | |
while(inGame) { | |
printBoard(); | |
int x = 0; | |
int y = 0; | |
do { | |
System.out.print("X: "); | |
x = s.nextInt() - 1; | |
System.out.print("Y: "); | |
y = s.nextInt() - 1; | |
} while(x >= board.length || y >= board.length || board[y][x] != '-'); | |
if(turn) { | |
turn = false; | |
board[y][x] = 'x'; | |
} else { | |
turn = true; | |
board[y][x] = 'o'; | |
} | |
if(checkWinner() != '-') { | |
printBoard(); | |
System.out.print("Winner is: " + checkWinner()); | |
inGame = false; | |
} | |
} | |
s.close(); | |
} | |
public static void printBoard() { | |
for(int i = 0; i < board.length; i++) { | |
for(int j = 0; j < board[i].length; j++) { | |
System.out.print(board[i][j]); | |
} | |
System.out.print("\n"); | |
} | |
} | |
public static char checkWinner() { | |
if((board[0][0] == board[0][1]) && (board[0][1] == board[0][2])) | |
return board[0][0]; | |
if((board[1][0] == board[1][1]) && (board[1][1] == board[1][2])) | |
return board[1][0]; | |
if((board[2][0] == board[2][1]) && (board[2][1] == board[2][2])) | |
return board[2][0]; | |
if((board[0][0] == board[1][0]) && (board[1][0] == board[2][0])) | |
return board[0][0]; | |
if((board[0][1] == board[1][1]) && (board[1][1] == board[2][1])) | |
return board[0][1]; | |
if((board[0][2] == board[1][2]) && (board[1][2] == board[2][2])) | |
return board[0][2]; | |
if((board[0][0] == board[1][1]) && (board[1][1] == board[2][2])) | |
return board[0][0]; | |
if((board[0][2] == board[1][1]) && (board[1][1] == board[2][0])) | |
return board[0][2]; | |
return '-'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment