2016-02-25 6 views
0

Целью программы является создание двумерной сетки сетки, состоящей из периодов (.). Пользователь обозначает начальную точку для «ходока», обозначенную «А», а затем ходок будет генерировать числа от 0 до 3 для представления четырех основных направлений. Он будет двигаться в этих случайных направлениях, увеличивая алфавит с каждой отметкой, которую он оставляет до тех пор, пока он не забежит к стене и не будет «арестован» или не достигнет «Z», на котором он «добрался до дома». Если он пробегает в пространстве, в котором он уже был, он должен двигаться вперед в том же направлении, пока не достигнет пустого пространства или не ударит по стене.Проверка сетки 2D-сетки

Моя проблема теперь в том, что у меня есть на прилавке, чтобы убедиться, что она не пробегает мимо «Z» и будет «добираться до дома», если она достигнет этой точки. Но даже те движения, которые он предпринимает, чтобы не переписывать, где он уже был, регистрируются на прилавке (чего им не должно быть), поэтому его возвращение истинно, даже если оно еще не ударило Z, и оно также все еще вызывает мои генератор случайных чисел, поэтому он не придерживается того же направления, когда пытается его исправить. Кажется, что иногда он даже прыгает через пустые пространства.

Проблема заключается в обработке()

package walktester; 

import java.lang.Math; 
import java.util.Random; 
import java.util.Scanner; 

class DrunkWalker { 
    private char[][] walkgrid = new char[10][10]; 
    private static int randNSEW; 
    private int randomnum; 
    private int startrow; 
    private int startcol; 
    private char alpha = 'A'; 
    private int nextrow; 
    private int nextcol; 

    public DrunkWalker(int r, int c) { 
     startrow = r; 
     startcol = c; 
     nextrow = startrow; 
     nextcol = startcol; 

     for (int i = 0; i < 10; i ++) { 
      for (int j = 0; j < 10; j++) 
       walkgrid[i][j] = '.'; 
     } 
     walkgrid[r][c] = alpha++; 
    } 

    public static void getRand(){ 
     int x100 = 0; 
     double randomNum = 0.0; 
     randomNum = Math.random(); 
     x100 = (int) (randomNum * 100); 
     randNSEW = x100 % 4; 
    } 

    public int getNextRow(){ 
     return nextrow; 
    } 

    public int getNextCol(){ 
     return nextcol; 
    } 

    public boolean processing(){ 
    for(int i = 1; i < 26; i ++){ 
     getRand(); 
     if(randNSEW == 0){ 
      nextcol--; 
     } 
     if(randNSEW == 1){ 
      nextrow++; 
     } 
     if(randNSEW == 2){ 
      nextcol++; 
     } 
     if(randNSEW == 3){ 
      nextrow--; 
     } 

     if(nextrow < 0 || nextrow >= 10 || nextcol < 0 || nextcol >= 10) { 
      return false; 
     } 
     if(randNSEW == 0 && walkgrid[nextrow][nextcol] != '.'){ 
      nextcol--; 
      continue; 
     } 
     if(randNSEW == 1 && walkgrid[nextrow][nextcol] != '.'){ 
      nextrow++; 
      continue; 
     } 
     if(randNSEW == 2 && walkgrid[nextrow][nextcol] != '.'){ 
      nextcol++; 
      continue; 
     } 
     if(randNSEW == 3 && walkgrid[nextrow][nextcol] != '.'){ 
      nextrow--; 
      continue; 
     } 

     walkgrid[nextrow][nextcol] = alpha++; 
    } 
    return true; 
} 




    public char[][] DisplayGrid() { 
    for(int y = 0; y < 10; y++) { 
     for(int x = 0; x < 10; x++) { 
      System.out.print(walkgrid[x][y] + " "); 
     } 
     System.out.println(); 
    } 
    return walkgrid; 
} 
} 

public class WalkTester { 

    public static void main(String[] args) { 
     Scanner inpr = new Scanner(System.in); 
     Scanner inpc = new Scanner(System.in); 
     Scanner inpchoice = new Scanner(System.in); 

     int r = 0; 
     int c = 0; 
     char choice = 'y'; 

     while(choice == 'y' || choice == 'Y') { 
      System.out.println("Please enter x coordinate between 1 and 10."); 
      r = inpr.nextInt(); 
      r = r - 1; 

      System.out.println("Please enter y coordinate between 1 and 10"); 
      c = inpr.nextInt(); 
      c = c - 1; 

      if(r < 0 || r > 9 || c < 0 || c > 9){ 
       System.out.println("Invalid Entry. Restart? y/n"); 
       choice = inpchoice.next().charAt(0); 
       if(choice == 'y' || choice == 'Y'){ 
        continue; 
       } 
       else if(choice == 'n' || choice == 'N'){ 
        return; 
       } 
       else{ 
        System.out.println("Invalid Entry. Restart? y/n"); 
        choice = inpchoice.next().charAt(0); 
       } 
      } 
      DrunkWalker drunkwalker = new DrunkWalker(r, c); 
      boolean walkerSucceeded = drunkwalker.processing(); 
      drunkwalker.DisplayGrid(); 
      if(walkerSucceeded) { 
      System.out.println("You made it home"); 
      } else { 
      System.out.println("You were arrested"); 
      } 

      System.out.println("Restart? y/n"); 
      choice = inpchoice.next().charAt(0); 
      if(choice == 'y' || choice == 'Y'){ 
       continue; 
      } 
      else if(choice == 'n' || choice == 'N'){ 
       return; 
      } 
      else{ 
       System.out.println("Invalid Entry. Restart? y/n"); 
       choice = inpchoice.next().charAt(0); 
      } 
     } 
    } 
} 

ответ

0

Следующий код фиксирует ваши проблемы. У вас в основном не было «государства», отличающего действительный ход, а также переход на «прыжок» по сравнению с предыдущими точками посещения. Я попытался сохранить код как можно ближе к существующему коду.

class DrunkWalker { 
    private char[][] walkgrid = new char[10][10]; 
    private static int randNSEW; 
    private int randomnum; 
    private int startrow; 
    private int startcol; 
    private char alpha = 'A'; 
    private int nextrow; 
    private int nextcol; 

    public DrunkWalker(int r, int c) { 
     startrow = r; 
     startcol = c; 
     nextrow = startrow; 
     nextcol = startcol; 

     for (int i = 0; i < 10; i ++) { 
      for (int j = 0; j < 10; j++) 
       walkgrid[i][j] = '.'; 
     } 
     walkgrid[r][c] = alpha++; 
    } 

    public static void getRand(){ 
     int x100 = 0; 
     double randomNum = 0.0; 
     randomNum = Math.random(); 
     x100 = (int) (randomNum * 100); 
     randNSEW = x100 % 4; 
    } 

    public int getNextRow(){ 
     return nextrow; 
    } 

    public int getNextCol(){ 
     return nextcol; 
    } 

    enum Mode {WALKING, CORRECTING}; 
    Mode mode = Mode.WALKING; 

    public boolean processing(){ 
    for(int i = 1; i < 26; i ++){ 

     if (mode == Mode.WALKING) { 
      getRand(); 
      if(randNSEW == 0){ 
       nextcol--; 
      } 
      if(randNSEW == 1){ 
       nextrow++; 
      } 
      if(randNSEW == 2){ 
       nextcol++; 
      } 
      if(randNSEW == 3){ 
       nextrow--; 
      } 
     } 

     if(nextrow < 0 || nextrow >= 10 || nextcol < 0 || nextcol >= 10) { 
      return false; 
     } 
     if(randNSEW == 0 && walkgrid[nextrow][nextcol] != '.'){ 
      i--; 
      nextcol--; 
      mode = Mode.CORRECTING; 
      continue; 
     } 
     if(randNSEW == 1 && walkgrid[nextrow][nextcol] != '.'){ 
      i--; 
      nextrow++; 
      mode = Mode.CORRECTING; 
      continue; 
     } 
     if(randNSEW == 2 && walkgrid[nextrow][nextcol] != '.'){ 
      i--; 
      nextcol++; 
      mode = Mode.CORRECTING; 
      continue; 
     } 
     if(randNSEW == 3 && walkgrid[nextrow][nextcol] != '.'){ 
      i--; 
      nextrow--; 
      mode = Mode.CORRECTING; 
      continue; 
     } 

     mode = Mode.WALKING; 
     walkgrid[nextrow][nextcol] = alpha++; 
    } 
    return true; 
} 
+0

После просмотра, если это сообщение было вам полезна; можете ли вы пометить товар как полезный или сообщить мне, если вам нужна дополнительная помощь. Спасибо. –

Смежные вопросы