Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class TicTacToe {
- // String[row][col]
- private String[][] board;
- private boolean xturn;
- String player;
- public TicTacToe(){
- board = new String[3][3];
- for(int i=0; i<3; i++){
- for(int j=0; j < 3; j++){
- board[i][j] = "-";
- }
- }
- xturn = false;
- player = "O";
- }
- public void printBoard(){
- System.out.println(" 0 1 2");
- for(int i = 0; i < 3; i++){
- System.out.println(i + " " +board[i][0]
- + " " + board[i][1] + " " + board[i][2]);
- }
- if(!checkWin()){
- System.out.println("It is " + player + "'s turn.");
- }
- }
- public boolean isValid(int r, int c){
- if(board[r][c].equals("-")){
- return true;
- }
- return false;
- }
- public void placePlayer(int r, int c){
- if(xturn){
- player = "X";
- board[r][c] = player;
- player = "O";
- } else {
- player = "O";
- board[r][c] = player;
- player = "X";
- }
- xturn = !xturn; //CHANGES PLAYERS
- }
- public boolean checkWin(){
- if(checkRow() || checkCol() || checkDiag()){
- return true;
- }
- return false;
- }
- public boolean checkRow(){
- for(int i = 0; i < 3; i++){
- if(board[i][0] == board[i][1] && board[i][1]== board[i][2]
- && board[i][0] != "-"){
- return true;
- }
- }
- return false;
- }
- public boolean checkCol(){
- for(int i = 0; i < 3; i++){
- if(board[0][i] == board[1][i] && board[1][i]== board[2][i]
- && board[0][i] != "-"){
- return true;
- }
- }
- return false;
- }
- public boolean checkDiag(){
- if(board[1][1] != "-"){
- if(board[0][0] == board[1][1] && board[1][1] == board[2][2]){
- return true;
- }
- if(board[2][0] == board[1][1] && board[1][1] == board[0][2]){
- return true;
- }
- }
- return false;
- }
- public String getPlayer(){
- if(player == "X"){
- player = "O";
- } else {
- player = "X";
- }
- return player;
- }
- }
- import java.util.Scanner;
- public class MyProgram
- {
- public static void main(String[] args)
- {
- TicTacToe thoe = new TicTacToe();
- int x;
- int y;
- Scanner sc = new Scanner(System.in);
- thoe.printBoard();
- while(!thoe.checkWin()){
- System.out.println("Which Row? ");
- x = Integer.valueOf(sc.nextLine());
- System.out.println("Which Column? ");
- y = Integer.valueOf(sc.nextLine());
- if(thoe.isValid(x,y)){
- thoe.placePlayer(x,y);
- } else {
- System.out.println("Invalid choice!");
- }
- thoe.printBoard();
- }
- System.out.println(thoe.getPlayer() + " wins!");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment