Reputation: 49
I need assistance on how to start 'playing' the game like if the user inputs any number from 1-9 that number will be replaced by 'X' or 'O'.
Here is my code so far:
import java.util.Scanner;
public class TicTacToe {
public static char[][] board = new char[3][3];
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
Player player1 = new Player("John");
Player player2 = new Player("Jill");
initBoard();
int turn = 1;
int choice = 0;
while(choice != -1){
printBoard();
Player currentPlayer = player1;
if(turn % 2 == 0){
currentPlayer = player2;
}
System.out.print(currentPlayer + ", pick a box: ");
if(choice == 1){
board[0][0] = 'X';
}
turn++;
choice = kb.nextInt();
}
}
public static void initBoard(){
for(int r = 0; r < board.length; r++){
for(int c = 0; c < board[r].length; c++){
board[r][c] = (char)((r*3)+(c+1)+48);
}
}
}
public static void printBoard(){
for(int r = 0; r < board.length; r++){
for(int c = 0; c < board[r].length; c++){
System.out.print(board[r][c]+" ");
}
System.out.println();
}
}
}
class Player{
String name;
int wins = 0;
int losses = 0;
int draws = 0;
public Player(String s){
name = s;
}
public String toString(){
return name;
}
}
Note: I'm not asking anyone to complete my homework for me, I just need a hint on how to place the 'X's and 'O's and to check to see if one of the boards has already an 'X' or 'O'.
Upvotes: 0
Views: 288
Reputation: 1828
I suppose that you are asking how to convert 1-9 into matrix indices.
In such case, if you the matrix `
`
You could find the pattern that allows you to convert numbers to indicies.
i = (input - 1) / 3;
j = (input - 1) % 3;
Upvotes: 1
Reputation: 440
You are on the right track, you can do something like:
if (board[row][col] != 'X' || board[row][col] != 'O'){ //Position is currently a number since it isn't X or O
// do something here since move is valid
}
You can also also initialize your board to ' '
instead of the actual numbers, then check if the board spot is equal to a space or not.
public static void initBoard(){
for(int r = 0; r < board.length; r++){
for(int c = 0; c < board[r].length; c++){
board[r][c] = ' '; // space here instead of numbers
}
}
}
if (board[row][col] == ' '){ // Board spot is a space so spot has not been played on
// do something here since move is valid
}
Upvotes: 0