I am currently learning java at school and thus far we have oly dealt with the text-based compiler JGrasp; therefore; my attempt to code Tictactoe or "X and O's" game is written as a text based program.
I have made use of a 2 dimensional integer array to represent the 3x3 grid. Each block therefore has a co-ordinate.eg. grid[0][0].Initially all blocks in the grid are equal to zero. The computer uses ones(1) and the player uses twos(2).The user is prompted to enter the row and column number and their choice is entered.
The problemm arises when the computer has to respond by choosig a block to play in. I thought that i could solve this by generating random numbers. The glitch is that when the same set of random co-ordinates is generated it appears as though the computer hasnt played at all. This means that as yet the game is still un-playable.
There are 16 possible outcomes ,all of which are catered for later in the program. I would like some suggestions/help to get the computer to stop picking the same position over and over again, and also to ensure that each block can only be used once.
Thank you.
I have made use of a 2 dimensional integer array to represent the 3x3 grid. Each block therefore has a co-ordinate.eg. grid[0][0].Initially all blocks in the grid are equal to zero. The computer uses ones(1) and the player uses twos(2).The user is prompted to enter the row and column number and their choice is entered.
The problemm arises when the computer has to respond by choosig a block to play in. I thought that i could solve this by generating random numbers. The glitch is that when the same set of random co-ordinates is generated it appears as though the computer hasnt played at all. This means that as yet the game is still un-playable.
Code:
int row3; int col3; int win; public void game() { display_grid(); for(int loop=4;loop>=0&&win!=1;loop--){ System.out.println("Computers turn:"); int row2=(int)(Math.random()*2+0); int col2=(int)(Math.random()*2+0); while(grid[row2][col2]==2||grid[row2][col2]==1){//glitch is somewhere here. row3=row2; col3=col2; } grid[row3][col3]=1; display_grid();
Thank you.
Comment