I've done my first aplication - Tic Tac Toe. I want to add a new function - display a winner (player X or O). How Can I do it?
public class Test extends JFrame {
int counter = 0;
public Test(){
setSize(800,800);
setTitle("Kółko i krzyżyk");
setVisible(true);
setLayout(new GridLayout(3,3));
for (int i = 1; i <= 9; i++){
JButton button = new JButton ("");
add (button);
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (counter % 2 ==0){
button.setText("X");
System.out.println("X");
} else{
button.setText("O");
System.out.println("O");
}
button.setEnabled(false);
counter++;
}
});
}
}
1.Player Class :
import java.util.Scanner;
public class Player {
private String name;
private MarkType mark;
private int row, col;
Scanner sc = new Scanner(System.in);
public Player(String name, MarkType mark) {
this.mark = mark;
this.name = name;
}
public String getName() {
return name;
}
public MarkType getMark() {
return mark;
}
public void nextMove() {
System.out.println(this.getName() + " enter position for " + this.getMark());
row = sc.nextInt();
col = sc.nextInt();
}
public int getRow() {
return row - 1;
}
public int getCol() {
return col - 1;
}
}
2.Board Class :
public class Board {
private MarkType board[][];
private int bsize;
public Board(int bsize) {
this.bsize = bsize;
board = new MarkType[bsize][bsize];
}
public int getBoardSize() {
return bsize;
}
public void updateBoard(int row, int col, MarkType mark) {
if (row > bsize || col > bsize) {
throw new ArrayIndexOutOfBoundsException();
} else if (board[row][col] == MarkType.$) {
board[row][col] = mark;
} else {
throw new InvalidPosition("Enter valid position");
}
}
public void initialize() {
for (int row = 0; row < bsize; row++)
for (int col = 0; col < bsize; col++)
board[row][col] = MarkType.$;
}
public boolean isWinner(int passedRow, int passedCol, MarkType mark) {
for (int col = 0; col < bsize; col++) {
if (board[passedRow][col] != mark)
break;
if (col == bsize - 1) {
return true;
}
}
for (int row = 0; row < bsize; row++) {
if (board[row][passedCol] != mark)
break;
if (row == bsize - 1) {
return true;
}
}
if (passedRow == passedCol) {
for (int row = 0; row < bsize; row++) {
if (board[row][row] != mark)
break;
if (row == bsize - 1) {
return true;
}
}
}
if (passedRow + passedCol == bsize - 1) {
for (int index = 0; index < bsize; index++) {
if (board[index][(bsize - 1) - index] != mark)
break;
if (index == bsize - 1) {
return true;
}
}
}
return false;
}
public void display() {
for (int row = 0; row < bsize; row++) {
for (int col = 0; col < bsize; col++) {
System.out.print(" " + board[row][col] + " ");
if (col != bsize - 1) {
System.out.print("|");
}
}
System.out.println();
if (row != bsize - 1) {
for (int col = 0; col < bsize; col++)
System.out.print("--- ");
}
System.out.println();
}
}
}
for complete answer follow the link below:
http://programmersthing.blogspot.in/2017/06/simple-game-in-java.html
Related
public class CA {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] numbersOnBoard = new int[6][6];
boardSetUpA(numbersOnBoard);
printTwoD(numbersOnBoard);
String[][] details = new String[6][6];
boardDetails(details);
}
public static void boardSetUpA(int[][] twoD) {
// Square with even size
// even rows
for (int row = 0; row < twoD.length; row++) {
if (row % 2 == 0) {
int num = twoD.length * (twoD.length - row);
for (int col = 0; col < twoD[row].length; col++) {
twoD[row][col] = num;
num--;
}
} //
else {
int num = twoD.length * (twoD.length - (row + 1)) + 1;
for (int col = 0; col < twoD[row].length; col++) {
twoD[row][col] = num;
num++;
}
}
} // for row
} //
public static void printTwoD(int[][] array) {
for (int row = 0; row < array.length; row++) {
for (int column = 0; column < array[row].length; column++) {
System.out.print(array[row][column] + "\t");
}
System.out.println();
}
}
public static void boardDetails(String[][] board) {
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
if (col + 2 == row || col + 1 == row * 2) {
board[row][col] = "Lad"; // Append value
} else if (col * 2 == row || row * 2 == col) {
board[row][col] = "Cht"; // Append value
} else {
board[row][col] = " ";
}
}
board[board.length - 1][0] = "Start";
if (board.length % 2 == 0) {
board[0][0] = "End";
} else {
board[0][board.length - 1] = "End";
}
}
}
public static void printBoard(int[][] twoD, String[][] strTwoD) {
// Printing
for (int row = 0; row < twoD.length; row++) {
for (int col = 0; col < twoD[row].length; col++) {
System.out.print(twoD[row][col] + " " + strTwoD[row][col] + "\t\t");
}
System.out.println("\n");
}
}
}
I am creating a snakes and ladders game board and the game (will be finished later).I am trying to print the chutes/snakes and ladders on the board using the method boardDetails but it is not showing up, only the board from 1-36 is shown. Am I not calling the method? Any help would be appreciated.
Thanks!
First time actually using the site so if I do anything wrong I apologize in advance and will work to correct it given guidance. I am currently working on my senior project. It is a game very similar to tic-tac-toe but the height and width of the board are of variable sizes and the amount in a row needed to win is also variable (all chosen by the user through jcomboboxes).
the problem is that the miniMax method will often select a tile that's already been chosen. I'm not entirely sure how to figure out the source of the problem, after having done quite a few hours of research. I just need to be pointed in the right direction on the means of finding the source but will gladly take any help I can get
attached below is the code. I provided all of the code for the program so that it can be compiled and tested, hopefully, with ease. If this is the wrong thing to do I apologize, let me know and I will correct.
I found various examples of the minimax algorithm being implemented and ended up using the one in the following link: simplest MiniMax algorithm for TicTacToe AI in Java
I also tried implementing the following: https://medium.com/#pelensky/unbeatable-tic-tac-toe-minimax-in-java-e1ad687ed821
but that led to numerous stackoverflow errors that I couldn't see how to reasonably mitigate without redoing the entire algorithm.
I am currently working with the former and it works to an extent but the AI doesn't appear to make intelligent decisions and will often try to choose a tile that's already been selected.
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
public class Konnexion extends JPanel
{
ArrayList<JButton> buttons = new ArrayList<JButton>();
private static int totalButtons;
private JLabel winStat;
private JLabel lossStat;
protected JLabel drawStat;
JPanel gameBoard;
JButton exitButton;
int wins = 0;
int losses = 0;
int draws = 0;
Game game;
public Konnexion(int height, int width, int connects, String ai)
{
JPanel gameStats = new JPanel();
gameStats.setLayout(new GridLayout(1,3));
winStat = new JLabel("Wins: " + wins);
lossStat = new JLabel("Losses: " + losses + " ");
drawStat = new JLabel("Draws: " + draws);
gameStats.add(winStat);
gameStats.add(lossStat);
gameStats.add(drawStat);
add(gameStats);
totalButtons = (height * width) - 1;
gameBoard = new JPanel();
gameBoard.setLayout(new GridLayout(height,width));
initializebuttons();
add(gameBoard);
JPanel menuButtons = new JPanel();
menuButtons.setLayout(new GridLayout(1,1));
exitButton = new JButton();
exitButton.setText("Exit Game");
exitButton.addActionListener(new buttonListener());
menuButtons.add(exitButton);
add(menuButtons);
game = new Game(totalButtons, height, width, connects, ai);
}
public void initializebuttons()
{
for(int i = 0; i <= totalButtons; i++)
{
buttons.add(i, new JButton());
buttons.get(i).setText("");
buttons.get(i).setPreferredSize(new Dimension(75,75));
buttons.get(i).addActionListener(new buttonListener());
gameBoard.add(buttons.get(i));
}
}
public void resetButtons()
{
for(int i = 0; i <= totalButtons; i++)
{
buttons.get(i).setText("");
}
game.resetGameState();
}
private class buttonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JButton buttonClicked = (JButton)e.getSource(); //get the particular button that was clicked
if (buttonClicked.getText().equals(""))
{
buttonClicked.setText(Game.getSymbol(game.getCurrentPlayer()));
game.setMarker(buttons.indexOf(buttonClicked), game.getSymbol(game.getCurrentPlayer()));
if (Game.getSymbol(game.getCurrentPlayer()).equals("X"))
{
game.changeCurrentPlayer();
if (game.hasWon("X", Game.cells)) {
wins++;
winStat.setText("Wins: " + wins);
JOptionPane.showConfirmDialog(null, "Player X Wins!!!");
resetButtons();
game.resetGameState();
}
}
else
{
game.changeCurrentPlayer();
if (game.hasWon("O", Game.cells)) {
losses++;
lossStat.setText("Losses: " + losses + " ");
JOptionPane.showConfirmDialog(null, "Player O Wins!!!");
resetButtons();
game.resetGameState();
}
}
if (game.getCurrentPlayer() == 2) {
game.printArrays();
game.copyGameState();
//System.out.println(game.miniMax(game.getCurrentPlayer()));
buttons.get(game.miniMax(game.getCurrentPlayer())).doClick();
}
}
else if (buttonClicked.equals(exitButton))
{
Window window = SwingUtilities.getWindowAncestor(exitButton);
window.dispose();
try {
new MainMenu();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else
{
JOptionPane.showMessageDialog(buttonClicked, "That tile has already been selected!");
}
if (game.checkDraw())
{
draws++;
drawStat.setText("Draws: " + draws);
JOptionPane.showConfirmDialog(null, "It was a Draw!!!");
resetButtons();
}
}
}
}
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class Game {
public static int ROWS;
public static int COLS;
public static int WIN_SIZE;
public static int currentPlayer;
public static String[][] cells; //Game state array
String[][] node; //copy of the game state used for minimax method
public Game(int totalButtons, int height, int width, int connects, String difficulty) {
ROWS = height;
COLS = width;
WIN_SIZE = connects;
currentPlayer = 1;
cells = new String[ROWS][COLS];
node = new String[ROWS][COLS];
resetGameState(cells);
resetGameState(node);
}
public void setMarker(int space, String marker) {
int col = space % COLS;
int rows = space / COLS;
cells[rows][col] = marker;
}
public void changeCurrentPlayer() {
if (currentPlayer == 1)
{
currentPlayer = 2;
}
else if (currentPlayer == 2)
{
currentPlayer = 1;
}
}
public int getCurrentPlayer() {
return currentPlayer;
}
public static String getSymbol(int playerNum) {
if (playerNum == 1)
return "X";
else
return "O";
}
public void resetGameState() {
currentPlayer = 1;
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
cells[i][j] = "-";
}
}
}
public static void resetGameState(String[][] gameState) {
for (int i = 0; i < gameState.length; i++) {
for (int j = 0; j < gameState[i].length; j++) {
gameState[i][j] = "-";
}
}
}
/**
*
* #param theSeed Value expected in each cell
* #param row Row index to check
* #param col Col index to check
* #param count Number of consecutive elements found in the line.
* #param rowIncrement Increment to the row index for the next evaluation
* #param colIncrement Increment to the col index for the next evaluation
* #return true if there is a winner combination in the line, otherwise false.
*/
private boolean checkLine(String theSeed, int row, int col, int count, int rowIncrement, int colIncrement, String[][] gameCheck) {
if (!areValidIndexes(row, col)) {
return false;
}
if (theSeed.equals(gameCheck[row][col])) {
count++;
if (count >= WIN_SIZE) {
return true;
} else {
return checkLine(theSeed, row + rowIncrement, col + colIncrement, count, rowIncrement, colIncrement, gameCheck);
}
} else {
return false;
}
}
private boolean areValidIndexes(int row, int col) {
if (row >= 0 && row < ROWS &&
col >= 0 && col < COLS) {
return true;
}
return false;
}
private boolean checkRow(String theSeed, int row, int col, String[][] gameCheck) {
return checkLine(theSeed, row, col, 0, 1, 0, gameCheck);
}
private boolean checkColumn(String theSeed, int row, int col, String[][] gameCheck) {
return checkLine(theSeed, row, col, 0, 0, 1, gameCheck);
}
private boolean checkForwardDiagonal(String theSeed, int row, int col, String[][] gameCheck) {
return checkLine(theSeed, row, col, 0, 1, 1, gameCheck);
}
private boolean checkBackwardDiagonal(String theSeed, int row, int col, String[][] gameCheck) {
return checkLine(theSeed, row, col, 0, -1, 1, gameCheck);
}
public boolean hasWon(String theSeed, String[][] gameCheck) {
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
if (checkRow(theSeed, row, col, gameCheck) ||
checkColumn(theSeed, row, col, gameCheck) ||
checkForwardDiagonal(theSeed, row, col, gameCheck) ||
checkBackwardDiagonal(theSeed, row, col, gameCheck)) {
return true;
}
}
}
return false;
}
public boolean checkDraw()
{
String s = "";
for (String[] r : cells) {
for (String t : r) {
s += t;
}
}
if (!s.contains("-"))
{
return true;
}
return false;
}
public static boolean checkDraw(String[][] node)
{
String s = "";
for (String[] r : node) {
for (String t : r) {
s += t;
}
}
if (!s.contains("-"))
{
return true;
}
return false;
}
public int checkWin(String[][] gameState) {
if (hasWon("X", gameState))
{
return 1;
}
else if (hasWon("O", gameState))
{
return 2;
}
else
{
return 0;
}
}
public void copyGameState() {
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
node[i][j] = cells[i][j];
}
}
}
public static int[] getAvailableSpaces() {
String s = "";
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
if (cells[i][j].equals("-"))
s += ((j * COLS) + i) + ", ";
}
}
String[] split = s.split(", ");
int[] availableSpaces = new int[split.length];
for (int i = 0; i < split.length; i++)
availableSpaces[i] = Integer.parseInt(split[i]);
return availableSpaces;
}
public void resetSpace(int space) {
int col = space % COLS;
int rows = space / COLS;
cells[rows][col] = "-";
}
public int miniMax(int playerNum)
{
//printArrays();
int victor = checkWin(cells); // returns 0 if game is ongoing, 1 for p1, 2 for p2, 3 for tie.
if(victor != 0) //game over
{
return Score(victor);
}
if(playerNum == 2) //AI
{
int bestVal = Integer.MAX_VALUE;
int bestSpot = 0;
for(int i = 0; i < cells.length; i++)
for (int j = 0; j < cells[i].length; j++)
{
if(!cells[i][j].equals("-"))
continue;
cells[i][j] = getSymbol(playerNum);
int value = miniMax(1);
if(value < bestVal)
{
bestVal = value;
bestSpot = (j * COLS) + i;
System.out.println("Best Value: " + bestVal);
System.out.println("Best Spot: " + bestSpot);
}
cells[i][j] = "-";
}
return bestSpot;
}
else
{
int bestVal = Integer.MIN_VALUE;
int bestSpot = 0;
for(int i = 0; i < cells.length; i++)
for(int j = 0; j < cells[i].length; j++)
{
if(!cells[i][j].equals("-"))
continue;
cells[i][j] = getSymbol(playerNum);
int value = miniMax(2);
if(value > bestVal)
{
bestVal = value;
bestSpot = (j * COLS) + i;
}
cells[i][j] = "-";
}
return bestSpot;
}
}
private int Score(int gameState)
{
if(gameState ==2) //O wins.
return 10;
else if(gameState==1) //X wins
return -10;
return 0;
}
public void printArrays() {
String s = "cells: ";
String l = "node: ";
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j <cells[i].length; j++) {
s += cells[i][j];
l += node[i][j];
}
}
System.out.println(s);
System.out.println(l);
}
}
This project involves three classes. Star creates the stars, Starfield creates a matrix of stars, and StarfieldSimualation is the runner
When I omit row 0, it omits the bottom row, instead of the top one. But, it works for rows 1-4. Thanks in advance for the help.
Starfield Code
public class Starfield
{
private Star[][] Sky;
public Starfield(int rows, int cols)
{
if(rows < 0 || cols < 0)
{
rows = cols = 1;
}
Sky = new Star[rows][cols];
}
public String toString()
{
String S = "";
for (Star[] row: Sky)
{
for(Star X: row)
{
if(X != null)
{
S+= X.getImage() + "\t";
}
else
{
S += "- \t";
}
}
S += "\n";
}
return S;
}
public void addStar(String Image, String Constellation, int row, int col)
{
if(row < 0 || row >= Sky.length || col < 0 || col >= Sky[0].length)
{
return;
}
Sky[row][col] = new Star(Image, Constellation, row, col);
}
public Star[][] omitRow(int r)
{
int i, j, k;
k = 0;
Star[][] rowless = new Star[Sky.length - 1][Sky[0].length];
for(i = 0; i < Sky.length-1; i++)
{
for(j = 0; j < Sky[0].length; j++)
{
k++;
}
}
Star[] ans = new Star[k];
k = 0;
for(i = 0; i < Sky.length; i++)
{
for(j = 0; j < Sky[0].length; j++)
{
if(i != r)
{
ans[k] = Sky[i][j];
k++;
}
}
}
k = 0;
for(i = 0; i < rowless.length; i++)
{
for(j = 0; j < rowless[0].length; j++)
{
if(i != r)
{
rowless[i][j] = ans[k];
k++;
}
}
}
return rowless;
}
Star Code
public class Star
{
private Star[][] Sky;
private String Image, Constellation;
private int row, col;
public Star(String I, String C, int r, int c)
{
Image = I;
Constellation = C;
row = r;
col = c;
}
public String getImage()
{
return Image;
}
public String getConstellation()
{
return Constellation;
}
public int getRow()
{
return row;
}
public int getCol()
{
return col;
}
}
Starfield Simluation Code
public class StarFieldSimulation
{
public static void main(String[] args)
{
Starfield theSky = new Starfield(5,4);
theSky.addStar("*", "Orion", 2, 3);
theSky.addStar("*", "Orion", 2, 2);
theSky.addStar("*", "Orion", 2, 1);
theSky.addStar("*", "Orion", 2, 0);
theSky.addStar("*", "Orion", 1, 3);
System.out.println("IT'S THE SKY EVERYONE");
System.out.println(theSky.toString());
Star[][] minusrow = new Star[4][4];
minusrow = theSky.omitRow(4);
System.out.println("A row has been removed");
System.out.println();
for(Star[] row: minusrow)
{
for(Star X: row)
{
if(X != null)
{
System.out.print(X.getImage() + "\t");
}
else
{
System.out.print("-\t");
}
}
System.out.println();
}
System.out.println();
System.out.println("It's the sky again");
System.out.println(theSky.toString());
}
I am making a Sudoku game in Java and I need some help.
I've got two classes for generating the Sudoku puzzle: SudokuSolver, SudokuGenerator`.
The SudokuSolver creates a full valid Sudoku puzzle for an empty table and the SudokuGenerator removes a random value from the table and then checks (using SudokuSolver) if the Sudoku puzzle is unique.
I found out that the Sudoku puzzle isn't unique, so I think my algorithm for checking the uniqueness of the Sudoku puzzle is bad.
For example, I have this Sudoku puzzle
497816532
132000000
000000000
910600080
086009000
000084963
021063059
743050020
600278304
And this solution:
497816532
132**745**698
568392471
914**637**285
386529147
275184963
821463759
743951826
659278314
I went to https://www.sudoku-solutions.com/ and I added the pattern of my Sudoku and they gave me another solution:
497816532
132**547**698
568392471
914**635**287
386729145
275184963
821463759
743951826
659278314
The funny think is that they're saying that This puzzle is valid and has a unique solution.
Some opinions?
SudokuSolver
public class SudokuSolver {
public static final int GRID_SIZE = 9;
public static final int SUBGRID_SIZE = 3;
private static int validRow = 0;
private static int validCol = 0;
private int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9};
public boolean solveSudoku(int[][] values, int forbiddenNum) {
if(!findUnassignedLocation(values)) return true;
//suffle the nums array - for having a different valid sudoku
shuffleNums();
for (int i = 0; i < GRID_SIZE; i++) {
int num = nums[i];
if(num == forbiddenNum) continue; //
if(isSafe(values,validRow, validCol, num)) {
values[validRow][validCol] = num;
if(solveSudoku(values, forbiddenNum)) return true;
if(validCol == 0) {
validRow--;
validCol = 8;
}else{
validCol--;
}
values[validRow][validCol] = 0;
}
}
return false;
}
public boolean createValidSudoku(int[][] values) {
if(!findUnassignedLocation(values)) return true;
shuffleNums();
for (int i = 0; i < GRID_SIZE; i++) {
int num = nums[i];
if(isSafe(values,validRow, validCol, num)) {
values[validRow][validCol] = num;
if(createValidSudoku(values)) return true;
if(validCol == 0) {
validRow--;
validCol = 8;
}else{
validCol--;
}
values[validRow][validCol] = 0;
}
}
return false;
}
private void shuffleNums() {
Random random = new Random();
for(int i = nums.length - 1; i > 0; i--) {
int index = random.nextInt(i + 1);
int a = nums[index];
nums[index] = nums[i];
nums[i] = a;
}
}
private boolean findUnassignedLocation(int[][] values) {
for(int row = 0; row < GRID_SIZE; row++) {
for(int col = 0; col < GRID_SIZE; col++) {
if (values[row][col] == 0) {
validRow = row;
validCol = col;
return true;
}
}
}
return false;
}
private boolean usedInRow(int[][] values, int row, int num) {
for (int col = 0; col < GRID_SIZE; col++) {
if(values[row][col] == num) return true;
}
return false;
}
private boolean usedInCol(int[][] values, int col, int num) {
for (int row = 0; row < GRID_SIZE; row++) {
if(values[row][col] == num) return true;
}
return false;
}
private boolean usedInBox(int[][] values, int boxStartRow, int boxStartCol, int num) {
for(int row = 0; row < SUBGRID_SIZE; row++) {
for (int col = 0; col < SUBGRID_SIZE; col++) {
if (values[row + boxStartRow][col + boxStartCol] == num) return true;
}
}
return false;
}
private boolean isSafe(int[][] values,int row, int col, int num) {
return !usedInRow(values, row, num) &&
!usedInCol(values, col, num) &&
!usedInBox(values, row - row % 3, col - col % 3, num);
}
public void printGrid(int[][] values) {
for (int row = 0; row < GRID_SIZE; row++) {
for (int col = 0; col < GRID_SIZE; col++) {
System.out.print(values[row][col]);
}
System.out.println();
}
}
}
SudokuGenerator
public class SudokuGenerator {
private int[][] generatorValues = new int[9][9];
public void generateSudoku() {
SudokuSolver sudokuSolver = new SudokuSolver();
//generate a random valid sudoku for an empty table
sudokuSolver.createValidSudoku(generatorValues);
int count = 0;
printNums(generatorValues);
while(count < 40){
Random random = new Random();
int row = 0;
int col = 0;
if(count < 15){
row = random.nextInt(3);
col = random.nextInt(9);
} else if (count >= 15 && count < 30) {
row = random.nextInt(3) + 3;
col = random.nextInt(9);
}else {
row = random.nextInt(3) + 6;
col = random.nextInt(9);
}
int num = generatorValues[row][col];
int tempValues[][] = Arrays.copyOf(generatorValues, generatorValues.length);
//System.out.println("Row:" + row + "Col: " + col + "Num: " + num);
//Set the cell to 0;
if(generatorValues[row][col] != 0){
generatorValues[row][col] = 0;
} else{
continue;
}
//If found a solution, set cell back to original num
if(sudokuSolver.solveSudoku(tempValues, num)) {
generatorValues[row][col] = num;
continue;
}
count++;
}
System.out.println("------------------");
printNums(generatorValues);
}
private void printNums(int[][] values) {
for (int row = 0; row < 9; row++) {
for(int col = 0; col < 9; col++) {
System.out.print(values[row][col]);
}
System.out.println();
}
}
public int[][] getGeneratorValues () {
return generatorValues;
}
}
Below is my code for a Tic Tac Toe game. There are two problems I am running into. For one, I am not sure how to return which player has won (X or O), I can just return if there is a winner. As well, when I try to run my program I can an out of bounds error. Where did I go wrong?
I have two files, one being TicTacToe and the other TTTBoard.
TicTaeToe.java
import java.util.Scanner;
import java.util.Random;
public class TicTacToe
{
public static void main(String[]args){
Scanner reader = new Scanner(System.in);
TTTBoard board = new TTTBoard();
System.out.println(board);
Random gen = new Random();
char player;
if(gen.nextInt(2)==1)
player = 'o';
else
player = 'x';
while(!board.checkWinner() && !board.full()){
System.out.println(player + " 's turn");
System.out.println("Enter the row and column [1-3, space, 1-3]: ");
int row = reader.nextInt();
int column = reader.nextInt();
boolean success = board.placeXor0(player, row, column);
if(!success)
System.out.println("Error: cell already occupied!");
else{
System.out.println(board);
if(player == 'x')
player = 'o';
else
player = 'x';
}
}
}
}
TTTBoard.java
public class TTTBoard{
private char[][] board;
public TTTBoard(){
board = new char[3][3];
reset();
}
public void reset(){
for(int row = 0; row < 3; row++)
for(int column = 0; column < 3; column++)
board[row][column] = '-';
}
public String toString(){
String result = "\n";
for(int row = 0; row <3; row++){
for (int column = 0; column < 3; column++)
result += board[row][column] + " ";
result +="\n";
}
return result;
}
public boolean placeXor0(char player, int row, int column){
if(board[row -1][column -1]=='-'){
board[row-1][column-1]= player;
return true;
}
else
return false;
}
public boolean checkWinner(){
return(checkRowsForWin()||checkColumnsForWin()||checkDiagnalsForWin());
}
public boolean full(){
boolean full = true;
for(int row = 0; row < 3; row++){
for(int column = 0; column < 3; column++){
if(board[row][column] == '-'){
full = false;
}
}
}
return full;
}
public boolean checkRowsForWin(){
for(int row = 0; row < 3; row++){
if(placeXor0(board[row][0], board[row][1], board[row][2]) == true){
return true;
}
}
return false;
}
public boolean checkColumnsForWin(){
for(int column = 0; column < 3; column++){
if(placeXor0(board[0][column], board[1][column], board[2][column]) == true){
return true;
}
}
return false;
}
public boolean checkDiagnalsForWin(){
return((placeXor0(board[0][0], board[1][1], board[2][2]) == true) || (placeXor0(board[0][2], board[1][1], board[2][0]) == true));
}
}
New Code:
public class TTTBoard{
private char[][] board;
public TTTBoard(){
board = new char[3][3];
reset();
}
public void reset(){
for(int row = 0; row < 3; row++)
for(int column = 0; column < 3; column++)
board[row][column] = '-';
}
public String toString(){
String result = "\n";
for(int row = 0; row <3; row++){
for (int column = 0; column < 3; column++)
result += board[row][column] + " ";
result +="\n";
}
return result;
}
public boolean placeXor0(char player, int row, int column){
if(board[row -1][column -1]=='-'){
board[row-1][column-1]= player;
return true;
}
else
return false;
}
public boolean checkWinner(){
return(checkRowsForWin()||checkColumnsForWin()||checkDiagnalsForWin());
}
/*public String getWinner(){
for(int row = 0; row <3; row++){
for (int column = 0; column < 3; column++)
}
}*/
public boolean full(){
boolean full = true;
for(int row = 0; row < 3; row++){
for(int column = 0; column < 3; column++){
if(board[row][column] == '-'){
full = false;
}
}
}
return full;
}
public boolean checkRowsForWin(){
for(int row = 0; row < 3; row++){
if(board[row][0]== board[row][1]&& board[row][0]== board[row][2]){
return true;
}
}
return false;
}
public boolean checkColumnsForWin(){
for(int column = 0; column < 3; column++){
if (board[0][column] == board[1][column] && board[0][column] == board[2][column]) {
return true;
}
}
return false;
}
public boolean checkDiagnalsForWin(){
return((board[0][0]== board[1][1]&& board[0][0] == board[2][2]) || (board[0][2] == board[1][1] && board[0][2]== board[2][0]));
}
}
In checkRowsForWin, you have the lines of code:
if(placeXor0(board[0][column], board[1][column], board[2][column]) == true) {
return true;
}
You want to replace this with:
if (board[0][column] == board[1][column] && board[0][column] == board[2][column]) {
return true;
}
And do a similar thing for checkColumnsForWin and checkDiagnalsForWin