Java Help - Making a 'sweeper' game - java

Our assignment is to make a simple 'pac-man' game that just eats the trash inside a rectangle. The trash being "*".
My code so far:
public class Sweeper
{
public static void main(String[] args) throws InterruptedException
{
//************************************************************
// Variable set up
int sy = 10, sx= 10; // Box size
int x= 5, y= 5; // Start point
int maxmc = 8; // Max distance moving
char [] [] env = new char[sy][sx];
int right = sx - 2, top = sy - 2, left = sx - (right + 1) , bottom = sy - (top + 1);
//************************************************************
//************************************************************
// Filling the grid with Stars
for(int i=0; i<sy;i++)
{
for(int j =0; j < sx; j++)
{
env[i][j] = '*';
}
}
//************************************************************
int mc = 0, direction = 0, count = (right * top);
// The actual game
while(count != 0)
{
direction = (int)(Math.random() * 3);
// Display
//System.out.println("\n\n\n\n\n");
for(int i = 0; i < sy; i++)
{
for(int j= 0; j< sx; j++)
{
System.out.print(env[i][j]);
}
System.out.println();
}
System.out.println("\n\n\n");
Thread.sleep(700);
System.out.println(direction);
if((x <= right && x >= left && y <= top && y >= bottom))
{
if(env[x][y] == ' ')
{
// RIGHT
if(direction == 0)
{
env[y][x] = '#';
x--;
env[y][x+2] = ' ';
}
// left
else if(direction == 1)
{
env[y][x] = '#';
x++;
env[y][x-2] = ' ';
}
// TOP
else if(direction ==2)
{
env[y][x] = '#';
y--;
env[y+2][x] = ' ';
}
// bottom
else if(direction ==3)
{
env[y][x] = '#';
y++;
env[y-2][x] = ' ';
}
}
else
{
if(direction == 0)
{
env[y][x] = '#';
x--;
env[y][x+2] = ' ';
}
// left
else if(direction == 1)
{
env[y][x] = '#';
x++;
env[y][x-2] = ' ';
}
// TOP
else if(direction ==2)
{
env[y][x] = '#';
y--;
env[y+2][x] = ' ';
}
// bottom
else if(direction ==3)
{
env[y][x] = '#';
y++;
env[y-2][x] = ' ';
}
// Keeps track of the trash
count--;
}
}
}
}
}
My problem:
It copies the '#' and stops moving sometimes.
Im trying to make it move aorund until all the inside 8x8 star symbols are all gone.

Just to clean your code: your moving algorithm is duplicated the (4 if/else statements) . You need to put only count-- in a if(! env[x][y] == ' ') statement.
For your problem: your badly checkin your bounds condition, you do
env[y][x] = '#';
x--;
env[y][x+2] = ' ';
But if x=1, then after the code it's 0, and because you have
if((x <= right && x >= left && y <= top && y >= bottom))
With x=0 and right=0, then it never enter the statement, count cannot change, and it loops infinetly.

Related

Check if a char is in a 2D array in java

I have been working on my homework of creating a simple chess program.
The chessboard is a 2D array, named board. The pieces are all single chars like R,Q,K, and empty space is filled with a ' ' char, so a space.
public static char[][] board;
The method get should return the char or whatever is there on the coordinate (x,y).
public char get(int x, int y) {
if(x < board[0].length && x >= 0 && y < board.length && y >= 0){
return board[x][y];
}
else
return '\0';
}
And the problem is that my program of evaluating who is the winner is not working as expected.
This program checks whether the king of each team is still in the chessboard, so the board array.
It should return 0 if both are still alive, 1, if only the white king is alive, and 2 if only the black king is alive.
I have made a program, or at least tried to make one, that goes through each coordinate and checks if there is a character 'K', which represents the white king, and 'S', the black king.
I have set the boolean kingIsAlive to false, so that if there is no K or S found in the array, it remains false.
Though, my code at the bottom, with the if and else that returns 0,1 or2, has the error, that kingWhiteIsAlive is always false and kingBlackIsAlive is always false.
So, I think my program of turning the kingIsAlive boolean to true is not working at all....
The errors I got is:
White should have won => expected: <1> but was: <-1>
No one should have won => expected: <0> but was: <1>
And after a couple of hours trying, I gave up and decided to ask here.
public int decideWinner(){
boolean kingWhiteIsAlive = false;
boolean kingBlackIsAlive = false;
for(int y = 0; y < board.length;y++){
for(int x = 0;x < board[0].length;x++){
if(get(x,y) == 'K'){
kingWhiteIsAlive = true;
}
}
}
for(int j = 0; j < board.length;j++){
for(int i = 0;i < board[0].length;i++){
if(get(i,j) == 'S'){
kingBlackIsAlive = true;
}
}
}
if(kingWhiteIsAlive && kingBlackIsAlive){
return 0;
}
else if(kingWhiteIsAlive && !kingBlackIsAlive){
return 1;
}
else if(!kingWhiteIsAlive && kingBlackIsAlive){
return 2;
}
else
return -1;
}
return -1 is for a test case that there are no kings from both teams.
I've tested your code & it's running perfectly, perhaps the problem is in your board initialization?
Try to debug your code by showing the actual content of the array at the beginning of decideWinner function.
I've used this initialization for the board, if it might help.
public void initBoard() {
board = new char[8][8];
// Init pawns
for (int j = 0; j < board.length; j++) {
board[j][1] = 'P';
board[j][6] = 'P';
}
// Rooks
board[0][0] = 'R';
board[7][0] = 'R';
board[0][7] = 'R';
board[7][7] = 'R';
// Knights
board[1][0] = 'N';
board[6][0] = 'N';
board[1][7] = 'N';
board[6][7] = 'N';
// Bishops
board[2][0] = 'B';
board[5][0] = 'B';
board[2][7] = 'B';
board[5][7] = 'B';
// Queens
board[3][0] = 'Q';
board[4][7] = 'Q';
// Kings
board[4][0] = 'K'; // White
board[3][7] = 'S'; // Black
// Empty space
for (int y = 0; y < board.length; y++) {
for (int x = 2; x < 6; x++) {
board[y][x] = ' ';
}
}
}
If you find a king, you need to interrupt your search. You can do it by a break statement.
for(int y = 0; y < board.length;y++){
for(int x = 0;x < board[0].length;x++){
if(get(x,y) == 'K'){
kingWhiteIsAlive = true;
break;
}
}
}
for(int j = 0; j < board.length;j++){
for(int i = 0;i < board[0].length;i++){
if(get(i,j) == 'S'){
kingBlackIsAlive = true;
break;
}
}
}

How to fix "Index 5 out of bounds for length 5" error in Java

I am working on solution for the CCC 2018 Robo Thieves Problem, it a simplified version of the original problem. My problem is that it will give me this "Index 5 out of bounds for length 5" when I executed my code and I'm not sure why it is happening. Half of my program executes and then this error occurs.
import java.util.*;
public class RoboThieves {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> rowPos = new ArrayList<Integer>();
ArrayList<Integer> colPos = new ArrayList<Integer>();
int sRow = -1; // robot pos
int sCol = -1;
int dotCounter = 0;
int stepCounter = 0;
int rowSize = sc.nextInt();
int colSize = sc.nextInt();
char[][] factoryGrid = new char[rowSize][colSize];
for (int i = 0; i < rowSize; i++) {
String rowChars = sc.next().toUpperCase();
for (int j = 0; j < colSize; j++) {
factoryGrid[i][j] = rowChars.charAt(j);
}
}
// check to see if the grid was inputted properly (with square brackets)
/*
* for (char [] row: factoryGrid) { System.out.println(Arrays.toString(row)); }
*/
// check to see if the grid was inputted properly (as inputted)
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++) {
System.out.print(factoryGrid[i][j]);
}
System.out.println();
}
// locate dots and store their row and col in arraylists
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++) {
if (factoryGrid[i][j] == '.') {
rowPos.add(i);
colPos.add(j);
dotCounter++;
}
}
}
// print dot location to check
for (int i = 0; i < rowPos.size(); i++) {
System.out.println("Dot Position = " + "(" + rowPos.get(i) + "," + colPos.get(i) + ")");
}
// locate robot position
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++) {
if (factoryGrid[i][j] == 'S')
sRow = i;
sCol = j;
}
}
// print camera location to check
System.out.println("Camera Position = " + "(" + sRow + "," + sCol + ")");
//System.out.println(dotCounter); // test to see if counter works
char above = getAbove(factoryGrid, sRow, sCol);
char right = getRight(factoryGrid, sRow, sCol);
char below = getBelow(factoryGrid, sRow, sCol);
char left = getLeft(factoryGrid, sRow, sCol);
if (above == '.') {
boolean canMove = check360(factoryGrid, sRow, sCol);
// check if camera is around dot
if (canMove == true) {
// set robot position to dot position and old position to W
sRow = sRow - 1;
// sCol = sCol;
factoryGrid[sRow][sCol] = 'W';
dotCounter--;
stepCounter++;
} else {
// this is if there is a camera in the 360 radius of the open space
System.out.println("You cannot move to the space beside because there is a camera in your sightline!");
}
} else if (right == '.') {
boolean canMove = check360(factoryGrid, sRow, sCol);
// check if camera is around dot
if (canMove == true) {
// set robot position to dot position and old position to W
// sRow = sRow;
sCol = sCol + 1;
factoryGrid[sRow][sCol] = 'W';
dotCounter--;
stepCounter++;
} else {
// this is if there is a camera in the 360 radius of the open space
System.out.println("You cannot move to the space beside because there is a camera in your sightline!");
}
} else if (below == '.') {
boolean canMove = check360(factoryGrid, sRow, sCol);
// check if camera is around dot
if (canMove == true) {
// set robot position to dot position and old position to W
sRow = sRow + 1;
// sCol = sCol;
factoryGrid[sRow][sCol] = 'W';
dotCounter--;
stepCounter++;
} else {
// this is if there is a camera in the 360 radius of the open space
System.out.println("You cannot move to the space beside because there is a camera in your sightline!");
}
} else if (left == '.') {
boolean canMove = check360(factoryGrid, sRow, sCol);
// check if camera is around dot
if (canMove == true) {
// set robot position to dot position and old position to W
// sRow = sRow;
sCol = sCol - 1;
factoryGrid[sRow][sCol] = 'W';
dotCounter--;
stepCounter++;
} else {
// this is if there is a camera in the 360 radius of the open space
System.out.println("You cannot move to the space beside because there is a camera in your sightline!");
}
} else {
System.out.println(
"The robot cannot move to any spaces try inputting a factory layout that can produce an answer.");
} // end if above dot (yes)
System.out.println(stepCounter);
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++) {
System.out.print(factoryGrid[i][j]);
}
System.out.println();
}
} // end main method
public static char getLeft(char[][] factGrid, int cRow, int cCol) {
return factGrid[cRow][(cCol - 1)];
}
public static char getAbove(char[][] factGrid, int cRow, int cCol) {
return factGrid[(cRow - 1)][(cCol)];
}
public static char getBelow(char[][] factGrid, int cRow, int cCol) {
return factGrid[cRow + 1][cCol];
}
public static char getRight(char[][] factGrid, int cRow, int cCol) {
return factGrid[cRow][(cCol + 1)];
}
public static boolean check360(char[][] factGrid, int cRow, int cCol) {
boolean canMove = true;
char left = getLeft(factGrid, cRow, cCol);
char above = getAbove(factGrid, cRow, cCol);
char right = getRight(factGrid, cRow, cCol);
char below = getBelow(factGrid, cRow, cCol);
if (left == 'C' || above == 'C' || right == 'C' || below == 'C') {
canMove = false;
}
return canMove;
}
} // end main program
Upon first look, I expect that the issue may lie in your getLeft(), getAbove(), getRight(), and getBelow() methods.
In these methods, you give it a value for cRow and cCol and add or subtract 1. However, you need to make sure that the index you are querying does not exceed the size of the double array factGrid, or go below 0.
For example, in your getRight() method, you might try:
public static char getRight(char[][] factGrid, int cRow, int cCol) {
if(factGrid[0].length > (cCol + 1)) {
return factGrid[cRow][(cCol + 1)];
} else {
return '';
}
}

Nested loop infinitely looping after random interval?

I am programming a connect 4 game using Java for an assignment. However, whenever player 2 makes a move about 5 moves in, the player 2 loop will infinitely loop. There is some sort of logic error that I cannot find, and it is frustrating. What is the logic error, and what is a good way to avoid future mistakes of the same vain?
I have tried changing the variables for the do > while loop where player 1 and player two attempt their moves. However that has no affect on it.
import java.util.Arrays;
public class Lab6Shell {
public static void main(String args[]) {
// variables
Scanner input = new Scanner(System.in);
char[][] board = new char[7][8];
boolean finished = false;
boolean gameOver = false;
int width = 7;
int height = 8;
char currentPlayer = 'X';
int numMoves = 0;
int bottom_row = width - 1;
// loop until user wants to stop
for (int row = 0; row < board.length; row++) {
java.util.Arrays.fill(board[row], 0, board[row].length, '*');
}
do {
// display the board
DisplayBoard(board);
// loop until this game is over
do {
// get the next move for the current player
int columnChosen = 0;
do {
if (currentPlayer == 'X') {
int counter = 1;
System.out.println("Player 1 turn");
System.out.println("Enter the column you want to place your piece.");
columnChosen = input.nextInt();
input.nextLine();
while (true) {
if (columnChosen > width) {
System.out.println("That's not a valid column");
break;
}
if ((board[bottom_row][columnChosen] == '*')) {
board[bottom_row][columnChosen] = 'X';
break;
} else if ((board[bottom_row][columnChosen] == 'X')
|| (board[bottom_row][columnChosen] == 'O')) {
if (board[bottom_row - counter][columnChosen] == '*') { // puts X if blank
board[bottom_row - counter][columnChosen] = 'X';
break;
}
counter += 1;
if (counter == width) {
System.out.println("That column is full");
break;
}
}
}
}
if (currentPlayer == 'O') {
int counter = 1;
System.out.println("Player 2's turn");
System.out.println("Enter the column you want to place your piece.");
columnChosen = input.nextInt();
input.nextLine();
while (true) {
if (columnChosen > width) {
System.out.println("That's not a valid column");
break;
}
if ((board[bottom_row][columnChosen] == '*')) {
board[bottom_row][columnChosen] = 'O';
break;
} else if ((board[bottom_row][columnChosen] == 'X')
|| (board[bottom_row][columnChosen] == 'O')) {
if (board[bottom_row - counter][columnChosen] == '*') { // puts O
board[bottom_row - counter][columnChosen] = 'O';
break;
}
counter += 1;
if (counter == width) {
System.out.println("That column is full");
break;
}
}
}
}
} while (columnChosen < 0 || columnChosen > 8 || board[1][columnChosen] != '*');
// place piece
// increment number of moves
numMoves++;
// display the board
DisplayBoard(board);
// check for win
if (checkWin(board)) {
// if winner, display congratulations and set gameOver true
System.out.println("Congratulations! You won!");
gameOver = true;
} else if (numMoves == 42) {
// if tie, display result and set gameOver true
DisplayBoard(board);
System.out.println("Tie Game! Game over");
gameOver = true;
} else if (checkWin(board) == false) {
if (currentPlayer == ('X')) {
currentPlayer = ('O');
} else {
currentPlayer = ('X');
}
}
} while (!gameOver);
// ask if user wants to play again, set finished accordingly
System.out.println("Would you like to play again?");
input.nextLine();
String decision = input.nextLine();
if (decision.toLowerCase().equals("yes")) {
finished = false;
}
else if (decision.toLowerCase().equals("no")) {
finished = true;
}
} while (finished == false);
}
// this method displays the board passed in
public static void DisplayBoard(char[][] board) {
for (int i = 0; i < board.length; i++) {
System.out.print("|");
for (int j = 0; j < board[i].length; j++) {
System.out.print(" " + board[i][j] + "|");
}
System.out.println("");
}
}
public static boolean checkWin(char[][] board) {
final int HEIGHT = board.length;
final int WIDTH = board[0].length;
final int EMPTY_SLOT = '*';
for (int r = 0; r < HEIGHT; r++) { // iterate rows, bottom to top
for (int c = 0; c < WIDTH; c++) { // iterate columns, left to right
char player = board[r][c];
if (player == EMPTY_SLOT)
continue; // don't check empty slots
if (c + 3 < WIDTH && player == board[r][c + 1] && // look right
player == board[r][c + 2] && player == board[r][c + 3])
return true;
if (r + 3 < HEIGHT) {
if (player == board[r + 1][c] && // look up
player == board[r + 2][c] && player == board[r + 3][c])
return true;
if (c + 3 < WIDTH && player == board[r + 1][c + 1] && // look up & right
player == board[r + 2][c + 2] && player == board[r + 3][c + 3])
return true;
if (c - 3 >= 0 && player == board[r + 1][c - 1] && // look up & left
player == board[r + 2][c - 2] && player == board[r + 3][c - 3])
return true;
}
}
}
return false; // no winner found
}
}
The expected result is that each player will play a piece until four of the same piece are in a row. Then the first to reach four in a row is declared the winner, and the game ends. However, once the game gets in about 5 loops, the player 2 loop infinitely loops until a column is full, and does not print out the board.
Your infinite loop is caused by checking the condition board[1][columnChosen] != '*' in your do ... while loop. The program will continue to ask the current user for a new move as long as the second to top row of the selected column is occupied.
Replace:
do
{
...
} while (columnChosen < 0 || columnChosen > 8 || board[1][columnChosen] != '*');
With:
do
{
...
} while (columnChosen < 0 || columnChosen > 8)
This should get you to a point where you can tackle the remaining issues.

Java: find in 2d array all adjacent elements with the same value, starting from a given element

I'm working on a program which contains a 2-dimensional 16x32 char array. What I want to do is, starting from a given element in this array, find all the elements that share the same value (in my case a blank space ' ') and that are horizontally and/or vertically linked to each other.
The method I'm using stores the indexes that it finds inside another array, called toShow (public static int toShow[][] = new int[30][30];). The problem is that this method does not seem to process towards the right side. Strangely enough, it seems to work on the other sides... Here's an example:
X1 123
31 1X
211 24
1X1 112X
111 12X34
111•2X32X
1X113X211
In this case, starting from the element marked as •, the method should store every ' ' character and all the neighbor numbers... but this is the result:
1••
1••
1•
1•
1•
1•
It does however usually work if it starts in the lower left corner, even though it does have to turn right!
I don't understand what's wrong with my code... Anyways here is the odd method:
public static void getEmptySurrounding(int xcoord, int ycoord) {
if (toShow[xcoord][ycoord] == 1) {
return;
}
else {
toShow[xcoord][ycoord] = 1;
}
//DOWN
if((ycoord!=29) && ycoord + 1 < 16) {
if (board[xcoord][ycoord] == ' ') {
getEmptySurrounding(xcoord, ycoord + 1);
}
}
//RIGHT
if((xcoord!=15) && xcoord + 1 < 30) {
if (board[xcoord][ycoord] == ' ') {
getEmptySurrounding(xcoord + 1, ycoord);
}
}
//UP
if((ycoord!=0) && ycoord - 1 >= 0) {
if (board[xcoord][ycoord] == ' ') {
getEmptySurrounding(xcoord, ycoord - 1);
}
}
//LEFT
if((xcoord!=0) && xcoord - 1 >= 0) {
if (board[xcoord][ycoord] == ' ') {
getEmptySurrounding(xcoord - 1, ycoord);
}
}
}
Thank you!
Based on the information you provided I made an application to test your method:
public class Mine {
private static char board[][] = new char[16][32];
private static int toShow[][] = new int[30][30];
public static void main(String[] args) {
int n = 0;
insert(n++, "X1 123");
insert(n++, "31 1X");
insert(n++, "211 24");
insert(n++, "1X1 112X");
insert(n++, "111 12X34");
insert(n++, "111 2X32X");
insert(n++, "1X113X211");
getEmptySurrounding(3, 5);
for (int i = 0; i < 30; i++) {
for (int j = 0; j < 30; j++) {
System.out.print(toShow[j][i]);
}
System.out.println();
}
}
public static void getEmptySurrounding(int xcoord, int ycoord) {
if (toShow[xcoord][ycoord] == 1) {
return;
}
else {
toShow[xcoord][ycoord] = 1;
}
// DOWN
if ((ycoord != 29) && ((ycoord + 1) < 16)) {
if (board[xcoord][ycoord] == ' ') {
getEmptySurrounding(xcoord, ycoord + 1);
}
}
// RIGHT
if ((xcoord != 15) && ((xcoord + 1) < 30)) {
if (board[xcoord][ycoord] == ' ') {
getEmptySurrounding(xcoord + 1, ycoord);
}
}
// UP
if ((ycoord != 0) && ((ycoord - 1) >= 0)) {
if (board[xcoord][ycoord] == ' ') {
getEmptySurrounding(xcoord, ycoord - 1);
}
}
// LEFT
if ((xcoord != 0) && ((xcoord - 1) >= 0)) {
if (board[xcoord][ycoord] == ' ') {
getEmptySurrounding(xcoord - 1, ycoord);
}
}
}
public static void insert(int n, String a) {
for (int i = 0; i < 16; i++) {
board[i][n] = a.length() <= i ? ' ' : a.charAt(i);
}
}
}
At the end it prints out the content of toShow, the relevant part is:
011111100000000000000000000000
011111110000000000000000000000
001111110000000000000000000000
001111100000000000000000000000
001110000000000000000000000000
001110000000000000000000000000
000100000000000000000000000000
000000000000000000000000000000
000000000000000000000000000000
000000000000000000000000000000
which suggest that the method works correctly.
So probably the problem lies elsewhere in your program.

How to navigate a spider in a grid system?

I have a problem where it needs to navigate a spider in a grid system (X, Y co-ordinate) with proper instruction. Initially, the spider is in (0,0) and face towards the positive Y axis.
There are 3 possible instructions for the navigation: 'F' for forward (1 grid in the same direction ), 'R' for right turn (90 degree) and 'L' for left turn (90 degree) and initially, the spider faces towards positive Y axis.
Say, if I pass the direction String of "LFF", the position should be (-2,0). I solve the problem and the current state of code is as following,
public static void spiderNavigator(String str ){
if( str == null || str.length() == 0)
return;
int [] initial = {0,0};
boolean xPos = false, xNeg = false, yPos = true, yNeg = false;
char[] ch = str.toCharArray();
for( char c: ch){
// the initial position of the spider is towards the positive Y axis
if(c == 'L'){
if(xPos){
xPos = false;
yPos = true;
}
else if ( xNeg){
xNeg = false;
yNeg = true;
}
else if(yPos){
xNeg = true;
yPos = false;
}
else if (yNeg){
yNeg = false;
xPos = true;
}
}
else if ( c == 'R'){
if(xPos){
xPos = false;
yNeg = true;
}
else if ( xNeg){
yPos = true;
xNeg = false;
}
else if(yPos){
yPos = false;
xPos = true;
}
else if (yNeg){
yNeg = false;
xNeg = true;
}
}
else if (c == 'F'){
if(xNeg){
initial[0] -= 1;
}
else if (xPos){
initial[0] += 1;
}
else if (yNeg){
initial[1] -=1;
}
else if( yPos){
initial[1] += 1;
}
}
}
System.out.println(Arrays.toString(initial));
}
However, the code feels quite ugly even to me. How can I design the algorithm in better way ?
Here's a shorter and more elegant solution:
public static void spiderNavigator(String str) {
if (str == null || str.length() == 0)
return;
int[] initial = {0, 0};
int angle = 90;
char[] ch = str.toCharArray();
for (char c : ch) {
if (c == 'L') {
angle = (angle + 90) % 360;
} else if (c == 'R') {
angle = (angle - 90) % 360;
} else if (c == 'F') {
initial[0] += (int) Math.cos(Math.toRadians(angle));
initial[1] += (int) Math.sin(Math.toRadians(angle));
}
}
System.out.println(Arrays.toString(initial));
}
Angle represents the direction spider is facing, and using trigonometric functions you can easily calculate where it should move based on current position and an angle it is facing.
Here is how I would approach it.
Have a direction variable spider_dir (where your spider is going to go now). It will store 4 different kind of values (like U, R, D, L).
Have a function change_direction which takes a current direction a and value L or R and returns a new direction. Notice that if L is passed you need to take previous circular value in array of values (['U', 'R', 'D', 'L']) of your previous value. If R than the next circular value.
Have a hash that maps your direction to your steps (assume +x, +y). U will be (0, 1), L will be (-1, 0).
Now that you have this simply iterate through your string and if you see F move add value to your current position depending on your spider_dir. If you see anything else - change your spider_dir depending on where to rotate and spider_dir
Here is a version built on a similar concept to the very nice answer by #MateuszDryzek, but without using trigonometric functions.
public static void spiderNavigator(String str) {
if (str == null || str.isEmpty())
return;
int x = 0, y = 0, dir = 0;
for (char c : str.toCharArray())
if (c == 'R')
dir = (dir + 1) % 4; // dir++: 0 -> 1 -> 2 -> 3 -> 0
else if (c == 'L')
dir = (dir + 3) % 4; // dir--: 3 -> 2 -> 1 -> 0 -> 3
else if (c == 'F')
if (dir == 0)
y++; // 0: Up
else if (dir == 1)
x++; // 1: Right
else if (dir == 2)
y--; // 2: Down
else
x--; // 3: Left
System.out.printf("(%d,%d)%n", x, y);
}

Categories