Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- import java.util.Arrays;
- public class Solution {
- static String[] board=new String[9];
- static String[] defaultBoard=new String[9];
- //Builds board
- static void Board(String[] board)
- {
- System.out.println(board[0]+"|"+board[1]+"|"+board[2]);
- System.out.println("_____");
- System.out.println(board[3]+"|"+board[4]+"|"+board[5]);
- System.out.println("_____");
- System.out.println(board[6]+"|"+board[7]+"|"+board[8]);
- }
- //Scans for number input, returns a new board state
- static String[] turn(Scanner scan,String[] board,String side)
- {
- String next=scan.nextLine();
- if(check(next)!=true)
- {
- System.out.println("You need to print an integer between 1-9.");
- turn(scan,board,side);
- }
- else{
- String hold=next;
- int convert=Integer.parseInt(hold);
- if(board[convert-1]!=" ")
- {
- System.out.println("This space is filled.");
- Board(board);
- turn(scan,board,side);
- }
- else{
- board[convert-1]=side;
- }
- }
- return board;
- }
- //Check if input is number
- static boolean check(String x)
- {
- if(x.matches("[1-9]"))
- {
- return true;
- }
- return false;
- }
- //Check gamestate
- static int gamestate(String[] board)
- {
- String[] check=new String[8];
- boolean available=Arrays.asList(board).contains(" ");
- boolean win=false;
- //Check rows
- for(int i=0;i<3;i++)
- check[i]=board[i*3]+board[i*3+1]+board[i*3+2];
- //Check columns
- for(int i=0;i<3;i++)
- check[3+i]=board[i]+board[i+3]+board[i+6];
- //Check diagonals
- check[6]=board[0]+board[4]+board[8];
- check[7]=board[2]+board[4]+board[6];
- if(Arrays.asList(check).contains("XXX")||Arrays.asList(check).contains("OOO"))
- {
- win=true;
- }
- //Keep playing
- if(available==true&&win==false)
- {
- return 0;
- }
- //Tie
- else if(available==false&&win==false)
- {
- return 1;
- }
- else{
- //Win
- return -1;
- }
- }
- public static void main(String[] args) {
- //Establish board and rules
- Arrays.fill(board," ");
- System.out.println("Instructions:");
- System.out.println("Here is your board.");
- Board(board);
- for(int i=1;i<=9;i++)
- {
- defaultBoard[i-1]=i+"";
- }
- System.out.println("During your turn, just place the number corresponding to the position you want to place your marker.");
- Board(defaultBoard);
- //Start taking inputs
- Scanner scan=new Scanner(System.in);
- //Turns
- int x=1;
- String[] y={"X","O"};
- while(gamestate(board)==0)
- {
- System.out.println("Player "+x+" Turn. Place an "+y[x-1]+".");
- board=turn(scan,board,y[x-1]);
- Board(board);
- if(x==1)
- {
- x=2;
- }
- else
- {
- x=1;
- }
- }
- if(gamestate(board)>0)
- {
- System.out.println("It's a tie.");
- }
- else{
- System.out.println("You win!");
- }
- scan.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement