I'm building a 2D grid game composed of cells in which players have to put tokens and try to contain (encircle) the opponent's tokens. Now each cell can have 3 states: empty, contains a red token or contains a blue token.
All cells that can form a "path" are in a list, and along that path I can draw lines (polygons) passing by the center of cells.
Also there is a list of contained tokens, the one being encircled,
Now I want to find a way to "invalidate" an encircled token so it can be ignored by path calculations
See examples below:
Blue tokens are encircled first, they cannot be apart of any further path calculation.
This cannot be allowed. First to contain, first to win.
All codes below are from the path class:
class Path extends Stack<int[]>{
private Token[][] grid;
//a path shorter than min can not surround any cell
private static final int MIN_PATH_LEGTH = 3;
//a collection of cells that has been tested
private ArrayList<int[]>checked;
//represents the cell where the search starts from
int[] origin;
//represents the token of the origin
Token originToken;
private int rows;
private int cols;
//represents the path bounds: min/max row/col in path
private int minPathRow, maxPathRow, minPathCol, maxPathCol;
Path(Token[][] grid){
this.grid = grid;
rows = grid.length;
cols = grid[0].length;
}
//search for a path
boolean findPath(int[] origin) {
this.origin = origin;
int row = origin[0] , col = origin[1];
//represents the token of the origin
originToken = grid[row][col];
//initialize list of checked items
checked = new CellsList();
boolean found = findPath(row, col);
if(found) {
printPath();
} else {
System.out.println("No path found");
}
return found;
}
//recursive method to find path. a cell is represented by its row, col
//returns true when path was found
private boolean findPath(int row, int col) {
//check if cell has the same token as origin
if(grid[row][col] != originToken) {
return false;
}
int[] cell = new int[] {row, col};
//check if this cell was tested before to avoid checking again
if(checked.contains(cell)) {
return false;
}
//get cells neighbors
CellsList neighbors = getNeighbors(row, col);
//check if solution found. If path size > min and cell
//neighbors contain the origin it means that path was found
if((size() >= MIN_PATH_LEGTH) && neighbors.contains(origin) ) {
add(cell);
return true;
}
//add cell to checked
checked.add(cell);
//add cell to path
add(cell);
//if path was not found check cell neighbors
for(int[] neighbor : neighbors ) {
boolean found = findPath(neighbor[0],neighbor[1]);
if(found) {
return true;
}
}
//path not found
pop(); //remove last element from stack
return false;
}
//use for testing
private void printPath() {
System.out.print("Path : " );
for(int[] cell : this) {
System.out.print(Arrays.toString(cell));
}
System.out.println("");
List<int[]> containedCells = getContainedWithin();
System.out.print(containedCells.size() +" cell contained : " );
for(int[] cell : containedCells) {
System.out.print(Arrays.toString(cell));
}
System.out.println("");
}
CellsList getPath() {
CellsList cl = new CellsList();
cl.addAll(this);
return cl;
}
}
The code below finds the neighbors of a cell (path.java):
//return a list of all neighbors of cell row, col
private CellsList getNeighbors(int row, int col) {
CellsList neighbors = new CellsList();
for (int colNum = col - 1 ; colNum <= (col + 1) ; colNum +=1 ) {
for (int rowNum = row - 1 ; rowNum <= (row + 1) ; rowNum +=1 ) {
if(!((colNum == col) && (rowNum == row))) {
if(isWithinGrid (rowNum, colNum ) ) {
neighbors.add( new int[] {rowNum, colNum});
}
}
}
}
return neighbors;
}
private boolean isWithinGrid(int colNum, int rowNum) {
if((colNum < 0) || (rowNum <0) ) {
return false;
}
if((colNum >= cols) || (rowNum >= rows)) {
return false;
}
return true;
}
}
The below code finds all bounded cell by a path (all contained or encircled tokens) and their token is of the opposite color of the path:
List<int[]> getContainedWithin() {
//find path max and min X values, max and min Y values
minPathRow = grid[0].length; //set min to the largest possible value
maxPathCol = grid.length;
maxPathRow = 0; //set max to the largest possible value
maxPathCol = 0;
//find the actual min max x y values of the path
for (int[] cell : this) {
minPathRow = Math.min(minPathRow, cell[0]);
minPathCol = Math.min(minPathCol, cell[1]);
maxPathRow = Math.max(maxPathRow, cell[0]);
maxPathCol = Math.max(maxPathCol, cell[1]);
}
List<int[]> block = new ArrayList<>(25);
int[] cell = get(0);//get an arbitrary cell in the path
Token pathToken = grid[cell[0]][cell[1]]; //keep a reference to its token
//iterate over all cells within path x, y limits
for (int col = minPathCol; col < (maxPathCol); col++) {
for (int row = minPathRow; row < (maxPathRow); row++) {
//check cell color
Token token = grid[row][col];
if ((token == pathToken) || (token == Token.VIDE)) {
continue;
}
if (isWithinLoop(row,col)) {
block.add(new int[] {row, col});
}
}
}
return block;
}
//check if row, col represent a cell within path by checking if it has a
//path-cell to its left, right, top and bottom
private boolean isWithinLoop(int row, int col) {
if( isPathCellOnLeft(row, col)
&&
isPathCellOnRight(row, col)
&&
isPathCellOnTop(row, col)
&&
isPathCellOnBottom(row, col)
) {
return true;
}
return false;
}
}
If you need more elements, just let me now, I'll update with the necessary.
This requirement means that previous paths, affect current path calculations. It can be achieved in many ways. The easiest, within current program structure could be adding a static collection of contained cells in all paths.
See allContainedWithin and the way it is used in the code.
Also note that I refactored getContainedWithin() to be a getter, and moved its functionality to a new method findContainedWithin().
All changes have no effect on other classes.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
//a stack representing cells in the path
//each cell represented by [row,col]
class Path extends Stack<int[]>{
private Token[][] grid;
//a path shorter than min can not surround any cell
private static final int MIN_PATH_LEGTH = 3;
//a collection of cells that has been tested
private ArrayList<int[]>checked;
//represents the cell where the search starts from
int[] origin;
//represents the token of the origin
Token originToken;
private int rows;
private int cols;
//represents the path bounds: min/max row/col in path
private int minPathRow, maxPathRow, minPathCol, maxPathCol;
//a collection of all cells that are bounded by the path
//and their token is of the opposite color of the path
private List<int[]> containedWithin;
//a STATIC collection that holds all containedWithin cells, of
//current and previous paths
private static CellsList allContainedWithin = new CellsList();
Path(Token[][] grid){
this.grid = grid;
rows = grid.length;
cols = grid[0].length;
}
//search for a path
boolean findPath(int[] origin) {
this.origin = origin;
int row = origin[0] , col = origin[1];
//represents the token of the origin
originToken = grid[row][col];
//initialize list of checked items
checked = new CellsList();
boolean found = findPath(row, col);
if(found) {
//find bounded cells
findContainedWithin();
//update the collection all
allContainedWithin.addAll(containedWithin);
printPath();
} else {
System.out.println("No path found");
}
return found;
}
//recursive method to find path. a cell is represented by its row, col
//returns true when path was found
private boolean findPath(int row, int col) {
//check if cell has the same token as origin
if(grid[row][col] != originToken) {
return false;
}
int[] cell = new int[] {row, col};
//check if this cell was tested before to avoid checking again
if(checked.contains(cell)) {
return false;
}
//check if this cell was contained in previously calculated paths
if(allContainedWithin.contains(cell)) {
return false;
}
//get cells neighbors
CellsList neighbors = getNeighbors(row, col);
//check if solution found. If path size > min and cell
//neighbors contain the origin it means that path was found
if((size() >= MIN_PATH_LEGTH) && neighbors.contains(origin) ) {
add(cell);
return true;
}
//add cell to checked
checked.add(cell);
//add cell to path
add(cell);
//if path was not found check cell neighbors
for(int[] neighbor : neighbors ) {
boolean found = findPath(neighbor[0],neighbor[1]);
if(found) {
return true;
}
}
//path not found
pop(); //remove last element from stack
return false;
}
//return a list of all neighbors of cell row, col
private CellsList getNeighbors(int row, int col) {
CellsList neighbors = new CellsList();
for (int colNum = col - 1 ; colNum <= (col + 1) ; colNum +=1 ) {
for (int rowNum = row - 1 ; rowNum <= (row + 1) ; rowNum +=1 ) {
if(!((colNum == col) && (rowNum == row))) {
if(isWithinGrid (rowNum, colNum ) ) {
neighbors.add( new int[] {rowNum, colNum});
}
}
}
}
return neighbors;
}
private boolean isWithinGrid(int colNum, int rowNum) {
if((colNum < 0) || (rowNum <0) ) {
return false;
}
if((colNum >= cols) || (rowNum >= rows)) {
return false;
}
return true;
}
//use for testing
private void printPath() {
System.out.print("Path : " );
for(int[] cell : this) {
System.out.print(Arrays.toString(cell));
}
System.out.println("");
List<int[]> containedCells = getContainedWithin();
System.out.print(containedCells.size()+" cell contained : " );
for(int[] cell : containedCells) {
System.out.print(Arrays.toString(cell));
}
System.out.println("");
}
CellsList getPath() {
CellsList cl = new CellsList();
cl.addAll(this);
return cl;
}
//finds all cells that are bounded by the path
//and their token is of the opposite color of the path
private void findContainedWithin() {
containedWithin = new ArrayList<>();
//find path max and min X values, max and min Y values
minPathRow = grid[0].length; //set min to the largest possible value
maxPathCol = grid.length;
maxPathRow = 0; //set max to the largest possible value
maxPathCol = 0;
//find the actual min max x y values of the path
for (int[] cell : this) {
minPathRow = Math.min(minPathRow, cell[0]);
minPathCol = Math.min(minPathCol, cell[1]);
maxPathRow = Math.max(maxPathRow, cell[0]);
maxPathCol = Math.max(maxPathCol, cell[1]);
}
//todo remove after testing
System.out.println("x range: "+minPathRow + "-"
+ maxPathRow + " y range: " + minPathCol + "-" + maxPathCol);
int[] cell = get(0);//get an arbitrary cell in the path
Token pathToken = grid[cell[0]][cell[1]]; //keep a reference to its token
//iterate over all cells within path x, y limits
for (int col = minPathCol; col < (maxPathCol); col++) {
for (int row = minPathRow; row < (maxPathRow); row++) {
//check cell color
Token token = grid[row][col];
if ((token == pathToken) || (token == Token.VIDE)) {
continue;
}
if (isWithinLoop(row,col)) {
containedWithin.add(new int[] {row, col});
}
}
}
}
//returns a collection of all cells that are bounded by the path
//and their token is of the opposite color of the path
List<int[]> getContainedWithin() {
return containedWithin;
}
//check if row, col represent a cell with in path by checking if it has a
//path-cell to its left, right, top and bottom
private boolean isWithinLoop(int row, int col) {
if( isPathCellOnLeft(row, col)
&&
isPathCellOnRight(row, col)
&&
isPathCellOnTop(row, col)
&&
isPathCellOnBottom(row, col)
) {
return true;
}
return false;
}
private boolean isPathCellOnLeft(int cellRow, int cellCol) {
for ( int col = minPathCol; col < cellCol ; col++) {
if(getPath().contains(new int[] {cellRow, col})) {
return true;
}
}
return false;
}
private boolean isPathCellOnRight(int cellRow, int cellCol) {
for ( int col = cellCol; col <= maxPathCol ; col++) {
if(getPath().contains(new int[] {cellRow, col})) {
return true;
}
}
return false;
}
private boolean isPathCellOnTop(int cellRow, int cellCol) {
for ( int row =minPathRow; row < cellRow ; row++) {
if(getPath().contains(new int[] {row, cellCol})) {
return true;
}
}
return false;
}
private boolean isPathCellOnBottom(int cellRow, int cellCol) {
for ( int row = cellRow; row <= maxPathRow; row++) {
if(getPath().contains(new int[] {row, cellCol})) {
return true;
}
}
return false;
}
}
Note that I only run some basic testing like :
In addition to the previous answer, I would like to add an alternative which requires a deeper change in the program.
A better way to handle the requirement would be to change the representation of a cell. Instead of using int[]{row, col} , consider representing it by a Cell class which has attributes like row, col,token, contained etc.
A simple implementation of Cell could be :
public class Cell {
private int row, col;
private Token token;
private boolean isContained;
Cell(int row, int col) {
this(row, col, Token.VIDE);
}
Cell(int row, int col, Token token) {
this.row = Math.abs(row); //to allow only positve addresses
this.col = Math.abs(col);
this.token = (token == null) ? Token.VIDE : token;
}
int getRow() {
return row;
}
int getCol() {
return col;
}
Token getToken() {
return token;
}
boolean isContained() {
return isContained;
}
void setRow(int row) {
this.row = row;
}
void setCol(int col) {
this.col = col;
}
void setToken(Token token) {
this.token = token;
}
void setContained(boolean isContained) {
this.isContained = isContained;
}
int[] getAddress() {
return new int[] {row, col};
}
#Override
public String toString() {
return Arrays.toString(getAddress()) +"-"+ token;
}
#Override
public boolean equals(Object cell) {
if ((cell == null) || !(cell instanceof Cell)) {
return false;
}
return Arrays.equals(getAddress(), ((Cell)cell).getAddress());
}
#Override
public int hashCode() {
return 31*row + 17*col;
}
}
Note: This representation should be changed all across the program.
(Not tested)
Related
I'm working on a Connect Four game for the console in Java. I have problems with the winning conditions, as I don't know how to program them. Here is my code my Main:
public class Main {
public static char[] playerNumber = new char[]{'1', '2'};
public static char[] Badge = new char[]{'X', 'O'};
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int moves = 7 * 6;
int whichPlayer = 0;
for (int i = 0; i < 10; i++) {
System.out.println(" FOUR IN A ROW");
System.out.println("-------------------------------------------------------");
System.out.println("Welcome to the amazing game Four In A Row:");
System.out.println("Enter a number between 0 and 6 for choosing a column.");
System.out.println();
Board board = new Board();
board.fillBoard();
board.presentBoard();
do {
// 1. get a badge
char Player = playerNumber[whichPlayer];
char badge = Badge[whichPlayer];
// 2. make a turn
board.makeTurn(badge, Player);
board.presentBoard();
// 3. Tjek om der er vinder
if (board.checkWinHorizontal() || board.checkWinVertical()) {
System.out.println("Player " + Player + " has won!");
break;
}
// 4. change the player
whichPlayer = 1 - whichPlayer;
// 5. decrease moves
--moves;
if (moves == 0) {
System.out.println("Game over, nobody has won.");
System.out.println("Do you want to play again? 'Y' or 'N':");
String newGame = scanner.nextLine();
if (newGame.equals("Y") || newGame.equals("y")) {
break;
}
if (newGame.equals("N") || newGame.equals("n")) {
System.out.println("Thanks for the game!");
return;
}
}
// 6. repeat
} while (true);
}
}
And here is my code for my Board class:
public class Board {
char[][] board = new char[6][7];
int column;
// Fills the empty spaces
public void fillBoard() {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
board[i][j] = ' ';
}
}
}
// Prints the board
public void presentBoard() {
for (int i = 0; i < 6; i++) {
System.out.print(" | ");
for (int j = 0; j < 7; j++) {
System.out.print(board[i][j] + " | ");
}
System.out.println();
System.out.print(" -----------------------------");
System.out.println();
}
}
// Turn
public void makeTurn(char badge, char Player) {
Scanner scanner = new Scanner(System.in);
do {
// 1. Ask for a column
System.out.println("Player " + Player + " turn: ");
column = scanner.nextInt();
// 2. Check if it's between 0 and 6
if (column > 6) {
System.out.println("That is not a valid number. Please enter a number between 0 and 6: ");
continue;
}
// 3. Place a badge
for (int i = 6 - 1; i >= 0; i--) {
if (board[i][column] == ' ') {
board[i][column] = badge;
return;
}
}
// If column is full
System.out.println("Column " + column + " is full. Try another column:");
} while (true);
}
// Check for vertical win
public boolean checkWinVertical() {
return verticalWin(5, column);
}
// Check for horizontal win
public boolean checkWinHorizontal() {
return horizontalWin(5,column);
}
// Conditions for vertical win
private boolean verticalWin(int x, int y) {
char charToCheck = board[x][y];
if (board[x-1][y] == charToCheck &&
board[x-2][y] == charToCheck &&
board[x-3][y] == charToCheck) {
return true;
}
return false;
}
// Conditions for horizontal win
private boolean horizontalWin(int x, int y) {
char charToCheck = board[x][y];
if (board[x][y+1] == charToCheck &&
board[x][y+2] == charToCheck &&
board[x][y+3] == charToCheck) {
return true;
}
return false;
}
I have succeeded in getting the game recognize a win horizontally and vertically at the bottom row of my array, but I don't know how to make the game recognize for the whole array. I'm only concentrating about the horizontal and vertical, as the diagonal is too complicated for me. And I don't know if this is the right approach or there is a better one.
Thanks!
Here's another solution. It's the same general idea as previously mentioned: loop through each row/column, checking for a streak of 4 in a row. Maybe this implementation will provide some other insight. Below, I've shown an example method checking the horizontal streaks. For vertical, you would iterate over the rows in the inner for loop instead.
public boolean checkWin(char badge) {
return checkHorizontalStreaks(board, badge)
|| checkVerticalStreaks(board, badge);
}
private boolean checkHorizontalStreaks(char[][] board, char badge) {
for (int row = 0; row < board.length; row++) {
// loop throught each row
int currentStreak = 0;
for (int col = 0; col < board[row].length; col++) {
// loop through each column in the row
if (board[row][col] == badge) {
// keep the streak of 'badge' going
currentStreak++;
if (currentStreak == 4) {
// winner
return true;
}
} else {
// restart the streak
currentStreak = 0;
}
}
}
return false;
}
And then update your Main class with
if (board.checkWin(badge)) {
System.out.println("Player " + Player + " has won!");
break;
}
I'd wager there is a more efficient way to determine a winner (perhaps by treating the grid as a graph and traversing it with some special logic). However, I suspect this may be enough for what you need. I'll spare you the output, but it worked with a few different test cases.
Possibly you could check all the adjacent fields around the last played field, so after the user did his turn. So for checking upwards you could do this:
public boolean checkUp(int rowPlayed, int columnPlayed){
boolean checked = false;
if(rowplayed + 1 <= maxrows){ //Checks if you didn't hit the top
if(board[rowPlayed+1][columnPlayed] != null){
if(board[rowPlayed+1][columnPlayed].getPlayer() == currentPlayer){
checked = true;
}
}
}
return checked;
}
and for example implemented like this:
public void checkWin(int rowPlayed, int columnPlayed){
boolean checkingWin = true;
int countWin = 0;
while(checkingWin){
if(checkUp(rowPlayed + countWin, columnPlayed)){
countWin++;
}
else{
checkingWin = false;
}
if(countWin == 4){
checkinWin = false;
//Insert win confirmation here
}
}
}
It's partially pseudo code because I don't know exactly how you handle things in your code, nor do I know if this is the best way to do it. But I hope it was of help for you.
This is a long answer and I'll go around the houses a bit so you can see how I reached my solution (which also expands to diagonal checking at the end).
I would use the last piece added as a starting point and work from there since checking all combinations is exhaustive and unnecessary.
Given the row and column of the last piece added I need to decide what I need to achieve.
I already know that the current row and column has the piece of the colour I'm looking for so I can ignore that.
For horizontal matching, I want to check I want to checking pieces to left and right in the same row have the same colour, and stop if the colour is different or there is no piece.
So imagine the following board (# = empty, R = Red piece, Y = Yellow piece:
6 # # # # # # # #
5 # # # # # # # #
4 # # # # # # # #
3 # # # # # # # #
2 # # # # # # # #
1 # # # # # # # #
0 Y R R R Y Y Y R
0 1 2 3 4 5 6 7
The last move was Yellow, row 0, col 4.
So I want to check left and right from [0][4] and see if the total number of consecutive pieces of the colour is 3, (not 4) since I know [0][4] is Yellow and can be discounted.
Based on this I can take a recursive approach where I check the adjacent to one side, then recursively do the same thing as long as I keep matching pieces of the same colour or do not encounter an empty slot.
I'll start of with a check to the right (to demonstrate):
private static final int COLS = 7;
private static final int ROWS = 6;
public enum Piece {RED, YELLOW}; // null is empty
private Piece[][] board = new Piece[ROWS][COLS]; // the board
private int checkRight(Piece piece, int row, int col) {
// assume valid row for now
col++; // moving col to the right
if (col >= COLS || board[row][col] != piece) {
// We're outside the limits of the column or the Piece doesn't match
return 0; // So return 0, nothing to add
} else {
// otherwise return 1 + the result of checkRight for the next col
return 1 + checkRight(piece, row, col);
}
}
Now I can perform the same to the left.
private int checkLeft(Piece piece, int row, int col) {
// assume valid row for now
col--; // moving col to the left
if (col < 0 || board[row][col] != piece) {
// We're outside the limits of the column or the Piece doesn't match
return 0; // So return 0, nothing to add
} else {
// otherwise return 1 + the result of checkLeft for the next col
return 1 + checkLeft(piece, row, col);
}
}
And to check a winner for horizontal, I could do this:
public boolean checkWinner(Piece piece, int row, int col) {
// if the sum is 3, we have a winner (horizontal only).
return checkRight(piece, row, col) + checkLeft(piece, row, col) == 3;
}
Ugh, there's a lot of repetition isn't there?
We can condense the two methods into one by introducing a new parameter direction which can change if we move col positive or negative through the values 1 and -1 respectively:
private int check(Piece piece, int row, int col, int direction) {
col += direction; // direction is either 1 (right) or -1 (left)
if (col < 0 || col >= COLS || board[row][col] != piece) {
return 0;
} else {
return 1 + check(piece, row, col);
}
}
Update checkWinner() for this new parameter:
private static final int POSITIVE = 1; // right at the moment
private static final int NEGATIVE = -1; // left at the moment
public boolean checkWinner(Piece piece, int row, int col) {
// if the sum is 3, we have a winner (horizontal only).
return check(piece, row, col, POSITIVE) + check(piece, row, col, NEGATIVE) == 3;
}
Now I could implement the same sort of logic for vertical, but instead stay on the same col and change the row. I will skip this part in detail and move onto a solution which includes this and diagonal checking.
This has been done using an enum called CheckType storing values for which row and col should change and is used by the check() method. e.g. for HORIZONTAL the column changes by 1 or -1 (depending upon the direction specified when check() is called) and the row remains 0.
public class Board {
public enum Piece {
RED, YELLOW
};
private enum CheckType {
HORIZONTAL(0, 1), VERTICAL(1, 0), DIAGNONAL_UP(1, 1), DIAGNONAL_DOWN(-1, 1);
int row;
int col;
CheckType(int row, int col) {
this.row = row;
this.col = col;
}
}
private static final int POSITIVE = 1;
private static final int NEGATIVE = -1;
private static final int ROWS = 6;
private static final int COLS = 7;
private Piece[][] board = new Piece[ROWS][COLS];
private boolean hasWinner = false;
public boolean hasWinner() {
return hasWinner;
}
private void checkWinner(Piece piece, int row, int col) {
// check all values of enum CheckType for a winner
// so HORIZONTAL, VERTICAL, etc..
int enumIndex = 0;
while (!hasWinner && enumIndex < CheckType.values().length) {
hasWinner = check(piece, row, col, POSITIVE, CheckType.values()[enumIndex])
+ check(piece, row, col, NEGATIVE, CheckType.values()[enumIndex]) == 3;
enumIndex++;
}
}
private int check(Piece piece, int row, int col, int direction, CheckType type) {
row += type.row * direction;
col += type.col * direction;
if (row >= ROWS || row < 0 || col >= COLS || col < 0 || board[row][col] != piece) {
return 0;
} else {
return 1 + check(piece, row, col, direction, type);
}
}
// for completeness, adding a Piece
public boolean add(Piece piece, int col) {
int row = 0;
while (row < ROWS && board[row][col] != null) {
row++;
}
if (row < ROWS) {
board[row][col] = piece;
// check for winner after successful add
checkWinner(piece, row, col);
}
return row < ROWS;
}
}
Hope this helps.
I cannot get my write to file code working the error message- writeFile cannot be resolved. I a trying to write the board positions to a text file so the game can be saved. If the user chooses to save the game then it should call a new subroutine that will write the pieces to the file.
/*
* Skeleton program code for the AQA COMP1 Summer 2016 examination
* This code to be used in conjunction with the Preliminary Material
* written by the AQA Programmer Team
* Developed in the NetBeans 7.3.1. programming environment
* Additional classes AQAConsole2016, AQAReadTextFile2016 and
* AQAWriteTextFile2016 may be used.
*
* A package name may be chosen and private and public modifiers added -
* permission to make these changes to the Skeleton Program does not need
* to be obtained from AQA or the AQA Programmer
*/
import java.util.Random;
public class Aaa {
AQAConsole2016 console = new AQAConsole2016();
Random random = new Random();
int boardSize;
public Aaa() {
char choice;
String playerName;
// int boardSize;
boardSize = 6;
playerName = "";
do {
displayMenu();
choice = getMenuChoice(playerName);
switch (choice) {
case 'p' : playGame(playerName, boardSize);
break;
case 'e' : playerName = getPlayersName();
break;
case 'c' : boardSize = changeBoardSize();
break;
}
} while (choice != 'q');
}
void setUpGameBoard(char[][] board, int boardSize) {
for (int row = 1; row <= boardSize; row++) {
for (int column = 1; column <= boardSize; column++) {
if (row == (boardSize + 1) / 2 && column == (boardSize + 1) / 2 + 1 || column == (boardSize + 1) / 2 && row == (boardSize + 1) / 2 + 1) {
board[row][column] = 'C';
} else {
if (row == (boardSize + 1) / 2 + 1 && column == (boardSize + 1) / 2 + 1 || column == (boardSize + 1) / 2 && row == (boardSize + 1) / 2) {
board[row][column] = 'H';
} else {
board[row][column] = ' ';
}
}
}
}
}
int changeBoardSize() {
int boardSize;
do {
console.print("Enter a board size (between 4 and 9): ");
boardSize = console.readInteger("");
} while (!(boardSize >= 4 && boardSize <= 9));
return boardSize;
}
int getHumanPlayerMove(String playerName) {
int coordinates;
console.print(playerName + " enter the coordinates of the square where you want to place your piece: ");
coordinates = console.readInteger("");
return coordinates;
}
int getComputerPlayerMove(int boardSize) {
return ((random.nextInt(boardSize) + 1) * 10 + (random.nextInt(boardSize) + 1));
}
boolean gameOver(char[][] board, int boardSize) {
for (int row = 1; row <= boardSize; row++) {
for (int column = 1; column <= boardSize; column++) {
if (board[row][column] == ' ')
return false;
}
}
return true;
}
String getPlayersName() {
String playerName;
console.print("What is your name? ");
playerName = console.readLine();
return playerName;
}
boolean checkIfMoveIsValid(char[][] board, int move) {
int row;
int column;
boolean moveIsValid;
row = move % 10;
column = move / 10;
moveIsValid = false;
if (((row<=boardSize) &&(row>0)) && ((column<=boardSize) && (column>0))){
if (board[row][column] == ' ') {
moveIsValid = true;
}
}
return moveIsValid;
}
int getPlayerScore(char[][] board, int boardSize, char piece) {
int score;
score = 0;
for (int row = 1; row <= boardSize; row++) {
for (int column = 1; column <= boardSize; column++) {
if (board[row][column] == piece) {
score = score + 1;
}
}
}
return score;
}
boolean checkIfThereArePiecesToFlip(char[][] board, int boardSize, int startRow, int startColumn, int rowDirection, int columnDirection) {
int rowCount;
int columnCount;
boolean flipStillPossible;
boolean flipFound;
boolean opponentPieceFound;
rowCount = startRow + rowDirection;
columnCount = startColumn + columnDirection;
flipStillPossible = true;
flipFound = false;
opponentPieceFound = false;
while (rowCount <= boardSize && rowCount >= 1 && columnCount >= 1 && columnCount <= boardSize && flipStillPossible && !flipFound ) {
if (board[rowCount][columnCount] == ' ') {
flipStillPossible = false;
} else {
if (board[rowCount][columnCount] != board[startRow][startColumn]) {
opponentPieceFound = true;
} else {
if (board[rowCount][columnCount] == board[startRow][startColumn] && !opponentPieceFound) {
flipStillPossible = false;
} else {
flipFound = true;
}
}
}
rowCount = rowCount + rowDirection;
columnCount = columnCount + columnDirection;
}
return flipFound;
}
void flipOpponentPiecesInOneDirection(char[][] board, int boardSize, int startRow, int startColumn, int rowDirection, int columnDirection) {
int rowCount;
int columnCount;
boolean flipFound;
flipFound = checkIfThereArePiecesToFlip(board, boardSize, startRow, startColumn, rowDirection, columnDirection);
if (flipFound) {
rowCount = startRow + rowDirection;
columnCount = startColumn + columnDirection;
while (board[rowCount][columnCount] != ' ' && board[rowCount][columnCount] != board[startRow][startColumn]) {
if (board[rowCount][columnCount] == 'H') {
board[rowCount][columnCount] = 'C';
} else {
board[rowCount][columnCount] = 'H';
}
rowCount = rowCount + rowDirection;
columnCount = columnCount + columnDirection;
}
}
}
void makeMove(char[][] board, int boardSize, int move, boolean humanPlayersTurn) {
int row;
int column;
row = move % 10;
column = move / 10;
if (humanPlayersTurn) {
board[row][column] = 'H';
} else {
board[row][column] = 'C';
}
flipOpponentPiecesInOneDirection(board, boardSize, row, column, 1, 0);
flipOpponentPiecesInOneDirection(board, boardSize, row, column, -1, 0);
flipOpponentPiecesInOneDirection(board, boardSize, row, column, 0, 1);
flipOpponentPiecesInOneDirection(board, boardSize, row, column, 0, -1);
}
void printLine(int boardSize) {
console.print(" ");
for (int count = 1; count <= boardSize * 2 - 1; count++) {
console.print("_");
}
console.println();
}
void displayGameBoard(char[][] board, int boardSize) {
console.println();
console.print(" ");
for (int column = 1; column <= boardSize; column++)
{
console.print(" ");
console.print(column);
}
console.println();
printLine(boardSize);
for (int row = 1; row <= boardSize; row++) {
console.print(row);
console.print(" ");
for (int column = 1; column <= boardSize; column++) {
console.print("|");
console.print(board[row][column]);
}
console.println("|");
printLine(boardSize);
console.println();
}
}
void displayMenu() {
console.println("(p)lay game");
console.println("(e)nter name");
console.println("(c)hange board size");
console.println("(q)uit");
console.println();
}
char getMenuChoice(String playerName) {
char choice;
console.print(playerName + " enter the letter of your chosen option: ");
choice = console.readChar();
return choice;
}
void playGame(String playerName, int boardSize) {
char[][] board = new char[boardSize + 1][boardSize + 1];
boolean humanPlayersTurn;
int move;
int humanPlayerScore;
int computerPlayerScore;
boolean moveIsValid;
setUpGameBoard(board, boardSize);
humanPlayersTurn = false;
int NoOfMoves=0;
do {
humanPlayersTurn = !humanPlayersTurn;
displayGameBoard(board, boardSize);
moveIsValid = false;
do {
if (humanPlayersTurn) {
move = getHumanPlayerMove(playerName);
} else {
move = getComputerPlayerMove(boardSize);
}
moveIsValid = checkIfMoveIsValid(board, move);
} while (!moveIsValid);
if (!humanPlayersTurn) {
NoOfMoves++;
console.println("The number of moves completed so far: " +NoOfMoves);
console.print("Press the Enter key and the computer will make its move");
console.readLine("");
}
makeMove(board, boardSize, move, humanPlayersTurn);
console.println();
String answer = console.readLine("Do you want to save the board? (y/n)");
if (answer.equalsIgnoreCase("y")){
writeBoard(board, boardSize);
console.println("Saved!");
}
} while (!gameOver(board, boardSize));
displayGameBoard(board, boardSize);
humanPlayerScore = getPlayerScore(board, boardSize, 'H');
computerPlayerScore = getPlayerScore(board, boardSize, 'C');
if (humanPlayerScore > computerPlayerScore) {
console.println("Well done, " + playerName + ", you have won the game!");
}
else {
if (humanPlayerScore == computerPlayerScore) {
console.println("that was a draw!");
} else {
console.println("The computer has won the game!");
}
console.println();
}
}
void writeBoard(char[][] board, int boardSize) {
String filename = "myFile.txt";
String piece = null;
writeFile.openFile(filename);
for(int row=1; row<=boardSize; row++){
for (int column = 1; column <= boardSize; column++) {
piece= Character.toString(board [row][column]);
writeFile.writeToTextFile(piece);
}
}
writeFile.closeFile();
}
public static void main(String[] args) {
new Aaa();
}
}
This Section contains the errors:
void writeBoard(char[][] board, int boardSize) {
String filename = "myFile.txt";
String piece = null;
writeFile.openFile(filename);
for(int row=1; row<=boardSize; row++){
for (int column = 1; column <= boardSize; column++) {
piece= Character.toString(board [row][column]);
writeFile.writeToTextFile(piece);
}
}
writeFile.closeFile();
}
The problematic section contains a variable named writeFile which can not be resolved. No where in the class Aaa that you have shared, neither this variable has been declared nor initialized with an instance of its type. So the method void writeBoard(char[][] board, int boardSize) gives compilation error.
From the usage of this variable it is clear that it belongs to a class which has following instance methods:
1) openFile(String filename)
2) writeToTextFile(String piece)
3) closeFile()
Please search the class which has the above methods and on finding create an instance of that as the first statement inside the method void writeBoard(char[][] board, int boardSize). Hope it helps.
I get to do a vertically merged using this function:
private static void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {
for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
if ( rowIndex == fromRow ) {
// The first merged cell is set with RESTART merge value
cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
} else {
// Cells which join (merge) the first one, are set with CONTINUE
cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
}
}
}
but I can't do the horizontal merge with similar function:
private static void mergeCellsHorizontally(XWPFTable table, int col, int fromCol, int toCol) {
for (int colIndex = fromCol; colIndex <= toCol; colIndex++) {
XWPFTableCell cell = table.getRow(0).getCell(colIndex);
if ( colIndex == fromCol ) {
// The first merged cell is set with RESTART merge value
cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
cell.setText("hola");
} else {
// Cells which join (merge) the first one, are set with CONTINUE
cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
cell.setText("adios");
}
}
}
Thanks!
The solution is:
setCellSpan(row.getCell(2), 5);
CTRow ctRow = row.getCtRow();
CTTc[] ctTcs = new CTTc[4]; // las colunas que quedan
for(int y = 0; y < ctRow.sizeOfTcArray(); y++) {
if(y != 4 && y != 5 && y != 6 && y != 7){ //Las columnas que desaparecen
ctTcs[y] = ctRow.getTcArray(y);
} }ctRow.setTcArray(ctTcs);
where:
public static void setCellSpan(XWPFTableCell cell, int span) {
if (cell.getCTTc().getTcPr() == null) {
cell.getCTTc().addNewTcPr();
}
if (cell.getCTTc().getTcPr().getGridSpan() == null) {
cell.getCTTc().getTcPr().addNewGridSpan();
}
cell.getCTTc().getTcPr().getGridSpan().setVal(BigInteger.valueOf((long) span));
}
I have attempted to complete my homework project and am seeking help finding a bug. I am using a backtracking algorithm to find all the solutions to an N-queens problem. My main concern is my conflict method-which is inside a stack class. Its purpose is to detect if the Queen object (parameter 1 of conflict method) being passed is in the same row, column, or diagonal as any other queens on the board. The queen object passed into the conflict method is stored inside the Queen class and its location is recorded with the help of an instance of the Point class. My code uses two methods in the Queen class that I created, public int getRow(), and public int getColumn(). Both return an int. Second parameter is a 2d array (or array of arrays) named board. Queens already on the board are denoted in this array with a boolean value of true. Boolean values of false indicate an empty square on the board.
Solution.n is a reference to a static int variable in another class. Its value denotes the edge of the board. Example...for the 8-Queens problem we create a 2d array with size 8. Solution.n is decremented by 1 to equal the last index of the 2d array.
Here is the code:
public boolean conflict(Queen x, boolean [][] board) //conflict method
{
if(checkColumn(x, board) == false)
return true; //conflict
else if(checkRow(x, board) == false)
return true; //conflict
else if(checkDiagonal(x, board) == false )
return true; //conflict
else
return false; //no conflict on board
}
private boolean checkColumn(Queen x, boolean [][] board)//returns true when column is safe
{
int col = x.getColumn();
for(int row = 0; row <= Solution.n; row++)
{
if(board[row][col] == true) //queen is in this column
{
return false;
}
}
return true;
}
private boolean checkRow(Queen x, boolean [][] board) //returns true when row is safe
{
int row = x.getRow();
for(int col = 0; col <= Solution.n; col++)
{
if(board[row][col] == true) //queen is in this row
{
return false;
}
}
return true;
}
private boolean checkDiagonal(Queen location, boolean [][] board) //returns true when diagonal is safe
{
int row, col;
row = location.getRow() - 1;
col = location.getColumn() - 1;
while(row >=0 && col >= 0) //iterate down-left
{
if(board[row][col] == true) //queen found?
{
return false;
}
row--;
col--;
}
row = location.getRow() - 1;
col = location.getColumn() + 1;
while(row != -1 && col <= Solution.n) //iterate down-right
{
if(board[row][col] == true) //queen found?
{
return false;
}
row--;
col++;
}
row = location.getRow() + 1;
col = location.getColumn() + 1;
while(row <= Solution.n && col <= Solution.n) //iterate up-right
{
if(board[row][col] == true) //queen found?
{
return false;
}
row++;
col++;
}
row = location.getRow() +1;
col = location.getColumn()-1;
while(row <= Solution.n && col != -1) //iterate up-left
{
if(board[row][col] == true) //queen found?
{
return false;
}
row++;
col--;
}
return true;
}
I am convinced this snippet of code contains a bug, but if i'm wrong then I apologize for wasting your time :P
Your help would be greatly appreciated. Thanks! :D
You have several small bugs in there - for example, you have loops that go from 0 to Solution.n, inclusive, while they should go to Solution.n-1. Most of the errors, however, can be eliminated by picking a more suitable data structure.
Think about it: you don't need a full NxN board to decide the placement of a queen:
There's one queen per row, so queen's number is its row.
There's one queen per column, so you need an array of boolean[N] to know which rows are taken.
There's one queen per ascending diagonal, so you need an array of boolean[2N-1] to know which ascending diagonals are taken.
There's one queen per descending diagonal, so you need an array of boolean[2N-1] to know which descending diagonals are taken.
boolean[] columns = new boolean[N];
boolean[] ascending = new boolean[2*N-1];
boolean[] descending = new boolean[2*N-1];
At this point you've got all you need: instead of a square boolean[N][N] array you need three linear arrays of boolean. This lets you do your checks much faster, too:
int c = x.getColumn();
int r = x.getRow();
boolean conflict = columns[c]
|| ascending[r+c]
|| descending[N-r+c];
That's it - no loops required! Now you can code your backtracking algorithm using these three arrays instead of a square board.
This answer won't solve your problem, since I'm not convinced your error is in the code you pasted, but here's your code, written a bit closer to how I might write it:
// returns true when column is safe
private boolean checkColumn(Queen x, boolean [][] board)
{
int col = x.getColumn();
for(int row = 0; row <= Solution.n; row++)
{
if(board[row][col]){ return false; }
}
return true;
}
// returns true when row is safe
private boolean checkRow(Queen x, boolean [][] board)
{
int row = x.getRow();
for(int col = 0; col <= Solution.n; col++)
{
if(board[row][col]){ return false; }
}
return true;
}
// returns true if the position is valid given the board size
// (as defined by Solution)
private boolean validPosition(int row, int col)
{
if(0 > row || row > Solution.n){ return false; }
if(0 > col || col > Solution.n){ return false; }
return true;
}
// returns true when diagonal is safe
private boolean checkDiagonal(Queen x, boolean [][] board)
{
int row, col;
// Down Left
row = x.getRow(); // "Start" on current position
col = x.getColumn();
while(true)
{
row--; col--; // Take a step in the direction
if(!validPosition(row, col)){ break; } // Stop if we've left the board
if(board[row][col]){ return false; } // Check whether it's occupied
}
// Down Right
row = x.getRow();
col = x.getColumn();
while(true)
{
row--; col++;
if(!validPosition(row, col)){ break; }
if(board[row][col]){ return false; }
}
// Up Right
row = x.getRow();
col = x.getColumn();
while(true)
{
row++; col++;
if(!validPosition(row, col)){ break; }
if(board[row][col]){ return false; }
}
// Up Left
row = x.getRow();
col = x.getColumn();
while(true)
{
row++; col--;
if(!validPosition(row, col)){ break; }
if(board[row][col]){ return false; }
}
return true;
}
public boolean conflict(Queen x, boolean [][] board) //conflict method
{
if ( checkColumn(x, board) == false){ return true; }
else if( checkRow(x, board) == false){ return true; }
else if(checkDiagonal(x, board) == false){ return true; }
else { return false; }
}
}
It simplifies a lot of the logic, adds a helper function validPosition(), and cleans up some of the tests and loops.
I'm browsing through some sudoku solvers and I'm looking for one that utilizes backtracking, now I've found this code but I'm not really sure whether it uses backtracking or some other algorithm?
Help is appreciated.
abstract class SudoKiller {
private SudokuBoard sb; // Puzzle to solve;
public SudoKiller(SudokuBoard sb) {
this.sb = sb;
}
private boolean check(int num, int row, int col) {
int r = (row / sb.box_size) * sb.box_size;
int c = (col / sb.box_size) * sb.box_size;
for (int i = 0; i < sb.size; i++) {
if (sb.getCell(row, i) == num ||
sb.getCell(i, col) == num ||
sb.getCell(r + (i % sb.box_size), c + (i / sb.box_size)) == num) {
return false;
}
}
return true;
}
public boolean guess(int row, int col) {
int nextCol = (col + 1) % sb.size;
int nextRow = (nextCol == 0) ? row + 1 : row;
try {
if (sb.getCell(row, col) != sb.EMPTY)
return guess(nextRow, nextCol);
}
catch (ArrayIndexOutOfBoundsException e) {
return true;
}
for (int i = 1; i <= sb.size; i++) {
if (check(i, row, col)) {
sb.setCell(i, row, col);
if (guess(nextRow, nextCol)) {
return true;
}
}
}
sb.setCell(sb.EMPTY, row, col);
return false;
}
}
And if this is not backtracking, is there an easy way to "convert" to it?
The whole project can be found on the authors site.
Looks like it does backtracking via recursion.
Here we step forward:
sb.setCell(i, row, col);
and here we step backward:
sb.setCell(sb.EMPTY, row, col);