Alright so I have to make a random tictactoe checker that shows when x wins, when o wins, and when there is a tie. So the issues I'm having is it wont show the ties and it will sometimes say that either x or o won when they didn't. I don't know what to change around in my code because before I did my diagonal check it would print out the ties. Here is the whole code but I'm pretty sure the problem is coming from the checking board part by making xWin and oWin come out true I can't find where its doing that tho.
package test;
import java.util.Scanner;
import java.util.Random;
public class TicTacToe {
public static void main(String[] args) {
System.out.println("Welcome to random Tic Tac Toe Checker. Let's see our randomly generated board.");
int dimension = 3;
char[][] board = new char[dimension][dimension];
Random r = new Random();
for (int i = 0; i < 3; i++) // filling board
{
for (int j = 0; j < 3; j++) {
int choice = r.nextInt(2);
if (choice == 0) {
board[i][j] = 'X';
} else if (choice == 1) {
board[i][j] = 'O';
}
}
}
for (int i = 0; i < 3; i++) // filling board
{
for (int j = 0; j < 3; j++) {
System.out.print(board[i][j]);
}
System.out.println();
}
boolean xWin = false;// checking board, order horizontal,vertical,left
// and right diagonal
boolean oWin = false;
for (int i = 0; i < 3; i++) {
boolean lineWin = true;
for (int j = 0; j < 3; j++) {
if (board[i][j] != board[i][0]) {
lineWin = false;
}
}
if (lineWin == true) {
if (board[i][0] == 'X') {
xWin = false;
}
if (board[i][0] == 'O') {
oWin = false;
}
}
}
for (int j = 0; j < 3; j++) {
boolean lineWin = true;
for (int i = 0; i < 3; i++) {
if (board[i][j] != board[0][j]) {
lineWin = true;
}
}
if (lineWin == true) {
if (board[0][j] == 'X') {
xWin = true;
}
if (board[0][j] == 'O') {
oWin = true;
}
}
}
boolean lineWin = true;
for (int i = 0; i < 3; i++) {
if (board[0][0] != board[i][i]) {
lineWin = false;
}
if (lineWin == true) {
if (board[0][0] == 'X') {
xWin = true;
}
if (board[0][0] == 'O') {
oWin = true;
}
}
}
lineWin = true;
for (int i = 0; i < 3; i++) {
if (board[0][0] != board[i][2 - i]) {
lineWin = false;
}
if (lineWin == true) {
if (board[0][0] == 'X') {
xWin = true;
}
if (board[0][0] == 'O') {
oWin = true;
}
}
}
if (xWin == false && oWin == false)// printing winners
{
System.out.println("CAT!It's a tie no one wins");
}
if (xWin == true) {
System.out.println("X wins!");
}
if (oWin == true) {
System.out.println("O wins!");
}
}
}
I fixed the boolean errors as well as the diagonal logic:
import java.util.Random;
public class TicTacToe {
private static final int DIMENSION = 3;
public static void main(String[] args) {
System.out.println("Welcome to random Tic Tac Toe Checker. Let's see our randomly generated board.");
char[][] board = new char[DIMENSION][DIMENSION];
final Random r = new Random();
for (int i = 0; i < DIMENSION; i++) {
for (int j = 0; j < DIMENSION; j++) {
int choice = r.nextInt(2);
if (choice == 0) {
board[i][j] = 'X';
} else if (choice == 1) {
board[i][j] = 'O';
}
}
}
for (int i = 0; i < DIMENSION; i++) {
for (int j = 0; j < DIMENSION; j++) {
System.out.print(board[i][j]);
}
System.out.println();
}
boolean xWin = false;
boolean oWin = false;
for (int i = 0; i < DIMENSION; i++) {
boolean lineWin = true;
for (int j = 0; j < DIMENSION; j++) {
if (board[i][j] != board[i][0]) {
lineWin = false;
}
}
if (lineWin) {
if (board[i][0] == 'X') {
xWin = true;
}
if (board[i][0] == 'O') {
oWin = true;
}
}
}
for (int j = 0; j < DIMENSION; j++) {
boolean lineWin = true;
for (int i = 0; i < DIMENSION; i++) {
if (board[i][j] != board[0][j]) {
lineWin = false;
}
}
if (lineWin) {
if (board[0][j] == 'X') {
xWin = true;
}
if (board[0][j] == 'O') {
oWin = true;
}
}
}
boolean lineWin = true;
for (int i = 0; i < DIMENSION; i++) {
if (board[0][0] != board[i][i]) {
lineWin = false;
}
}
if (lineWin) {//this check should not be in the loop
if (board[0][0] == 'X') {
xWin = true;
}
if (board[0][0] == 'O') {
oWin = true;
}
}
lineWin = true;
for (int i = 0; i < DIMENSION; i++) {
if (board[DIMENSION - 1][0] != board[i][DIMENSION - 1 - i]) {
lineWin = false;
}
}
if (lineWin) {//this check should not be in the loop
if (board[DIMENSION - 1][0] == 'X') {
xWin = true;
}
if (board[DIMENSION - 1][0] == 'O') {
oWin = true;
}
}
if (xWin == true && oWin == true) {//printing winners
System.out.println("Both players won!");
}
if (xWin == false && oWin == false) {
System.out.println("CAT!It's a tie no one wins");
}
if (xWin == true) {
System.out.println("X wins!");
}
if (oWin == true) {
System.out.println("O wins!");
}
}
}
Note: you can increase DIMENSION for a laugh.
I think the main problem in this file comes around the middle, specifically lines 34 - 66, where you do the initial checks for horizontal and vertical rows of the same character.
for (int i = 0; i < 3; i++) {
boolean lineWin = true;
for (int j = 0; j < 3; j++) {
if (board[i][j] != board[i][0]) {
lineWin = false;
}
}
if (lineWin == true) {
if (board[i][0] == 'X') {
xWin = false; //THESE LINES SHOULD BE CHANGING THE WIN CONDITION TO TRUE
}
if (board[i][0] == 'O') {
oWin = false; //LISTED ABOVE
}
}
}
for (int j = 0; j < 3; j++) {
boolean lineWin = true;
for (int i = 0; i < 3; i++) {
if (board[i][j] != board[0][j]) {
lineWin = true; //THIS LINE SHOULD BE FALSE
}
}
if (lineWin == true) {
if (board[0][j] == 'X') {
xWin = true;
}
if (board[0][j] == 'O') {
oWin = true;
}
}
I listed some changes that will fix the code and make it run the way you want it to. It looks like there were some errors in declaring a boolean to be true or false at the wrong time, so this should be able to fix the problem.
In the first block
if(lineWin == true)
{
if(board[i][0] == 'X')
{
xWin = false;
}
if(board[i][0] == 'O')
{
oWin = false;
}
}
should be changed as follows.
if(lineWin == true)
{
if(board[i][0] == 'X')
{
xWin = true;
}
if(board[i][0] == 'O')
{
oWin = true;
}
}
Furthermore, in the second block, the part
if(board[i][j] != board[0][j])
{
lineWin = true;
}
should be changed as follows.
if(board[i][j] != board[0][j])
{
lineWin = false;
}
Related
I came across a problem. The code is:
Scanner input = new Scanner(System.in);
int time = input.nextInt();
int line = input.nextInt();
input.nextline();
int[][] PrimaryArray = new int[12][11];
int[] Number = new int[12];
boolean[] dualPass = new boolean[12];
for (int i = 0; i < 12; i++) {
dualPass[i] = false;
}
for (int i = 0; i < line; i++) {
int SourceNode = input.nextInt();
int DistNode = input.nextInt();
input.nextLine();
if (SourceNode == 1) {
PrimaryArray[SourceNode][Number[1]] = DistNode;
Number[1]++;
}
if (SourceNode == 2) {
for (int j = 0; j < PrimaryArray[DistNode].length; j++) {
if (PrimaryArray[DistNode][j] == SourceNode)
dualPass[2] = true;
}
if (dualPass[2] != true) {
PrimaryArray[SourceNode][Number[2]] = DistNode;
Number[2]++;
}
dualPass[2] = false;
}
if (SourceNode == 3) {
for (int j = 0; j < PrimaryArray[DistNode].length; j++) {
if (PrimaryArray[DistNode][j] == SourceNode)
dualPass[3] = true;
}
if (dualPass[3] != true) {
PrimaryArray[SourceNode][Number[3]] = DistNode;
Number[3]++;
}
dualPass[3] = false;
}
if (SourceNode == 4) {
for (int j = 0; j < PrimaryArray[DistNode].length; j++) {
if (PrimaryArray[DistNode][j] == SourceNode)
dualPass[4] = true;
}
if (dualPass[4] != true) {
PrimaryArray[SourceNode][Number[4]] = DistNode;
Number[4]++;
}
dualPass[4] = false;
}
if (SourceNode == 5) {
for (int j = 0; j < PrimaryArray[DistNode].length; j++) {
if (PrimaryArray[DistNode][j] == SourceNode)
dualPass[5] = true;
}
if (dualPass[5] != true) {
PrimaryArray[SourceNode][Number[5]] = DistNode;
Number[5]++;
}
dualPass[5] = false;
}
if (SourceNode == 6) {
for (int j = 0; j < PrimaryArray[DistNode].length; j++) {
if (PrimaryArray[DistNode][j] == SourceNode)
dualPass[6] = true;
}
if (dualPass[6] != true) {
PrimaryArray[SourceNode][Number[6]] = DistNode;
Number[6]++;
}
dualPass[6] = false;
}
if (SourceNode == 7) {
for (int j = 0; j < PrimaryArray[DistNode].length; j++) {
if (PrimaryArray[DistNode][j] == SourceNode)
dualPass[7] = true;
}
if (dualPass[7] != true) {
PrimaryArray[SourceNode][Number[7]] = DistNode;
Number[7]++;
}
dualPass[7] = false;
}
if (SourceNode == 8) {
for (int j = 0; j < PrimaryArray[DistNode].length; j++) {
if (PrimaryArray[DistNode][j] == SourceNode)
dualPass[8] = true;
}
if (dualPass[8] != true) {
PrimaryArray[SourceNode][Number[8]] = DistNode;
Number[8]++;
}
dualPass[8] = false;
}
if (SourceNode == 9) {
for (int j = 0; j < PrimaryArray[DistNode].length; j++) {
if (PrimaryArray[DistNode][j] == SourceNode)
dualPass[9] = true;
}
if (dualPass[9] != true) {
PrimaryArray[SourceNode][Number[9]] = DistNode;
Number[9]++;
}
dualPass[9] = false;
}
if (SourceNode == 10) {
for (int j = 0; j < PrimaryArray[DistNode].length; j++) {
if (PrimaryArray[DistNode][j] == SourceNode)
dualPass[10] = true;
}
if (dualPass[10] != true) {
PrimaryArray[SourceNode][Number[10]] = DistNode;
Number[10]++;
}
dualPass[10] = false;
}
}
for (int i = 1; i < 11; i++) {
System.out.println(PrimaryArray[i][1]);
}
I have 2 problems:
about clean code that it is not and very long and has not readability. I want better solution.
about response that is false
for example when the input is :
3 14
1 2
1 5
1 9
1 3
2 8
2 6
5 9
9 4
9 6
3 10
8 11
7 11
10 7
6 7
output must be second member each. I want to say in this code that for example:
when we enter: 1 2
then 2 1
it must ignore 2 1.
output of code is wrong and I don't understand it.
For you first question, even if it's the wrong place there is an answer, just replace your
// ...
for (int i = 0; i < line; i++) {
int sourceNode = input.nextInt();
System.out.println("SourceNode: " + sourceNode);
int distNode = input.nextInt();
System.out.println("DistNode: " + distNode );
input.nextLine();
// you will get same response with following code instead all your if's:
for (int j = 0; j < primaryArray[distNode].length; j++) {
if (primaryArray[distNode][j] == sourceNode)
dualPass[sourceNode] = true;
}
if (dualPass[sourceNode] != true) {
primaryArray[sourceNode][number[sourceNode]] = distNode;
number[sourceNode]++;
}
dualPass[sourceNode] = false;
// end of code change
}
// ...
Your second answer only can be answered if we get more informations, i do not have any Idea what your code should do yet.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have problem with recognizing flushes and straights. I operate in 2D boolean array and it must be a boolean array nothing else. Could somebody help me in writing this method?
I already have logically incorrect methods, but I don't know how to solve it:
public static Boolean isFlush(boolean[][] hand) { // 5 cards same color
boolean found = false;
for (int i = 0; i < 4; i++) {
for(int j = 0; j < 9; j++){
if (hand[i][j] == true && hand[i][j+1] == true && hand[i][j+2] == true && hand[i][j+3] == true && hand[i][j+4] == true) {
found = true;
}
}}
System.out.println("Found from flush: " + found);
return found;
}
public static Boolean isStraight(boolean[][] hand) { // straight patter example 4,5,6,7,8
boolean found = false;
int pom = 0;
for(int i = 0; i<4; i++) {
for (int j = 0; j < 9; j++) {
if (hand[i][j] == true || hand[i][j+1] == true || hand[i][j+2] == true || hand[i][j+3] == true || hand[i][j+4])
pom++;
// System.out.println("straight value: "+i);
}
}
return pom==5;
}
Working Straight method but step by step writed
public static Boolean isStraight(boolean[][] hand) { // straight patter example 4,5,6,7,8
boolean found = false;
for (int j = 0; j < 9; j++) {
if ((hand[0][j] == true || hand[1][j] == true || hand[2][j] == true || hand[3][j] == true)
&& (hand[0][j+1] == true || hand[1][j+1] == true || hand[2][j+1] == true || hand[3][j+1] == true)
&& (hand[0][j+2] == true || hand[1][j+2] == true || hand[2][j+2] == true || hand[3][j+2] == true)
&& (hand[0][j+3] == true || hand[1][j+3] == true || hand[2][j+3] == true || hand[3][j+3] == true)
&& (hand[0][j+4] == true || hand[1][j+4] == true || hand[2][j+4] == true || hand[3][j+4] == true ))
found = true;
}
return found;
}
For what it is worth, here is the most efficient way to solve a straight, using DP
public static boolean isStraight(boolean[][] hand) {
int[] straightCounter = new int[13];
for (int j=0; j<13; j++) {
boolean isCard = hand[0][j] || hand[1][j] || hand[2][j] || hand[3][j];
if (isCard) {
if (j==0)
straightCounter[j]=1;
else
straightCounter[j]=straightCounter[j-1]+1;
if (straightCounter[j] == 5)
return true;
if (j==12 && straightCounter[j] == 4 && straightCounter[0] == 1)
return true; // the 10/J/Q/K/A scenario
}
}
return false;
}
something like the following
public static Boolean isFlush(boolean[][] hand) { // 5 cards same color
for (int i = 0; i < 4; i++) {
int count = 0;
for(int j = 0; j < 13; j++) {
if(hand[i][j]) {
count++;
}
}
if(count == 5) {
return true;
}
}
return false;
}
public static Boolean isStraight(boolean[][] hand) { // straight patter
for (int i = 0; i < 9; i++) {
int count = 0;
for(int j = 0; j < 5; j++) {
for(int k = 0; k < 4; k++) {
if (hand[k][i + j]) {
count++;
break;
}
}
}
if(count == 5) {
return true;
}
}
return false;
}
I have this class called deepToe_2. Whenever I click on the shortcut key for run, eclipse runs another class called TicTacToe which I had previously ran.
I have tried making changes to run cofig but it still does not seem to work.
Here is my code :
package deepToe;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
import deepToe.deepToe_2.buttonListener;
public class deepToe_2 extends JPanel {
JButton buttons[] = new JButton[9];
int alternate = 0;
String MotherBoard[] = {"","","","","","","","",""};
String board[];
public static void main(String[] args) {
JFrame window = new JFrame("Tic Tac Toe");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(new TicTacToe());
window.setBounds(300,200,300,300);
window.setVisible(true);
}
public deepToe_2()
{
setLayout(new GridLayout(3,3));
initializebuttons();
toss();
}
public void toss(){
Random ran = new Random();
int r = ran.nextInt(2);
if(r == 1){
JOptionPane.showMessageDialog(null, "deepToe goes First.");
alternate++;
deepToe();
}
else {
JOptionPane.showMessageDialog(null, "deepToe goes First.");
alternate++;
deepToe();
}
}
public void deepToe() {
if(alternate == 1) {
buttons[4].setText("O");
}else {
int moves[] = {-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000,-1000};
for(int i = 0; i < 9; i++) {
board = MotherBoard;
if(board[i] == "") {
board[i] = "O";
moves[i] = evaluateBoard();
}
}
int high = -999, final_move = -1;
for(int j = 0; j < 9; j++) {
if(moves[j] > high){
high = moves[j];
final_move = j;
}
}
buttons[final_move].setText("O");
}
updateMotherBoard();
if(!(checkResults())) alternate++;
}
public int evaluateBoard() {
int x = 0;
if(canSomeoneWin("O") != -1) x += 2;
if(canSomeoneWin("X") != -1) x -= 2;
return x;
}
public void updateMotherBoard() {
for(int i = 0; i < 9; i++) {
MotherBoard[i] = buttons[i].getText();
}
}
public int canSomeoneWin(String c) {
int x = 0, y = 1, z = 2;
for(int j = 0; j < 3; j++){
if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
x += 3;
y += 3;
z += 3;
}
x = 0; y = 3; z = 6;
for(int j = 0; j < 3; j++){
if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
x++;
y++;
z++;
}
x = 0; y = 4; z = 8;
for(int j = 0; j < 2; j++){
if((board[y] == board[z])&&(board[y] == c)&&(board[x] == "")) return x;
if((board[x] == board[z])&&(board[x] == c)&&(board[y] == "")) return y;
if((board[x] == board[y])&&(board[x] == c)&&(board[z] == "")) return z;
x = 2; z = 6;
}
return -1;
}
public void initializebuttons()
{
for(int i = 0; i <= 8; i++)
{
buttons[i] = new JButton();
buttons[i].setText("");
buttons[i].addActionListener(new buttonListener());
add(buttons[i]);
}
buttons[5].setText("X");
}
public class buttonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JButton buttonClicked = (JButton)e.getSource();
if((alternate%2 == 0)&&(buttonClicked.getText().equals(""))){
buttonClicked.setText("X");
updateMotherBoard();
if(!(checkResults())) {
alternate++;
deepToe();
}
}
}
}
public boolean checkResults(){
if(checkForWin())
{
if(alternate%2 == 0)
JOptionPane.showConfirmDialog(null, "Human wins. Great Job!!!");
else
JOptionPane.showConfirmDialog(null, "deepToe wins.");
return true;
}else{
if(checkForDraw()){
JOptionPane.showConfirmDialog(null, "Draw. Good game.");
return true;
}
}
return false;
}
public boolean checkForDraw() {
boolean yes = true;
for(int j = 0; j < 9; j++){
if(buttons[j].getText().equals("")) yes = false;
}
return yes;
}
public boolean checkForWin()
{
if( checkAdjacent(0,1) && checkAdjacent(1,2) ) //no need to put " == true" because the default check is for true
return true;
else if( checkAdjacent(3,4) && checkAdjacent(4,5) )
return true;
else if ( checkAdjacent(6,7) && checkAdjacent(7,8))
return true;
else if ( checkAdjacent(0,3) && checkAdjacent(3,6))
return true;
else if ( checkAdjacent(1,4) && checkAdjacent(4,7))
return true;
else if ( checkAdjacent(2,5) && checkAdjacent(5,8))
return true;
else if ( checkAdjacent(0,4) && checkAdjacent(4,8))
return true;
else if ( checkAdjacent(2,4) && checkAdjacent(4,6))
return true;
else
return false;
}
public boolean checkAdjacent(int a, int b)
{
if ( buttons[a].getText().equals(buttons[b].getText()) && !buttons[a].getText().equals("") )
return true;
else
return false;
}
}
It probably IS running this class, but you are inserting the wrong panel in your frame:
window.getContentPane().add(new TicTacToe());
it should be deepToe_2 like in
window.getContentPane().add(new deepToe_2());
since there is no other reference to that class in the poseted code.
Just to be sure change the frame's title:
JFrame window = new JFrame("Deep Toe 2"); // or so
I also would encourage you to (learn to) use the debugger, would b helpful to identify such problems...
Right click either in your class file or the class itself and click Run As -> Java Application
you need just to double click your class and then run the program from where ever you want. you can right click as suggested by kkflf or run it from shortcut key as you used to do.
Hope this will help.
My check vertical win and check horizontal win work perfectly fine, however i dont know what to do with my check diagonal code to make it actually check diagonal. Some guidance would be much appreciated and this is in java. Thank you.
private boolean checkVerticalWin()
{
PieceType type = myBoard[myLastPoint.x][myLastPoint.y];
System.out.println("check vert");
for(int j = 0; j < myNumColumns; j++)
{
for(int i = 0; i < myNumRows; i++)
{
if(myBoard[i][j] == type && myBoard[i][j] != null )
{
count++;
if(count == 1)
{
myWinBegin = new Point(i,j);
}
}
else
{
myWinBegin = null;
count = 0;
}
System.out.println(count);
if(count == myWinLength)
{
myWinEnd = new Point(i,j);
return true;
}
}
}
myWinBegin = null;
return false;
}
private boolean checkHorizontalWin()
{
System.out.println("test");
PieceType type = myBoard[myLastPoint.x][myLastPoint.y];
for(int i = 0; i < myNumRows; i++)
{
for(int j = 0; j < myNumColumns; j++)
{
if(myBoard[i][j] == type && myBoard[i][j] != null)
{
count++;
if (count == 1)
{
myWinBegin = new Point(i,j);
}
}
else
{
myWinBegin = null;
count = 0;
}
if(count == myWinLength)
{
myWinEnd = new Point(i,j);
return true;
}
}
}
myWinBegin = null;
return false;
}
private boolean checkDiagonalWin()
{
PieceType type = myBoard[myLastPoint.x][myLastPoint.y];
for(int i = 0; i < myNumRows; i++)
{
for (int j = 0; j < myNumColumns; j++)
{
if(myBoard[i][j] == type && myBoard[i][j] != null )
{
count++;
myWinBegin = new Point(i,j);
}
else
{
count = 0;
myWinEnd = new Point(i,j);
}
if(count == myWinLength)
{
return true;
}
}
}
for(int j = 0; j < myNumColumns; j--)
{
for (int i = 0; i < myNumRows; i--)
{
if(myBoard[i][j] == type && myBoard[i][j] != null )
{
count++;
myWinBegin = new Point(i,j);
}
else
{
count = 0;
}
if(count == myWinLength)
{
myWinEnd = new Point(i,j);
return true;
}
}
}
for(int j = 0; j < myNumColumns; j++)
{
for (int i = 0; i < myNumRows; i--)
{
if(myBoard[i][j] == type && myBoard[i][j] != null )
{
count++;
}
else
{
myWinBegin = new Point(i,j);
count = 0;
}
if(count == myWinLength)
{
myWinEnd = new Point(i,j);
return true;
}
}
}
for(int j = 0; j < myNumColumns; j--)
{
for (int i = 0; i < myNumRows; i++)
{
if(myBoard[i][j] == type && myBoard[i][j] != null )
{
count++;
myWinBegin = new Point(i,j);
}
else
{
count = 0;
}
if(count == myWinLength)
{
myWinEnd = new Point(i,j);
return true;
}
}
}
return false;
}
So basically, you need a start point, you then need to determine in which direction to move
With that idea in hand, you could use something like...
boolean win = true;
for (int count = 0; count < 4; count++) {
if (row < myNumRows && row >= 0 && col < myNumColumns && col >= 0) {
int test = myBoard[row][col];
if (test != check) {
win = false;
break;
}
} else {
break;
}
row += rowDelta;
col += colDelta;
}
As the basic algorithm. All this does is checks each cell from a start point, to a total of 4 cells, the algorithm moves by the specified delta/direction and keeps checking while each cell matches the check value.
Now, I'd wrap this in a simple method
public boolean didWin(int[][] grid, int check, int row, int col, int rowDelta, int colDelta) {
boolean win = true;
for (int count = 0; count < 4; count++) {
if (row < ROWS && row >= 0 && col < COLUMNS && col >= 0) {
int test = grid[row][col];
if (test != check) {
win = false;
break;
} else {
break;
}
}
row += rowDelta;
col += colDelta;
}
return win;
}
which makes it simpler to call, know given any point, you can do something like...
int startRow = ...;
int startCol = ...;
int player = ...;
if (didWin(myBoard, player, startRow, startCol, 1, 0) || // Vertical, down
didWin(myBoard, 1, startRow, startCol, 0, 1) || // Right
didWin(myBoard, 1, startRow, startCol, 0, -1) || // Left
didWin(myBoard, 1, startRow, startCol, 1, 1) || // Right/down
didWin(myBoard, 1, startRow, startCol, -1, -1) || // Left/Up
didWin(myBoard, 1, startRow, startCol, 1, -1) || // Down/Left
didWin(myBoard, 1, startRow, startCol, -1, 1) // Up/Right
) {
// You be the winner
}
nb: I've left out check a vertical up direction, because it's unlikely that you could actually win this way
ps: I'd be even more lazy and would just have a didWin method, which did the above checks and returned true or false, but I'm lazy
So, the startRow and startCol would represent the anchor point around which you want to check and would, in this example, represent the last drop.
This example uses a int to represent the player/token, but you could use anything, all this does is compares the token you supply with the values in the array
I've tried to create a Tic Tac Toe game class with the play and hasWon methods.
public class TicTacToe {
private enum State{Blank, X, O}
private int grid;
private State[][] board = new State[grid][grid];
private int moves;
//Default Constructor
public TicTacToe(int grid){
board = new State[grid][grid];
moves = 0;
}
public void play(State s, int m, int n){
if (board[m][n] == State.Blank){
board[m][n] = s;
}
moves++;
}
public boolean hasWon(State[][] board){
//check winner in rows
boolean state = false;
int j = 0;
int i = 0;
while(j <= grid) {
for (i = 0; i <= grid; i++) {
if (board[j][i] == board[j][i + 1])
state = true;
else state = false;
break;
}
if(state == false)
j++;
else return true;
}
//check winner in columns
while(j <= grid) {
for (i = 0; i < grid; i++) {
if (board[i][j] == board[i + 1][j])
state = true;
else state = false;
break;
}
if (state == true)
j++;
else return true;
}
//check winner in top diagonal
while(j <= grid && i <= grid){
if (board[i][j] == board[i+1][j+1])
state = true;
else state = false;
break;
i++;
j++;
return true;
}
//check winner in bottom diagonal
int k = grid;
int l = grid;
while(k >= 0 && l >= 0){
if (board[k][l] == board[k-1][l-1])
state = true;
else state = false;
break;
k--;
l--;
return true;
}
return false;
}
}
However when called in the Main class the program behaves erratically. Is there a logical problem in the code.
When checking your rows with
for (i = 0; i < n; i++) {
if (board[j][i] == board[j][i + 1])
state = true;
}
this code always sets the state to true if the last two chars in the row are the same, independently of the chars previous in that row.
The same thing for columns and the diagonal (of which you are checking only as Todd said).
You want to stop comparing values for that row if you find some values that are not equal:
for (i = 0; i < n; i++) {
if (board[j][i] == board[j][i + 1]) {
state = true;
} else {
state = false;
break;
}
}
Same for rows and diagonal(s).
Edit:
Furthermore: You are not setting your field grid in the constructor, so it always is 0 and you are not checking your complete rows, columns, diagonals
Missing:
this.grid = grid;