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.
Related
This is my board class
public class Board {
char[][] grid;
int width;
int height;
int count;
char player;
public Board(int height, int width){
count = 0;
grid = new char[height][width];
this.width = width;
this.height = height;
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++){
if(i == 0 && j == 0){
grid[i][j] = '┌';
}
else if(j % 2 == 1) {
grid[i][j] = '─';
}
else if (i == 0 && j == width - 1){
grid[i][j] = '┐';
}
else if (i == height-1 && j == 0){
grid[i][j] = '└';
}
else if (i == height - 1 && j == width - 1){
grid[i][j] = '┘';
}
else if (i == 0){
grid[i][j] = '┬';
}
else if (j == 0){
grid[i][j] = '├';
}
else if (i == height - 1){
grid[i][j] = '┴';
}
else if (j == width - 1){
grid[i][j] = '┤';
}
else
grid[i][j] = '┼';
}
}
}
public void print(){
for(int i=0; i<height; i++){
for(int j=0; j<width; j++)
System.out.print(grid[i][j]);
System.out.println();
}
}
Below is the put function of the board class. The problem is the put function. You must enter a line from the selectline function and have the player appear on the desired line.
However, no matter how hard I modify the conditional statement, it only appears in the first line.
How do I modify the conditional statement of the put function?
public void put(SelectLine setLine) {
int y=setLine.getY();
int x = grid.length-1;
if(count%2 == 0) {
player = '●';
}
else {
player = '○';
}
for(int i = grid.length-1; i >=0; i--) {
if(grid[i][(y-1)*2] != player) {
grid[i][(y-1)*2] = player;
count++;
break;
}
}
System.out.println("────────" + player + "'s Turn ────────");
this.print();
}
}
public class SelectLine {
int line;
public void input(){
System.out.print("Select Line : ");
Scanner sc = new Scanner(System.in);
line = sc.nextInt();
}
public int getY(){
return line;
}
}
The goal is to keep stacking up like the picture below.
enter image description here
Modify your SelectLine class as follows:
class SelectLine {
int line;
public int input(){
System.out.print("Select Line : ");
Scanner sc = new Scanner(System.in);
line = sc.nextInt();
return line;
}
public int getY(){
return input();
}
Working code:
https://onlinegdb.com/ryhum-Eu_
You need to take into account that a user may input negative values or such exceeding grid size, though.
Regards.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Board b = new Board(10, 10);
b.print();
b.put(new SelectLine());
System.out.println("Hello World");
}
}
class Board {
char[][] grid;
int width;
int height;
int count;
char player;
public Board(int height, int width){
count = 0;
grid = new char[height][width];
this.width = width;
this.height = height;
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++){
if(i == 0 && j == 0){
grid[i][j] = '┌';
}
else if(j % 2 == 1) {
grid[i][j] = '─';
}
else if (i == 0 && j == width - 1){
grid[i][j] = '┐';
}
else if (i == height-1 && j == 0){
grid[i][j] = '└';
}
else if (i == height - 1 && j == width - 1){
grid[i][j] = '┘';
}
else if (i == 0){
grid[i][j] = '┬';
}
else if (j == 0){
grid[i][j] = '├';
}
else if (i == height - 1){
grid[i][j] = '┴';
}
else if (j == width - 1){
grid[i][j] = '┤';
}
else
grid[i][j] = '┼';
}
}
}
public void print(){
for(int i=0; i<height; i++){
for(int j=0; j<width; j++)
System.out.print(grid[i][j]);
System.out.println();
}
}
public void put(SelectLine setLine) {
int y=setLine.getY();
int x = grid.length-1;
if(count%2 == 0) {
player = '●';
}
else {
player = '○';
}
for(int i = grid.length-1; i >=0; i--) {
if(grid[i][(y-1)*2] != player) {
grid[i][(y-1)*2] = player;
count++;
break;
}
}
System.out.println("────────" + player + "'s Turn ────────");
this.print();
}
}
class SelectLine {
int line;
public int input(){
System.out.print("Select Line : ");
Scanner sc = new Scanner(System.in);
line = sc.nextInt();
return line;
}
public int getY(){
return input();
}
}
I am a new to java programming and I am developing a simple a one player TICTACTOE game using swing. Thee are two classes. One main TICTACTOE class which uses an XOButtton class to set up buttons which can listen to click events. I begin by creating an object of this tictactoe class then use this object to call a method called initialCheckButton to find out if the buttons have been clicked 3 timess. If yes it calls another method to find out if the Xs or Os are consecutively displayed.If yes you win. I plan to develop this further but this is just a template. When the GUI dsiplays,clicking on buttons and display of successive Xs or Os does not display the message of the JoptionPane. Any help?
public class TicTacToe extends JFrame {
JPanel p = new JPanel();
boolean done = false;
XOButton buttons[] = new XOButton[9];
public static void main(String args[]) {
TicTacToe t = new TicTacToe();
t.initialCheckButton();
}
public TicTacToe() {
super("TicTacToe");
setSize(400, 400);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
p.setLayout(new GridLayout(3, 3));
for (int i = 0; i < 9; i++) {
buttons[i] = new XOButton();
p.add(buttons[i]);
}
add(p);
setVisible(true);
}
public void initialCheckButton() {
int sum = 0;
while (sum <= 3) {
for (int i = 0; i < 9; i++) {
if (buttons[i].checkButtonO() == 1) {
sum++;
}
if (buttons[i].checkButtonX() == 1) {
sum++;
}
}
}
checkButtonFinal();
}
public void checkButtonFinal() {
for (int i = 0; i < 9; i++)
for (int j = i + 3; j < 9; j++) {
for (int k = j + 3; k < 9; k++) {
if (buttons[i].checkButtonO() == buttons[j].checkButtonO() && buttons[k].checkButtonO() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
if (buttons[i].checkButtonX() == buttons[j].checkButtonX() && buttons[k].checkButtonX() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
}
}
for (int i = 0; i < 9; i += 3) {
if (buttons[i].checkButtonO() == buttons[i + 1].checkButtonO() && buttons[i + 2].checkButtonO() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
if (buttons[i].checkButtonX() == buttons[i + 1].checkButtonX() && buttons[i + 2].checkButtonX() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
}
for (int i = 0; i < 9; i += 2) {
for (int j = i + 2; j < 9; j += 2)
for (int k = j + 2; k < 9; k += 2) {
if (buttons[i].checkButtonO() == buttons[j].checkButtonO() && buttons[k].checkButtonO() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
if (buttons[i].checkButtonX() == buttons[j].checkButtonX() && buttons[k].checkButtonX() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
}
}
for (int i = 0; i < 9; i += 4) {
for (int j = i + 4; j < 9; j += 4)
for (int k = j + 4; k < 9; k += 4) {
if (buttons[i].checkButtonO() == buttons[j].checkButtonO() && buttons[k].checkButtonO() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
if (buttons[i].checkButtonX() == buttons[j].checkButtonX() && buttons[k].checkButtonX() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
}
}
}
public static class XOButton extends JButton implements ActionListener {
public int buttonClicked = 0;
public int buttonClickedX = 0;
public int buttonClickedO = 0;
ImageIcon X, O;
byte value = 0;
/*
* 0:nothing 1:X 2:O
*/
public XOButton() {
X = new ImageIcon(this.getClass().getResource("X.png"));
O = new ImageIcon(this.getClass().getResource("O.png"));
this.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
value++;
value %= 3;
switch (value) {
case 0:
setIcon(null);
buttonClicked = 0;
break;
case 1:
setIcon(X);
buttonClickedX = 1;
break;
case 2:
setIcon(O);
buttonClickedO = 1;
break;
}
}
public int checkButtonO() {
return buttonClickedO;
}
public int checkButtonX() {
return buttonClickedX;
}
}
}
The following is a refactored version of your code that includes some documented changes :
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class TicTacToe extends JFrame {
private static int ROW = 3, COLS = 3;
private final JPanel p;
private final XOButton buttons[];
//static counter, so it has the same value for all button instances
//used as a toggle between X and O
private static int counter = 0;
public static void main(String args[]) {
new TicTacToe();
}
public TicTacToe() {
super("TicTacToe");
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
buttons = new XOButton[ROW*COLS];
p = new JPanel();
p.setLayout(new GridLayout(3, 3));
initialize();
add(p);
pack();
setVisible(true);
}
private void initialize(){
for (int i = 0; i < 9; i++) {
buttons[i] = new XOButton();
p.add(buttons[i]);
}
}
//restart game
private void restart(){
p.removeAll();
initialize();
revalidate();
}
private void checkButtons() {
//many similar for loops are not easy to follow
//refactor into methods
XOButton[] winningButtons = checkRows();
if( winningButtons != null) {
won(winningButtons);
}
winningButtons = checkCols();
if( winningButtons != null) {
won(winningButtons);
}
winningButtons = checkDIagonals();
if( winningButtons != null) {
won(winningButtons);
}
}
//returns winning buttons, or null
private XOButton[] checkRows() {
for(int row = 0; row < buttons.length ; row +=3 ){
int totalX = buttons[row].buttonClickedX + buttons[row+1].buttonClickedX+ buttons[row+2].buttonClickedX ;
int totalO = buttons[row].buttonClickedO + buttons[row+1].buttonClickedO+ buttons[row+2].buttonClickedO ;
if(totalX >=3 || totalO >=3) return new XOButton[]{buttons[row], buttons[row+1], buttons[row+2]};
}
return null;
}
//returns winning buttons, or null
private XOButton[] checkCols() {
for(int col = 0; col < COLS ; col++ ){
System.out.println(col+"-"+(col+3)+"-"+(col+6));
int totalX = buttons[col].buttonClickedX + buttons[col+3].buttonClickedX+ buttons[col+6].buttonClickedX ;
int totalO = buttons[col].buttonClickedO + buttons[col+3].buttonClickedO+ buttons[col+6].buttonClickedO ;
if(totalX >=3 || totalO >=3) return new XOButton[]{buttons[col], buttons[col+3], buttons[col+6]};
}
return null;
}
//returns winning buttons, or null
private XOButton[] checkDIagonals() {
int totalX = buttons[0].buttonClickedX + buttons[4].buttonClickedX+ buttons[8].buttonClickedX ;
int totalO = buttons[0].buttonClickedO + buttons[4].buttonClickedO+ buttons[8].buttonClickedO ;
if(totalX >=3 || totalO >=3) return new XOButton[]{buttons[0], buttons[4], buttons[8]};
totalX = buttons[2].buttonClickedX + buttons[4].buttonClickedX+ buttons[6].buttonClickedX ;
totalO = buttons[2].buttonClickedO + buttons[4].buttonClickedO+ buttons[6].buttonClickedO ;
if(totalX >=3 || totalO >=3) return new XOButton[]{buttons[2], buttons[4], buttons[6]};
return null;
}
//invoked when there is a winner
private void won(XOButton[] winningButtons) {
for(XOButton button : winningButtons){
button.setBackground(Color.PINK);
}
JOptionPane.showMessageDialog(null, "Great, you won");
restart(); //start new game
}
class XOButton extends JButton implements ActionListener {
private int buttonClicked = 0, buttonClickedX = 0, buttonClickedO = 0;
String X, O; //avoid using unavailable images when posting
public XOButton() {
X = "X";
O = "O";
this.addActionListener(this);
setPreferredSize(new Dimension(40,40));
}
#Override
public void actionPerformed(ActionEvent e) {
if(buttonClicked > 0 ) return; //invoke only on first click
buttonClicked ++;
counter = (counter+1)%2; //changes from 1 to 0 and back to 1
switch (counter) {
case 0:
setText(X);
buttonClickedX = 1;
break;
case 1:
setText(O);
buttonClickedO = 1;
break;
}
checkButtons();//check buttons after every click
}
public int checkButtonO() {
return buttonClickedO;
}
public int checkButtonX() {
return buttonClickedX;
}
}
}
This is a class that creates the game connect four in console and drawing panel, and I am having trouble in the connectedFour method where it determines if someone has gotten 4 discs in a row. The problem is, is that I am not sure how to set up my for loops to check through the array for four discs in a row
Here is my code:
import java.util.*;
import java.awt.*;
public class ConnectFour{
public static void main(String[] args){
//board
DrawingPanel panel = new DrawingPanel(550,550);
int rowAvailable;
Graphics g = panel.getGraphics();
g.drawLine(0,0,0,500);
g.drawLine(0,0,500,0);
g.drawLine(500,0,500,427);
g.drawLine(0,427,500,427);
for(int i = 0; i< 6; i++){
for(int j= 0; j<= 6; j++){
g.setColor(Color.YELLOW);
g.fillRect(j*71,i*71,71,71);
g.setColor(Color.WHITE);
g.fillOval(j*71,i*71,71,71);
}
}
//setBlankArray
Scanner console = new Scanner(System.in);
char[][] board = new char[6][7];
for(int j = 0;j <= 6; j++){
for(int i= 0; i < 6; i++){
board[i][j] = ' ';
}
}
boolean isBlack = true;
boolean isRed = false;
int column = 0;
boolean playersTurn = true;
boolean rightNum = false;
//oneTurn
while(getWinner(board, playersTurn)){
//while(playersTurn == true){
rightNum = false;
if(isBlack == true){
// displayCurrentPlayer
System.out.println("Black's Turn");
g.setColor(Color.WHITE);
g.drawString("Red Disc's Turn",200, 450);
g.setColor(Color.BLACK);
g.drawString("Black Disc's Turn",200, 450);
}
else{
// displayCurrentPlayer
System.out.println("Red's Turn");
g.setColor(Color.WHITE);
g.drawString("Black Disc's Turn",200, 450);
g.setColor(Color.RED);
g.drawString("Red Disc's Turn",200, 450);
}
System.out.print("Choose a column to place your disk (1-7): ");
while(rightNum == false){
column = (console.nextInt()) -1;
if(column >= 0 && column < 7 && board[0][column] == ' '){
rightNum = true;
}
else{
System.out.print("Try again: ");
}
}
drawBoard(column, board, isBlack, isRed, board, g);
isBlack = !isBlack;
}
if(isBlack == false){System.out.println("Congratulations Black Player");}
else{System.out.println("Congratulations Red Player");}
// use the while loop to say try again if the column is filled.
}
public static void drawBoard(int column, char[][] board, boolean isBlack, boolean isRed, char[][] availability,Graphics g){
char player = ' ';
if(isBlack == true){
g.setColor(Color.BLACK);
player = 'b';
}
else{
g.setColor(Color.RED);
player = 'r';
}
int x = 0;
int row = 5;
while(board[row-x][column] != ' '){
x++;
}
row = row-x;
g.fillOval((column * 71),(row * 71), 71,71);
board[row][column] = player;
}
public static boolean getWinner(char[][] board, boolean playersTurn){
int verticalCount = 0;
boolean isVertical = false;
for(int i = 6; i >= 0; i--){
verticalCount = 0;
for(int j = 5; j > 0; j--){
if(board[j][i] == board[j-1][i] && board[j][i] != ' '){
verticalCount++;
}
if(verticalCount == 4){
isVertical = true;
}
}
}
int horizontalCount = 0;
boolean isHorizontal = false;
for(int i =1; i <= 5; i++){
for(int j =1; j<6; j++){
if(board[j][i] == board[j][i+1] && board[j][i] != ' '){
horizontalCount++;
}
if(horizontalCount == 3){
isHorizontal = true;
}
}
}
int diagonalCount = 0;
boolean isDiagonal = false;
// for(int i = 0; i<=6; i++){
// for(int j =0; j<6; j++){
// if(board[i][j-1] == board[i][j]){
// diagonalCount++;
// }
// }
// }
if(isVertical || isHorizontal || isDiagonal){
playersTurn = false;
}
else{
playersTurn = true;}
return playersTurn;
}
}
I would implement this by checking if the game-winning condition is met after a disc has been placed. This way you aren't iterating over the entire board after each move.
Regardless, try this:
replace
while (gameWon == false ){
with
while (!connectedFour(board, playersTurn)) {
I don't think this will completely fix your problems as it looks like there are a handful of other things wrong with the code you've posted.
OK so I have programmed a Sudoku solver.. And when I run the debug to check if its going through everything.. it is.. But it does not seem to work. It will print it out, and it will change the "." to 0's. But thats as far as it goes. It will not change the 0's, to the numbers when it loops over it.
public class SudokuSolver {
int[][] sudoku;
String data;
public SudokuSolver()
{
getPuzzle();
solvePuzzle(0,0);
}
private void getPuzzle()
{
try
{
Scanner in = new Scanner(new File("C:/Users/Ben/workspace/Sudoku Solver/src/puzzle1.txt"));
sudoku = new int[9][9];
for(int y = 0; y<9;y++)
{
for(int x = 0; x<9; x++)
{
data = in.next();
if(data.equals("."))
sudoku[x][y]=0;
else
sudoku[x][y] = Integer.parseInt(data);
}
}
in.close();
}
catch(Exception e)
{
}
for(int y = 0; y<9; y++)
{
for(int x = 0; x<9; x++)
{
System.out.print(sudoku[x][y]);
if(x ==2 || x ==5)
System.out.print(" ");
if(x==8)
{
System.out.print("\n");
}
}
if(y == 2|| y == 5)
{
System.out.println(" ");
}
}
}
private boolean isValid(int x, int y, int num)
{
int xSection = x/3;
int ySection = y/3;
for ( int row = 0; row < sudoku.length; row++ )
{
if(sudoku[row][y] == num)
{
return false;
}
}
for( int col = 0; col < sudoku.length; col++)
{
if(sudoku[x][col] == num)
{
return false;
}
}
for(int box = 3*xSection; box < 3*xSection + 3; box++)
{
for(int boxY = 3*ySection; boxY < 3*ySection + 3; boxY++)
{
if(sudoku[box][boxY] == num)
{
return false;
}
}
}
return true;
}
private int xPosition(int x, int y)
{
if(x<8)
{
return x+1;
}
else
{
return 0;
}
}
private int yPosition(int x, int y)
{
if(x<8)
{
return y;
}
else
{
return y+1;
}
}
private boolean solvePuzzle(int x, int y)
{
if( x >= 9 || y >= 9)
{
return true;
}
else
{
for(int num = 1; num < 10; num++)
{
if(isValid(x,y,num))
{
sudoku[x][y] = num;
if( solvePuzzle(xPosition(x,y), yPosition(x,y)) )
{
return true;
}
else
{
sudoku[x][y] = 0;
}
}
}
return false;
}
}
public static void main(String args[])
{
SudokuSolver solver = new SudokuSolver();
}
}
You're printing the puzzle inside the getPuzzle-method, which is before solvePuzzle has been called. You need to print the puzzle after it has been solved.
So I have been working on my final term project which is a Connect Four game. I ran into this issue where i believe my CheckWin logic should work, put is providing me with no output when i run the program. I have my CheckWin() being called in my actionPerformed and I am stuck as to what to do here. As a side note, is there any way to easily increase the size of text inside of a JButton? I would like to increase the size of the "X's" and "O's". I am relatively new at programming so sorry if these are simple fixes. My code is below:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Connect implements ActionListener {
private JFrame window = new JFrame();
private JPanel myPanel = new JPanel();
private JPanel myPanelB = new JPanel();
private JButton[][] myButtons = new JButton[6][7];
private JButton[] buttons = new JButton[7];
private boolean win = false;
private int count = 5;
private int count2 = 5;
private int count3 = 5;
private int count4 = 5;
private int count5 = 5;
private int count6 = 5;
private int count7 = 5;
private int countA = 0;
private String letter = "";
public boolean checkHorizontalWin(String letter) {
for (int y = 0; y < myButtons.length; y++) {
// going to length-3 to avoid IndexOutOfBounds exception
for (int x = 0; x < myButtons[y].length - 3; x++) {
if (myButtons[y][x].getText().equals(letter)
&& myButtons[y][x + 1].getText().equals(letter)
&& myButtons[y][x + 2].getText().equals(letter)
&& myButtons[y][x + 3].getText().equals(letter)
) {
return true;
}
}
}
return false;
}
public boolean checkVerticalWin(String letter) {
for (int y = 0; y < myButtons.length - 3; y++) {
for (int x = 0; x < myButtons[y].length; x++) {
if (myButtons[y][x].getText().equals(letter)
&& myButtons[y + 1][x].getText().equals(letter)
&& myButtons[y + 2][x].getText().equals(letter)
&& myButtons[y + 3][x].getText().equals(letter)
) {
return true;
}
}
}
return false;
}
public boolean checkDiagonalToTheLeftWin(String letter) {
for (int y = 0; y < myButtons.length - 3; y++) {
for (int x = 0; x < myButtons[y].length - 3; x++) {
if (myButtons[y][x].getText().equals(letter)
&& myButtons[y + 1][x + 1].getText().equals(letter)
&& myButtons[y + 2][x + 2].getText().equals(letter)
&& myButtons[y + 3][x + 3].getText().equals(letter)
) {
return true;
}
}
}
return false;
}
public boolean checkDiagonalToTheRightWin(String letter) {
for (int y = 0; y < myButtons.length - 3; y++) {
for (int x = 3; x < myButtons[y].length; x++) {
if (myButtons[y][x].getText().equals(letter)
&& myButtons[y + 1][x - 1].getText().equals(letter)
&& myButtons[y + 2][x - 2].getText().equals(letter)
&& myButtons[y + 3][x - 3].getText().equals(letter)
) {
return true;
}
}
}
return false;
}
public Connect(){
window.setSize(800,700);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myPanel.setLayout(new GridLayout(1,7));
myPanelB.setLayout(new GridLayout(6,7));
for (int i = 0; i < buttons.length; i ++){
buttons[i] = new JButton();
myPanel.add(buttons[i]);
buttons[i].addActionListener(this);
}
for (int i = 0; i < 6; i ++){
for (int j = 0; j < 7; j ++){
myButtons[i][j] = new JButton();
myPanelB.add(myButtons[i][j]);
}
}
window.add(myPanel, BorderLayout.NORTH);
window.add(myPanelB, BorderLayout.CENTER);
window.setVisible(true);
}
public void actionPerformed(ActionEvent e){
countA++;
if (countA % 2 == 0)
letter = "X";
else
letter = "O";
if (e.getSource() == buttons[0]){
myButtons[count][0].setText(letter);
count --;
}
if (e.getSource() == buttons[1]){
myButtons[count2][1].setText(letter);
count2 --;
}
if (e.getSource() == buttons[2]){
myButtons[count3][2].setText(letter);
count3--;
}
if (e.getSource() == buttons[3]){
myButtons[count4][3].setText(letter);
count4--;
}
if (e.getSource() == buttons[4]){
myButtons[count5][4].setText(letter);
count5--;
}
if (e.getSource() == buttons[5]){
myButtons[count6][5].setText(letter);
count6--;
}
if (e.getSource() == buttons[6]){
myButtons[count7][6].setText(letter);
count7--;
}
if (myButtons[0][0].getText().equals("O") || myButtons[0][0].getText().equals("X")){
buttons[0].setEnabled(false);
}
if (myButtons[0][1].getText().equals("O") || myButtons[0][1].getText().equals("X")){
buttons[1].setEnabled(false);
}
if (myButtons[0][2].getText().equals("O") || myButtons[0][2].getText().equals("X")){
buttons[2].setEnabled(false);
}
if (myButtons[0][3].getText().equals("O") || myButtons[0][3].getText().equals("X")){
buttons[3].setEnabled(false);
}
if (myButtons[0][4].getText().equals("O") || myButtons[0][4].getText().equals("X")){
buttons[4].setEnabled(false);
}
if (myButtons[0][5].getText().equals("O") || myButtons[0][5].getText().equals("X")){
buttons[5].setEnabled(false);
}
if (myButtons[0][6].getText().equals("O") || myButtons[0][6].getText().equals("X")){
buttons[6].setEnabled(false);
if (myButtons[0][6].getText().equals("O") || myButtons[0][6].getText().equals("X")){
buttons[6].setEnabled(false);
if (checkHorizontalWin(letter)
|| checkVerticalWin(letter)
|| checkDiagonalToTheLeftWin(letter)
|| checkDiagonalToTheRightWin(letter)
) {
win = true;
if (win == true) {
JOptionPane.showMessageDialog(null, letter + " has won!");
System.exit(0);
}
}
}
if(win == true){
JOptionPane.showMessageDialog(null, letter + " has won!");
System.exit(0);
} else if(count == 42 && win == false){
JOptionPane.showMessageDialog(null, "tie game");
System.exit(0);
}
}
}
public static void main(String[] args){
new Connect();
}
}
Identation helps.
if (myButtons[0][6].getText().equals("O") || myButtons[0][6].getText().equals("X"))
{
buttons[6].setEnabled(false);
// Missing brace on previous if
// checkXWin methods only invoked inside the above if-statement.
if (checkHorizontalWin(letter)
|| checkVerticalWin(letter)
|| checkDiagonalToTheLeftWin(letter)
|| checkDiagonalToTheRightWin(letter)
) {
win = true;
if (win == true) {
JOptionPane.showMessageDialog(null, letter + " has won!");
ystem.exit(0);
}
}
}
You haven't closed a brace in one of your if statements properly in the actionPerformed method. As a result, your program will only check for a win once the last column is full.
It also seems the condition if (myButtons[0][6].getText().equals("O") || myButtons[0][6].getText().equals("X") is repeated twice. That wouldn't be the cause of your issue but I think you might want to remove one of those statements.
Your brackets on your if statements are incorrectly placed.
if (myButtons[0][6].getText().equals("O") || myButtons[0][6].getText().equals("X")){
buttons[6].setEnabled(false);
if (myButtons[0][6].getText().equals("O") || myButtons[0][6].getText().equals("X")){
buttons[6].setEnabled(false);
On both of theses if statements you have opening brackets but the closing brackets do not come until the end of the actionPerformed method.
This means the code to check for a winner does not get executed unless both of these conditions resulted in true, which is not what you want and I'm pretty sure is impossible...