How do you move through a 2D array without for loops? - java

I am trying to build a treasure hunt game using test files I have been given. These texts files are of chars S,W,E,N and T which all correspond to directions except for T, which is the treasure. Everything works fine until it moves the length of the rows/columns. I suspect it has something to do with the for loops but I'm not certain. Is there a way to do this without for loops or does anyone have any advice to get this back on track?
Here is my Updated code so far:
import java.util.*;
public class NewGridGame {
public static final int FALL_OFF = -1;
public static final int GOING_IN_CIRCLES = -2;
private int row;
private int col;
private char[][] gameBoard;
NewGridGame(int conRow, int conCol, char[][] conGameBoard) {
row = conRow;
col = conCol;
gameBoard = new char[row][col];
for (int i = 0; i < gameBoard.length; i++) {
for (int j = 0; j < gameBoard[i].length; j++) {
gameBoard[i][j] = conGameBoard[i][j];
}
}
System.out.println(Arrays.deepToString(gameBoard));
}
public int playGame() {
boolean[][] beenHereBefore = new boolean[row][col];
int turns = 0;
int i = 0;
int j = 0;
while (true) {
if (beenHereBefore[i][j] == true) {
return GOING_IN_CIRCLES;
} else {
beenHereBefore[i][j] = true;
}
if (gameBoard[i][j] == 'N') {
if (i - 1 >= 0) {
i--;
turns++;
System.out.println(turns);
System.out.println(gameBoard[i][j]);
} else {
return FALL_OFF;
}
} else if (gameBoard[i][j] == 'S') {
if (i + 1 < row) {
i++;
turns++;
System.out.println(turns);
System.out.println(gameBoard[i][j]);
} else {
return FALL_OFF;
}
} else if (gameBoard[i][j] == 'E') {
if (j + 1 < col) {
j++;
turns++;
System.out.println(turns);
System.out.println(gameBoard[i][j]);
} else {
return FALL_OFF;
}
} else if (gameBoard[i][j] == 'W') {
if (j - 1 >= 0) {
j--;
turns++;
System.out.println(turns);
System.out.println(gameBoard[i][j]);
} else {
return FALL_OFF;
}
} else if (gameBoard[i][j] == 'T') {
return turns;
}
}
}
}
Here is an example of a test file as well.
ES
TW
this one should return 3, which is the number of moves (turns, in my code) but instead it gets to W (which takes 2 moves) and returns -2, which is only for when it's gone to a position more than once. Additionally, not all of the Arrays are squares, some are 1x200 or 4x5 for examples.

If you know that the board is such that, starting at (0, 0), you won't get stuck in a loop or move off the board you can just used something like this:
public int playGame()
{
int numMoves = 0;
int currentRow = 0;
int currentCol = 0;
while(gameBoard[currentRow][currentCol] != 'T')
{
switch (gameBoard[currentRow][currentCol])
{
case 'E': currentCol++; break;
case 'W': currentCol--; break;
case 'S': currentRow--; break;
case 'N': currentRow++; break;
default:
throw new IllegalStateException("Unrecognized Move");
}
numMoves++;
}
return numMoves;
}
You may want to use if-then-else instead of a switch.
If you need to check for loops or off-board moves you should be able to add these checks in.

Related

Java terminal game

I am trying to create a game in a terminal for a school assignment. No pop out windows or anything. The problem is a bug in the game itself. the 'x' should move until it hits the wall, but it gets stuck inside the wall. I am only learning java and also any tips for future posts or programming are appreciated.
import java.util.Scanner;
public class App {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
int coordx = 1;
int coordy = 1;
while (true) {
// System.out.println("Move: ");
String move = input.nextLine();
switch (move) {
case "a":
while (!wall(coordy - 1, coordx)) {
coordx--;
}
break;
case "w":
while (!wall(coordy, coordx - 1)) {
coordy--;
}
break;
case "d":
while (!wall(coordy + 1, coordx)) {
coordx++;
}
break;
case "s":
while (!wall(coordy, coordx + 1)) {
coordy++;
}
break;
default:
break;
}
render(coordx, coordy);
}
}
public static void render(int chary, int charx) {
int[][] grid = new int[9][40];
for (int i = 0; i < 9; i++) {
System.out.print("\n");
for (int j = 0; j < 40; j++) {
if (i == charx && j == chary) {
grid[i][j] = 0;
System.out.print("x");
} else if (wall(i, j)) {
grid[i][j] = 2;
System.out.print("#");
} else {
grid[i][j] = 1;
System.out.print(" ");
}
}
}
}
public static boolean wall(int coordy, int coordx) {
if (coordx == 0 || coordx == 39 || coordy == 0 || coordy == 8) {
return true;
} else {
return false;
}
// return true;
}
}
I like little games like this very much and it's great to help somebody like you early on in their adventure threw programming.
I think you have some of the while contidions mixed up. For Example:
case "a":
while (!wall(coordy - 1, coordx)) {
coordx--;
As far as I understand your game it should be:
case "a":
while (!wall(coordy, coordx - 1)) {
coordx--;
Check the other conditions in your gameloob too.

Checking adjacent tiles in 2-dimensional array

So i'm trying to make a game of Connect Four in Java, instead I'm connecting 6 instead of 4.
I have a 2-dimensional array and X amount of players. I have to check if 6 blocks in succession (horizontal, vertical and diagonal) are marked by the same player. If they are, the program should print who won.
Now, I don't have problems with the checking or determining who won, though for the life of me I can't figure out how to prevent the program from crashing whenever it tries to check for a block that's outside the array.
Now, I'm trying to avoid using try-catch or plopping 8 loops one after the other, and instead use one method for all of the directions with just variation in the parameters but I can't seem to make it work :\
Does anyone have a suggestion on how this might work?
I'm a beginner in programming and I've possibly missed something so that's why I'm asking for help :)
Cheers
Edit: here's the code. It's a bit long, that's why i want to shorten it and make it work somehow. the Terminal class is the same as the System.out.println one.
void checkIfPlayerWins(Field field, Integer rowNumber, Integer colNumber) {
Integer counter = 1;
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber, colNumber + i)) {
counter++;
} else {
break;
}
}
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber - i, colNumber + i)) {
counter++;
} else {
break;
}
}
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber - i, colNumber)) {
counter++;
} else {
break;
}
}
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber - i, colNumber - i)) {
counter++;
} else {
break;
}
}
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber, colNumber - i)) {
counter++;
} else {
break;
}
}
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber + i, colNumber - i)) {
counter++;
} else {
break;
}
}
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber + i, colNumber)) {
counter++;
} else {
break;
}
}
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber + i, colNumber + i)) {
counter++;
} else {
break;
}
}
if (counter == 6) {
Terminal.printLine("");
}
}
here's the isOccupied method
boolean isOccupied(Integer x, Integer y) {
return !this.field[x][y].equals("**");
}
You could simply handle the case where you're attempting to check whether the Field is occupied at invalid coordinates in your isOccupied method:
boolean isOccupied(Integer x, Integer y) {
if(x < 0 || y < 0 || x >= numberOfColumns || y >= numberOfRows) {
// Attempting to check outside the grid: it's non-occupied.
return false;
}
return !this.field[x][y].equals("**");
}

five hand card game and couldn't figure out, badugi & four of a kind

am trying to find four of a kind in a five-card poker hand. but it's not working and couldn't figure out why.
public boolean hasFourOfaKind(String hand) {
int counter = 0;
char x = 0;
for (int i = 0; i < hand.length(); i++)
{
if (i == 0) {
x = hand.charAt(0);
} else if (x == hand.charAt(i)) {
counter++;
}
}
if (counter >= 4) {
return true;
} else {
return false;
}
}
the same problem here am trying to check whether the given four-card hand is a badugi
public boolean hasFourCardBadugi(String hand) {
int diffcounter = 0;
char badugi = 0;
for (int i = 0; i < hand.length(); i++) {
if (i == 0) {
badugi = hand.charAt(0);
} else if (badugi != hand.charAt(i)) {
diffcounter++;
}
}
if (diffcounter >= 10) {
return true;
} else {
return false;
}
}
Let's look at your for loop.
for (int i = 0; i < hand.length(); i++)
{
if (i == 0) {
x = hand.charAt(0);
} else if (x == hand.charAt(i)) {
counter++;
}
}
In this part
if (i == 0) {
x = hand.charAt(0);
}
You set x to the first card. But you never count that card. You need to add:
if (i == 0) {
x = hand.charAt(0);
counter++;
}
Of course this still has the issue that it will not detect hands where the four of a kind does not match the first card (ace two two two two), but you should be able to work that out now that the basic bug is fixed. One way to do it would just involve a second loop.

TicTacToe Problems

I am stuck on my tictactoe problem. Define a calss called TicTacToe. An object of type TicTacToe is a single game of TicTacToe. Store the game board as a single 2d array of base type char that has three rows and three columns. Include methods to add a move, display the board, to tell whose turn it is, to tell whether there is a winnner, to say who the winner is, and to restart the game to the beginning. Write a main method for the class that will allow two players to enter their moves in turn at the same keyboard.
I have some of my methods written and have been testing as I go. When I test my code I either get it to place a mark but also print out invalid entry or it will continuously loop through asking for a move and then saying the space is occupied. I can't figure out how to fix that. I'm sure it has something to do with my do while loop and the boolean methods for isEmpty and notValid. Also I'm stuck on how to implement a counter for each player's win.
Here is my code:
public void addMove()
{
checkTurn();
int row, col;
do
{
System.out.println("Enter a row (1-3): ");
row = in.nextInt() - 1; //Array index starts at 0.
System.out.println("Enter a column (1-3): ");
col = in.nextInt() - 1;
if (row>=0 && row<ROWS)
if(col>=0 && col<COLUMNS)
if (playerX)
{
gameBoard[row][col] = player1Move;
}
else
{
gameBoard[row][col] = player2Move;
}
checkForWin();
changePlayer();
}while (notValid(row,col));
System.out.println("Invaild Entry.");
//System.exit(0);
//checkForWin();
//changePlayer();
}
public boolean notValid(int row, int col)
{
if (row < 0 || row > ROWS )
return true;
if (col < 0 || col > COLUMNS)
return true;
if (!isEmpty(row,col))
return true;
return false;
}
public boolean isEmpty(int row, int col)
{
if(gameBoard[row][col]==' ')
return true;
else
{
System.out.println("Space is already occupied.");
return false;
}
}
}
Here is my testing class:
public class TicTacToe
{
public static void main(String[] args)
{
TicTacToeClass game = new TicTacToeClass();
game.addMove();
game.printBoard();
}
}
I will let you handle the multiple game part. This plays one game and exits.
import java.util.Scanner;
public class TicTacToe
{
private final static int ROWS = 3;
private final static int COLUMNS = 3;
private char[][] gameBoard;
private int player1WinCount = 0;
private int player2WinCount = 0;
private char player1Move = 'X', player2Move = 'O';
private boolean playerX = true;
Scanner in = new Scanner(System.in);
public TicTacToe()
{
gameBoard = new char [ROWS][COLUMNS];
playerX = true;
startGame();
}
//Initiate the game board with all empty spaces.
public void startGame()
{
for (int row = 0; row < ROWS; row++) //Loop through rows.
for(int col = 0; col < COLUMNS; col++) //Loop through columns.
gameBoard[row][col]= ' ';
}
public boolean checkTurn()
{
if (playerX)
{
System.out.println("Player X's turn.");
}
else
{
System.out.println("Player O's turn.");
}
return playerX;
}
public void addMove()
{
int row, col;
do
{
checkTurn();
System.out.println("Enter a row (1-3): ");
row = in.nextInt() - 1; //Array index starts at 0.
System.out.println("Enter a column (1-3): ");
col = in.nextInt() - 1;
if(notValid(row,col)){
// do not proceed
System.out.println("Invalid Entry.");
continue;
}
if (row>=0 && row<ROWS)
if(col>=0 && col<COLUMNS)
if (playerX)
{
gameBoard[row][col] = player1Move;
}
else
{
gameBoard[row][col] = player2Move;
}
boolean hasWon = checkForWin();
if(hasWon)
{
System.out.println("You won");
if(playerX)
{
player1WinCount++;
}
else
{
player2WinCount++;
}
break;
}
changePlayer();
}while (true);
}
public boolean notValid(int row, int col)
{
if (row < 0 || row > (ROWS - 1))
return true;
if (col < 0 || col > (COLUMNS - 1))
return true;
if (!isEmpty(row,col))
return true;
return false;
}
public boolean isEmpty(int row, int col)
{
if(gameBoard[row][col]==' ')
return true;
else
{
System.out.println("Space is already occupied.");
return false;
}
}
public void changePlayer()
{
if (playerX)
{
playerX = false;
}
else
{
playerX = true;
}
}
public void printBoard()
{
for (int row = 0; row < ROWS; row++){
for (int col = 0; col < COLUMNS; col++)
{
System.out.print("" + gameBoard[row][col]);
if(col == 0 || col == 1)
System.out.print("|");
}
if (row ==0 || row ==1)
System.out.print("\n-----\n");
}
}
/**
* This method checks to see if a winner.
* return true is there is a winner.
*/
public boolean checkForWin()
{
//checks rows for win
for(int row = 0; row < ROWS; row ++)
{
if (gameBoard[row][0] == gameBoard[row][1] && gameBoard[row][1]==gameBoard[row][2] && gameBoard[row][0]!= ' ')
return true;
}
//checks columns for wins.
for (int col = 0; col < COLUMNS; col++)
{
if (gameBoard[0][col] == gameBoard[1][col]&& gameBoard[1][col]==gameBoard[2][col] && gameBoard[0][col]!= ' ')
return true;
}
//check the diagonals for wins.
if (gameBoard[0][0] == gameBoard[1][1] && gameBoard[1][1] == gameBoard[2][2] && gameBoard[0][0]!= ' ')
return true;
if (gameBoard[2][0] == gameBoard[1][1] && gameBoard[1][1] == gameBoard[0][2] && gameBoard[0][2]!= ' ')
return true;
return false;
}
public static void main(String args[])
{
TicTacToe game = new TicTacToe();
game.addMove();
game.printBoard();
}
}

Java Tic-Tac-Toe, prints 3 boards

I'm having a setback in the code for a Tic Tac Toe Java program. Every time I run it, the game board prints 3 times and o the second time, the X's all fill in a line saying that player X wins. I've been trying to figure it out, but I still can't find the problem going on with it. What I'm asking is, what is the main problem of the code printing out more than it needs to and to stop filling in the lines?
I hope I format this correctly.
import java.util.Scanner;
public class TicTacToeWork {
//Variable declaration.
public static char[][] GameBoard = new char[3][3];
public static Scanner keyboard = new Scanner(System.in);
public static int column, row;
public static char PlayerTurn = 'X';
public static void main(String args[]) {
for (int i = 0; i > 3; i++) {
for (int j = 0; j < 3; j++) {
GameBoard[i][j] = '_';
}
}
System.out.println("Enter coordinates of row then column to choose your space.");
Playing();
}
public static void Playing() {
boolean PlayerPlaying = true;
while (PlayerPlaying) {
boolean playing = true;
while (playing) {
row = keyboard.nextInt() - 1;
column = keyboard.nextInt() - 1;
GameBoard[row][column] = PlayerTurn;
if (EndGame(row, column)) {
playing = false;
System.out.println("Game over player " + PlayerTurn + " wins!");
}
BoardPrint();
if (PlayerTurn == 'X') {
PlayerTurn = 'O';
} else {
PlayerTurn = 'X';
}
}
}
}
public static void BoardPrint() {
//Print out the game board.
for (int i = 0; i < GameBoard.length; i++) {
for (int n = 0; n < 3; n++) {
System.out.println();
for (int j = 0; j < 3; j++) {
if (j == 0) {
System.out.print("| ");
}
System.out.print(GameBoard[i][j] + " | ");
}
}
System.out.println();
}
System.out.println();
}
public static boolean EndGame(int RowMove, int ColumnMove) {
//Deciding factors on who wins and ties.
if (GameBoard[0][ColumnMove] == GameBoard[1][ColumnMove]
&& GameBoard[1][ColumnMove] == GameBoard[2][ColumnMove]) {
return true;
}
if (GameBoard[RowMove][0] == GameBoard[1][RowMove]
&& GameBoard[RowMove][0] == GameBoard[RowMove][2]) {
return true;
}
if (GameBoard[0][0] == GameBoard[1][1] && GameBoard[0][0] == GameBoard[2][2]
&& GameBoard[1][1] != '_') {
return true;
}
if (GameBoard[0][2] == GameBoard[1][1] && GameBoard[0][2] == GameBoard[2][0]
&& GameBoard[1][1] != '_') {
return true;
} else {
return false;
}
}
}
Your BoardPrint method is all wrong. You have to do something like this..
public static void BoardPrint() {
System.out.println("-------------");
for (int i = 0; i < 3; i++) {
System.out.print("| ");
for (int j = 0; j < 3; j++) {
System.out.print(GameBoard[i][j] + " | ");
}
System.out.println();
System.out.println("-------------");
}
You are also going to have to redo your check for a win.
A little hint.. you are not using a Boolean method correctly. This line if(EndGame(row, column)) is saying if EndGame is true stop the game. The way you have your method set up it is not doing the check correctly. You would have to say "if not true" - so it would look like this if(!EndGame(row, column)) There are a couple of other errors but this should give you a good start on completing the project.

Categories

Resources