[CS4/JS] Mazes, Mazes, *Everywhere*!

For the people who are careful not to venture uninvited into the Scripting forum, I thought I might mention it here as well.
A small Javascript that can fill any shape you care to draw (including holes and curves) with a random maze -- just the thing to spice up that dry financial report you were typesetting!
The title mentions "CS4", because that's what I tested it with. It might or might not work on other CSes -- I don't know.
(In addition, be careful if you are a Windows user. It seems Javascript-for-Windows is not as solid as the Mac OS X version. The script runs flawless on my Mac, but on my PC InDesign sometimes freezes or crashes. Sorry -- nothing I can do about that. Make sure you don't have important stuff opened while running.)
Download from my web site -- it comes down zipped, so check if it's necessary to unpack (some browsers do this automatically). Save into your User Script folder (see this article if you don't know how). Draw some shape, using rectangles, ellipses, or polygons, or even the pencil -- if you draw several, you must combine them using the Pathfinder into one solid shape. Make sure this object is selected, then run the script. Et voila:
Where's the money ...

Thanks, guys, for the praise! It's way cool to think something up and then find others like it as much as I do!
I made a major improvement: when possible, the outer outline of the maze now gets constructed as a single long path. That means you can now fill the outline and set its stroke width. The thin lines inside are all connected as a single long path, so you don't have to click ten zillion single lines if you want to change its line width or color or its corner options.
Check this out: a simple image of a sideways cross-section; outer line courtesy of ID's Trace Edges; brain traced manually as a separate object; add some shadow effects, and presto! What Jongware's Brain Looks Like.

Similar Messages

  • Displaying and Moving Characters in Maze

    Right now, i am tryin to get keyListener to work. But how do I go about creating the character that appears in the maze. And how do i make the character move according to the path and so that it does not walk through the walls?
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    class MazeS extends JFrame implements KeyListener
    static int board[][] = {
    {1,1,1,1,1,1},
    {0,0,1,1,1,1},
    {1,0,1,1,1,1},
    {1,0,0,0,0,1},
    {1,0,1,1,1,1},
    {1,0,1,1,1,1},
    {1,0,1,1,1,1},
    Rectangle rect = new Rectangle();
    Maze maze;
    private JPanel panMaze, panSouth;
    private JTextArea txtChat;
    private JTextField txtInput;
    private Image image;
    public MazeS()
         this.addKeyListener(this); // This class has its own key listeners.
    this.setFocusable(true);
    // don't do this, at least until you know how
    // to avoid having to..
    // setSize(700,520);
    maze = new Maze();
    panMaze = new JPanel();
    panMaze.add(maze);
    // gamble that the default layout of this container
    // is a border layout.
    getContentPane().add(panMaze, BorderLayout.WEST);
    panSouth = new JPanel();
              panSouth = new JPanel(new BorderLayout());
                   txtChat = new JTextArea(10, 20);
                   txtInput = new JTextField();
    txtChat.setLineWrap(true);
    txtChat.setEditable(false);
    txtChat.setForeground(Color.blue);
    JScrollPane txtChatPane = new JScrollPane(txtChat,
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    txtInput.setEnabled(true);
    panSouth.add(txtInput, BorderLayout.SOUTH);
    panSouth.add(txtChatPane, BorderLayout.CENTER);
    panSouth.setPreferredSize(new Dimension(200, 200));
    getContentPane().add(panSouth, BorderLayout.SOUTH);
    //picture
    String image1 = "smiley.jpg";
    image = Toolkit.getDefaultToolkit().getImage(image1);
    pack();
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    class Maze extends JPanel
    int cellSize = 30;
    int pad = 5;
    Maze() {
    setPreferredSize( new Dimension(
    (6*cellSize)+(2*pad),
    (7*cellSize)+(2*pad)
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    g.drawRect(4,4,6*cellSize,7*cellSize);
    g.setColor(Color.pink);
    for (int y=0; y < 7; y++)
    for (int x=0; x < 6; x++)
    if (board[y][x] == 1) g.setColor(Color.pink);
    if (board[y][x] == 0) g.setColor(getBackground());
    g.fillRect(x*cellSize+5,y*cellSize+5,29,29);
    g.setColor(Color.black);
    public void paint(Graphics h){
         super.paint(h);
         h.drawImage(image, 150, 150, this);
    public void keyPressed(KeyEvent e){
         if(e.getKeyCode() == KeyEvent.VK_LEFT){
         txtChat.setText("k");
                   if (e.getKeyCode() == KeyEvent.VK_UP){
                        if (e.getKeyCode() == KeyEvent.VK_RIGHT){
                             if (e.getKeyCode() == KeyEvent.VK_DOWN){
         public void keyReleased( KeyEvent e ) {
    public void keyTyped( KeyEvent e ){
    public static void main (String args[])
    Runnable r = new Runnable() {
    public void run() {
    new MazeS().setVisible(true);
    SwingUtilities.invokeLater(r);
    }

    >
    it wasn't my idea, ..>No, it was my idea. And while I regret that has caused you some flack, I still feel it was the right decision.
    The earlier problem was about paint(), and (as per my inference of the real intent) layouts. Then after that problem was discussed, and (in my opinion) resolved, further questions arose on different topics.
    - Listening to events.
    - Game (logic) design.
    I feel that either of those questions is better represented under a different and more specific title. The title of this thread is good for what the OP (original poster) is trying to achieve.
    DB - if you are intent on being irritated with anyone over this thread, please save that irritation for me. I also ask you to consider whether any single project should necessarily be discussed under one single thread.
    And to the OP. Please figure out how to use the code tags. ..Please.

  • Image repaint preformance and threading

    Folks,
    I'm trying to make this sucker run faster.
    My question is, can anyone please guide me, especially with regards synchronising the Threads more efficiently... I'm thinking of using join and i]notify to make the "navigator" threads yield to the swing threads, to give it a chance to repaint before continuing... does this sound sane to you?
    Currently, without the thread.sleep it paints get the first "burst", and then nothing until the alrorithm has completed... exactly not what I wanted, because the whole point of this GUI is to watch the algorithm at work... sort of a "visual debugger"... I find that watching an algorithm play out helps me to "imagineer" ways of improving it... and in this case improvement means optimisation... it's all about getting from A-J faster than anyone else on the planet, especially those smarty-wishbone-legs C# programmers ;-)
    The code is too big to post (darn that 7500 char limit!) so I'll split it over several posts here, and I've also posted it as a single download to [MazeOfBoltonGUI2.java|http://groups.google.com/group/comp_lang_java_exchange/web/MazeOfBoltonGUI2.java] on my google group (comp lang java exchange).
    Cheers all. Keith.
    package forums.maze;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.SortedMap;
    import java.util.TreeMap;
    import java.util.Stack;
    import java.util.Queue;
    import java.util.PriorityQueue;
    import java.util.Iterator;
    import java.util.Set;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.ExecutionException;
    import java.awt.Dimension;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Font;
    import java.awt.image.BufferedImage;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JPanel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import javax.swing.SwingWorker;
    import java.io.PrintWriter;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    * A Visual debugger,
    * for the [A* Alogorithm|http://en.wikipedia.org/wiki/A*_search_algorithm] navigator
    * of the [Maze Of Bolton|http://cplus.about.com/od/programmingchallenges/a/challenge12.htm]
    * as implemented by [Prometheuz|http://forums.sun.com/profile.jspa?userID=550123]
    * with GUI by [Kajbj|http://forums.sun.com/profile.jspa?userID=91610]
    * hacked together by [Keith Corlett|http://forums.sun.com/profile.jspa?userID=640846]
    * and posted on [Sun's Java Forum|http://forums.sun.com/thread.jspa?threadID=5319334]
    * and posted on [Google news group|http://groups.google.com.au/group/comp_lang_java_exchange/]
    public class MazeOfBoltonGUI2
      static final char[][] matrix = readMatrix("map.txt");
      public static void main(String[] args) {
        SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              try {
                MazeNavigator navigator = new MazeNavigator(matrix);
                JFrame frame = new JFrame("MazeOfBoltonGUI2");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setContentPane(new MainPanel(navigator));
                frame.pack();
                frame.setVisible(true);
              } catch (Exception e) {
                e.printStackTrace();
       * Reads the file into a char matrix[rows,cols] ie: an array of char arrays.
       * @param String filename - the name of the file to read
       * @return a fixed length array of strings containing file contents.
      private static char[][] readMatrix(String filename) {
        try {
          BufferedReader input = null;
          try {
            input = new BufferedReader(new FileReader(filename));
            char[][] matrix = null;
            List<String> lines = new ArrayList<String>();
            String line = null;
            while ( (line = input.readLine()) != null ) {
              lines.add(line);
            int rows = lines.size();
            matrix = new char[rows][];
            for (int i=0; i<rows; i++) {
              matrix[i] = lines.get(i).toCharArray();
            System.err.println("DEBUG: rows="+rows+", cols="+matrix[0].length);
            return matrix;
          } finally {
            if(input!=null)input.close();
        } catch (IOException e) {
          e.printStackTrace();
          throw new IllegalStateException("Failed to readMatrix!", e);
    class MainPanel extends JPanel
      private static final long serialVersionUID = 1L;
      // button panel
      private final JButton goButton;
      // maze panel
      private final MazeNavigator navigator;
      private final Monitor<Path> monitor;
      private BufferedImage background;
      private BufferedImage image;
      private List<Path>currentPaths;
      public MainPanel(MazeNavigator navigator) {
        this.navigator = navigator;
        this.monitor = new SwingMonitor();
        this.goButton = new JButton("Go");
        goButton.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent event) {
              final String caption = goButton.getText();
              goButton.setVisible(false);
              monitor.execute();
        add(goButton);
        setPreferredSize(new Dimension(navigator.maze.cols*3, navigator.maze.rows*3)); //w,h
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image==null) {
          image = (BufferedImage)createImage(navigator.maze.cols, navigator.maze.rows);
          mazeColors = createMazeColors(navigator.maze);
        this.draw(image.createGraphics());
        ((Graphics2D)g).drawImage(image, 0, 0, super.getWidth(), super.getHeight(), null);
      private static Color[][] mazeColors;
      private static Color[][] createMazeColors(Maze maze) {
        Color[][] colors = new Color[maze.rows][maze.cols];
        for (int r=0; r<maze.rows; r++) {
          for (int c=0; c<maze.cols; c++) {
            colors[r][c] = getColor(maze.matrix[r][c].ch);
        return colors;
      }*... PTO ...*

    I'm persuaded that the main issue (no intermediate results drawn) is the improper use of SwingWorker.
    When you've got over it, you may want to consider other smaller-effect optimizations:
    Reconsider usage of an offscreen image*
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image==null) {
          image = (BufferedImage)createImage(navigator.maze.cols, navigator.maze.rows);
          mazeColors = createMazeColors(navigator.maze);
        this.draw(image.createGraphics());
        ((Graphics2D)g).drawImage(image, 0, 0, super.getWidth(), super.getHeight(), null);
      }At first I didn't get why you wanted to draw an offscreen image, then paint it to the screen, all that in the EDT.
    After reading the draw() method more closely, I guess you want to ease the coding of the scaling: you draw an image where one cell = one pixel, then paint the image, scaled to the panel's display size.
    In terms of performance, I don't know how it stands:
    On one hand, the image creation if lighter (1 pixel per cell). And you have a point that the built-in scaling offered by Graphics2D.drawImage(image, size) may be efficient. I can't comment on that, I hope the granphics and hardware acceleration folks will pop in the thread.
    On the other hand, if the built-in scaling had poor performance, it may be good to try what "manual" scaling would bring you. That means, in a simplified version, skip the offscreen image creation, and draw directly on the paintComponent()'s Graphics2D argument. the drawing of a cell at coordinates c,r, for example, would look like:
    g.fillRect(c*CELL_WIDTH, r*CELL_HEIGHT, WIDTH, HEIGHT);Performance apart, the scaling as you do it currently has functional drawbacks, if you want pathes as 1-pixel width lines over large cells:
    - if the maze is smaller (in rows, columns) than the panel displaying it (in pixels), the cells will be scaled but the pathes too: so your 1-pixel lines appear as large as the cells. May or may not be a desired effect.
    - if the maze is larger than the display panel, the cells are shrinked, fine, but the so are the path lines, to a point where they may be invisible (probably depending on color blending, I'm a n00b at graphics operations).
    But maybe I misunderstood the need, and maybe the intended drawing of a path is actually the drawing of the rectangles of all its traversed cells, in special path colors?
    Reconsider intermediate allocations*
    Each paintComponent() call results in the allocation of a 2D-array of Color objects (method createMazeColors(Maze)).
    I don't see what the mazeColors array brings you. I assume you wanted to decouple the determination of colors (depending on cell state) and the rendering of the colors: what does it bring: no performance advantage (on the contrary, it adds a 2D array allocation, and 2xN^2 2D-array access), and does not improve the code readability either (subjective rant, sorry).
    Why don't you pass the Maze as an argument to the draw() method, and call the getColor(cell.ch) from there?
    Side note, maybe a bit subjective: performance apart, the design of the usage of this mazeColor array is a no-go!
    An instance method alters a static variable reference,which is used subsequently in another instance method, with no synchronization. The current code does that in a single thread (+paintxxx()+ is only called in the EDT), which keeps that safe (I'd dare to say: by luck), but considerations exposed below may have you refactor the design to introduce other threads, and may exhibit the thread-unsafety of this design.
    Consider drawing the image in a background thread.*
    Indeed the technique of drawing to an offscreen image is quite common, but it is often done to improve responsiveness (not raw performance) of Swing applications. Here is a resource about this (what the author calls the passive approach), although it doesn't use a background thread.
    The idea is that if a paintCompobnent() methods involves lots of computation (arithmetics of traversing a 2D model, scaling things, etc.), this takes CPU times in the EDT, and all subsequent events (such as, a MouseEvent, but also other painting events) keep pending on the event queue, which is consumed by the single event-dispatch thread. The result is that the UI appear unresponsive, and painting of other areas may seem hung.
    The idea is to move the computation to a background thread, which posts rendering to the EDT when the Image is ready to be displayed.
    Of course this doesn't gain any CPU time. This only ensures the EDT uses a minimal part of this CPU (only render and image and process events), instead of performing the whole computation.
    In your case you already have a background thread, and indeed an appropriate choice, a SwingWorker. The application of this technique would consist in calling the draw() method in the worker thread (in the update(Path) method), and invoke super.publish() only after the image has been updated. Note that the process(List<Path>) could then ignore its argument (you may reconsider the choice of type parameter of the worker), and simply get the latest version of the image attribute).
    Of course in this technique, the offscreen image filling is called synchronously from the Navigator, so this halts the algorithm part itself, for the duration of the image generation. You may refine the technique by spawning a dedicated thread for the image generation - with subtle guard code to handle occasions when the algorithm goes faster than the image generation, and posts a new update(Path) while the image generation for the previous path has not completed yet...
    Recuce the number of things to redraw*
    Two parts:
    first, depending on the number of cells and pathes, there may be (yet another) optimization, to not redraw the whole offscreen image, but only the cells/path that have changed in the last update(). In particular, if a path is not a line but a list of cells, then it's quite easy, reusing the current offscreen image, to only fillRect(...) the appropriate cells.
    Second, if a path is not rendered as a thin line over larger cells, but as cells themselves rendered in special path colors, you may paint cells and path in one go: instead of drawing, first the cells, then the path, draw only the cells, electing the color using a decision method such as:
    private Color getColor(Cell) {
        if (cell.getPathState()!=NOT_IN_ANY_PATH) {
            return getColor(cell.getPathState());
        else {
            return getColor(cell.ch);
    }Of course this forces you to modify your data model, and update the new pathState as part of the algorithm (or better isolated, in the update(Path) method, before invoking the drawing machinery). Maybe that was the intention of the mazeColors array?
    I haven't studied your other posts on the logic of the MazeOfBolton algorithm, so I don't know if it's acceptable for you that a cell appear to have only one path state, as opposed to one for each of the pathes that traverse it. This last trick may then seem incorrect, but please consider it as only a graphical information, and indeed your current image drawing draws only ONE path for a given cell (the last path in currentPaths that traverses this cell ).

  • Problem using KeyListener in a JFrame

    Let's see if anyone can help me:
    I'm programming a Maze game, so I use a JFrame called Window, who extends JFrame and implements ActionListener, KeyListener. Thw thing is that the clase Maze is a JPanel, so I add it to my Frame and add the KeyListener to both, the Maze and the Window, but still nothing seems to happen.
    I've tried to remove the KeyListener from both separately, but still doesn't work...
    Any suggestions???

    This is the code for my Window.java file. May be someone can see the error...
    package maze;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Window extends JFrame implements ActionListener, KeyListener {
      private Maze maze;
      private JButton crear = new JButton("New");
      public Window(int size, String s) {
        super("3D Maze");
        boolean b = true;
        if (s.equalsIgnoreCase("-n"))
          b = false;
        else if (s.equalsIgnoreCase("-v"))
          b = true;
        Container c = getContentPane();
        c.setLayout(new BorderLayout());
        maze = new Maze(size,size,b);
        crear.addActionListener(this);
        addKeyListener(this);
        maze.addKeyListener(this);
        c.add(crear,BorderLayout.NORTH);
        c.add(maze,BorderLayout.CENTER);
        setSize(600,650);
        show();
      public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == e.VK_UP || e.getKeyCode() == e.VK_W)
          maze.walk();
        else if (e.getKeyCode() == e.VK_DOWN || e.getKeyCode() == e.VK_S)
          maze.back();
        else if (e.getKeyCode() == e.VK_LEFT || e.getKeyCode() == e.VK_A)
          maze.turnLeft();
        else if (e.getKeyCode() == e.VK_RIGHT || e.getKeyCode() == e.VK_D)
          maze.turnRight();
        else if (e.getKeyCode() == e.VK_V)
          maze.alternaMostrarCreacion();
        else if (e.getKeyCode() == e.VK_M)
          maze.switchMap();
      public void keyTyped(KeyEvent e) {}
      public void keyReleased(KeyEvent e) {
      public void actionPerformed(ActionEvent e) {
        maze.constructMaze();
      public static void main(String[] args) {
        int i = 30;
        String s = "-v";
        if (args.length != 0) {
          try {
            i = Integer.parseInt(args[0]);
            if (!(i >= 15 && i <= 50))
              i = 30;
            s = args[1];
          catch(Exception e) {}
        Window w = new Window(i,s);
        w.addWindowListener(
          new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
              ImageIcon im = new ImageIcon("./Logo.gif");
              String s = "";
              s += "3D MAZE\n\n";
              s += "Creator: Allan Marin\n";
              s += "http://metallan.topcities.com\n\n";
              s += ""+((char)(169))+" 2002";
              JOptionPane.showMessageDialog(null,s,"About...",JOptionPane.PLAIN_MESSAGE,im);
              System.exit(0);
    }

  • I'm writing a mazerace game...I need help from a Java Pro regarding GUI

    I've tested my code using a textUI, but not successful with GUI.
    Following are the files I have at present but are incomplete...someone please assist me, let me know what I'm missing to run the program successfully in a window.
    All I need to do is to bring the maze (2D array) onto a window, and listen to the keys (A,S,D,W & J,K,L,I) and make the move accordingly (using the move method in the MazeRace Class)
    This is my class - MazeRace
    import javax.swing.*;
    import java.io.*;
    * This class is responsible for:
    * -Initializes instance variables used to store the current state of the game
    * -When a player moves it checks if the move is legal
    * and updates the state of the game if move is allowable and made
    * -Reports information about current state of the game when asked:
    * o whether game has been won
    * o how many moves have been made by a given player
    * o what is the current configuration of the maze, etc.
    public class MazeRace {
    /** The Maze Race layout */
    private static char[][] mazeLayout;
    /** Dimensions of the maze */
    //private static final int rowLength = mazeLayout.length;
    //private static final int columnLength = mazeLayout[0].length;
    /** space in the grid is a wall */
    private static final char wall = 'X';
    /** space in the grid has been used */
    private static final char spaceUsed = '.';
    /** space in the grid is available */
    private static final char spaceAvailable = ' ';
    /** Character for Charles, Ada & Goal*/
    private static final char CHARLES = 'C';
    private static final char ADA = 'A';
    private static final char GOAL = 'G';
    /** Location of Goal in the Maze */
    private static int rowGoal = 0;
    private static int columnGoal = 0;
    /** Location of Ada in the Maze */
    private static int rowAda = 0;
    private static int columnAda = 0;
    /** Location of Charles in the Maze */
    private static int rowCharles = 0;
    private static int columnCharles = 0;
    /** Number of Ada's moves */
    private static int countAdasMoves = 0;
    /** Number of Charles's moves */
    private static int countCharlesMoves = 0;
    * Constructor for MazeRace
    * &param mazeGrid - 2D array of characters
    public MazeRace(char[][] mazeGrid){
    this.mazeLayout = mazeGrid;
    for (int row = 0; row < mazeLayout.length; row++){
    for (int column = 0; column < mazeLayout[0].length; column++){
    if (mazeLayout[row][column] == GOAL){
    this.rowGoal = row;
    this.columnGoal = column;
    if (mazeLayout[row][column] == ADA){
    this.rowAda = row;
    this.columnAda = column;
    if (mazeLayout[row][column] == CHARLES){
    this.rowCharles = row;
    this.columnCharles = column;
    public boolean canMoveLeft(){
    int rowA = this.rowAda;
    int columnA = this.columnAda;
    int rowC = this.rowCharles;
    int columnC = this.rowCharles;
    boolean canMove = false;
    if (mazeLayout[rowA][columnA - 1] == spaceAvailable
    || mazeLayout[rowA][columnA - 1] == GOAL) {
    canMove = true;
    return canMove;
    * This method takes in a single character value that indicates
    * both the player making the move, and which direction the move is in.
    * If move is legal, the player's position will be updated. Move is legal
    * if player can move one space in that direction i.e. the player isn't
    * moving out of the maze, into a wall or a space has already been used.
    * @param moveDirection: indicates the player making the move and direction
    * @return moveMade: boolean value true if move was made, false otherwise
    public boolean move(char move){
    boolean validMove = false;
    /** store Ada's current row location in a temp variable */
    int rowA = this.rowAda;
    /** store Ada's current column location in a temp variable */
    int columnA = this.columnAda;
    /** store Charles current row location in a temp variable */
    int rowC = this.rowCharles;
    /** store Charles current column location in a temp variable */
    int columnC = this.columnCharles;
    /** if Ada is moving left, check if she can make a move */
    if (move == 'A' && (mazeLayout[rowA][columnA - 1] == spaceAvailable
    || mazeLayout[rowA][columnA - 1] == GOAL)) {
    /** if move is legal, then update old space to spaceUsed '.' */
    mazeLayout[rowA][columnA] = spaceUsed;
    /** update Ada's new position */
    mazeLayout[rowA][columnA - 1] = ADA;
    this.rowAda = rowA; //update new row location of Ada
    this.columnAda = columnA - 1; //update new column location of Ada
    validMove = true; //valid move has been made
    countAdasMoves++; //increment Ada's legal move
    /** if Ada is moving down, then check if she can make the move */
    if (move == 'S'&& (mazeLayout[rowA + 1][columnA] == spaceAvailable
    || mazeLayout[rowA + 1][columnA] == GOAL)) {
    mazeLayout[rowA][columnA] = spaceUsed;
    mazeLayout[rowA + 1][columnA] = ADA;
    this.rowAda = rowA + 1;
    this.columnAda = columnA;
    validMove = true;
    countAdasMoves++;
    /** if Ada is moving right, then check if she can make the move */
    if (move == 'D'&& (mazeLayout[rowA][columnA + 1] == spaceAvailable
    || mazeLayout[rowA][columnA + 1] == GOAL)) {
    mazeLayout[rowA][columnA] = spaceUsed;
    mazeLayout[rowA][columnA + 1] = ADA;
    this.rowAda = rowA;
    this.columnAda = columnA + 1;
    validMove = true;
    countAdasMoves++;
    /** if Ada is moving up, then check if she can make the move */
    if (move == 'W'&& (mazeLayout[rowA - 1][columnA] == spaceAvailable
    || mazeLayout[rowA - 1][columnA] == GOAL)) {
    mazeLayout[rowA][columnA] = spaceUsed;
    mazeLayout[rowA - 1][columnA] = ADA;
    this.rowAda = rowA - 1;
    this.columnAda = columnA;
    validMove = true;
    countAdasMoves++;
    /** if Charles is moving left, then check if he can make the move */
    if (move == 'J'&& (mazeLayout[rowC][columnC - 1] == spaceAvailable
    || mazeLayout[rowC][columnC - 1] == GOAL)) {
    mazeLayout[rowC][columnC] = spaceUsed;
    mazeLayout[rowC][columnC -1] = CHARLES;
    this.rowCharles = rowC;
    this.columnCharles = columnC - 1;
    validMove = true;
    countCharlesMoves++;
    /** if Charles is moving down, then check if he can make the move */
    if (move == 'K'&& (mazeLayout[rowC + 1][columnC] == spaceAvailable
    || mazeLayout[rowC + 1][columnC] == GOAL)) {
    mazeLayout[rowC][columnC] = spaceUsed;
    mazeLayout[rowC + 1][columnC] = CHARLES;
    this.rowCharles = rowC + 1;
    this.columnCharles = columnC;
    validMove = true;
    countCharlesMoves++;
    /** if Charles is moving right, then check if he can make the move */
    if (move == 'L'&& (mazeLayout[rowC][columnC + 1] == spaceAvailable
    || mazeLayout[rowC][columnC + 1] == GOAL)) {
    mazeLayout[rowC][columnC] = spaceUsed;
    mazeLayout[rowC][columnC + 1] = CHARLES;
    this.rowCharles = rowC;
    this.columnCharles = columnC + 1;
    validMove = true;
    countCharlesMoves++;
    /** if Charles is moving up, then check if he can make the move */
    if (move == 'I'&& (mazeLayout[rowC - 1][columnC] == spaceAvailable
    || mazeLayout[rowC - 1][columnC] == GOAL)){
    mazeLayout[rowC][columnC] = spaceUsed;
    mazeLayout[rowC - 1][columnC] = CHARLES;
    this.rowCharles = rowC - 1;
    this.columnCharles = columnC;
    validMove = true;
    countCharlesMoves++;
    return validMove;
    * This method indicates whether the current maze configuration is a winning
    * configuration for either player or not.
    * Return 1 if Ada won
    * Return 2 if Charles won
    * Return 0 if neither won
    * @return int won: Indicates who won the game (1 or 2) or no one won the
    * game (0)
    public static int hasWon() {
    int won = 0;
    /** if location of Goal's row and column equals Ada's then she won */
    if (rowGoal == rowAda && columnGoal == columnAda){
    won = 1;
    /** if location of Goal's row and column equals Charles's then he won */
    if (rowGoal == rowCharles && columnGoal == columnCharles){
    won = 2;
    /** if both players are away from the Goal then no one won */
    if ((rowGoal != rowAda && columnGoal != columnAda) &&
    (rowGoal != rowCharles && columnGoal != columnCharles)) {
    won = 0;
    return won;
    * This method indicates whether in the current maze configuration both
    * players are caught in dead ends.
    * @return deadEnd: boolean value true if both players can't make a valid
    * move, false otherwise
    public static boolean isBlocked(){
    boolean deadEnd = false;
    /** Check if Ada & Charles are blocked */
    if (((mazeLayout[rowAda][columnAda - 1] == wall
    || mazeLayout[rowAda][columnAda - 1] == spaceUsed
    || mazeLayout[rowAda][columnAda - 1] == CHARLES)
    && (mazeLayout[rowAda][columnAda + 1] == wall
    || mazeLayout[rowAda][columnAda + 1] == spaceUsed
    || mazeLayout[rowAda][columnAda + 1] == CHARLES)
    && (mazeLayout[rowAda + 1][columnAda] == wall
    || mazeLayout[rowAda + 1][columnAda] == spaceUsed
    || mazeLayout[rowAda + 1][columnAda] == CHARLES)
    && (mazeLayout[rowAda - 1][columnAda] == wall
    || mazeLayout[rowAda - 1][columnAda] == spaceUsed
    || mazeLayout[rowAda - 1][columnAda] == CHARLES))
    && ((mazeLayout[rowCharles][columnCharles - 1] == wall
    || mazeLayout[rowCharles][columnCharles - 1] == spaceUsed
    || mazeLayout[rowCharles][columnCharles - 1] == ADA)
    && (mazeLayout[rowCharles][columnCharles + 1] == wall
    || mazeLayout[rowCharles][columnCharles + 1] == spaceUsed
    || mazeLayout[rowCharles][columnCharles + 1] == ADA)
    && (mazeLayout[rowCharles + 1][columnCharles] == wall
    || mazeLayout[rowCharles + 1][columnCharles] == spaceUsed
    || mazeLayout[rowCharles + 1][columnCharles] == ADA)
    && (mazeLayout[rowCharles - 1][columnCharles] == wall
    || mazeLayout[rowCharles - 1][columnCharles] == spaceUsed
    || mazeLayout[rowCharles - 1][columnCharles] == ADA))) {
    deadEnd = true;
    return deadEnd;
    * This method returns an integer that represents the number of moves Ada
    * has made so far. Only legal moves are counted.
    * @return int numberOfAdasMoves: number of moves Ada has made so far
    public static int numAdaMoves() {
    return countAdasMoves;
    * This method returns an integer that represents the number of moves Charles
    * has made so far. Only legal moves are counted.
    * @return int numberOfCharlesMoves: number of moves Charles has made so far
    public static int numCharlesMoves() {
    return countCharlesMoves;
    * This method returns a 2D array of characters that represents the current
    * configuration of the maze
    * @return mazeLayout: 2D array that represents the current configuration
    * of the maze
    public static char[][] getGrid() {
    return mazeLayout;
    * This method compares contents of this MazeRace object to given MazeRace.
    * The two will not match if:
    * o the two grids have different dimensions
    * o the two grids have the same dimensios but positions of walls, players or
    * goal differs.
    * @param MazeRace: MazeRace object is passed in and compared with the given
    * MazeRace grid
    * @return boolean mazeEqual: true if both grids are same, false otherwise
    public static boolean equals(char[][] mr) {
    boolean mazeEqual = true;
    /** If the length of the arrays differs, then they are not equal */
    if (mr.length != mazeLayout.length || mr[0].length != mazeLayout[0].length){
    mazeEqual = false;
    } else {
    /** If lengths are same, then compare every element of the array to other */
    int count = 0;
    int row = 0;
    int column = 0;
    while( count < mr.length && mazeEqual) {
    if( mr[row][column] != mazeLayout[row][column]) {
    mazeEqual = false;
    count = count + 1;
    row = row + 1;
    column = column + 1;
    return mazeEqual;
    * This method represents the current state of the maze in a string form
    * @return string mazeString: string representation of the maze configuration
    public String toString() {
    String mazeString = "";
    for (int row = 0; row < mazeLayout.length; row++){
    for (int column = 0; column < mazeLayout[0].length; column++){
    mazeString = mazeString + mazeLayout[row][column];
    mazeString = mazeString + "\n";
    return mazeString.trim();
    The following is the Driver class: MazeRaceDriver
    import javax.swing.*;
    import java.io.*;
    * This class is the starting point for the maze race game. It is invoked
    * from the command line, along with the location of the layout file and
    * the desired interface type. Its main purpose is to initialize the
    * components needed for the game and the specified interface.
    public class MazeRaceDriver {
    * A method that takes a text file representation of the maze and
    * produces a 2D array of characters to represent the same maze.
    * @param layoutFileName location of the file with the maze layout
    * @return The maze layout.
    public static char[][] getLayoutFromFile( String layoutFileName )
    throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(layoutFileName));
    String s = br.readLine();
    int r = 0; // start at row 1
    int c = s.length(); // initialize column to the length of the string
    while(s != null){
    r++;
    s = br.readLine();
    char[][]grid = new char[r][c];
    // this part, gets the text file into a char array
    BufferedReader brr = new BufferedReader(new FileReader(layoutFileName));
    String ss = brr.readLine();
    int row = 0;
    while(ss != null){
    for(int col = 0; col < c; col++){
    grid[row][col] = ss.charAt(col);
    row++;
    ss = brr.readLine();
    return grid;
    * The main method of your program.
    * @param args command-line arguments provided by the user
    public static void main( String[] args ) throws IOException {
    // check for too few or too many command line arguments
    if ( args.length != 2 ) {
    System.out.println( "Usage: " +
    "java MazeRaceDriver <location> <interface type>" );
    return;
    if ( args[1].toLowerCase().equals( "text" ) ) {
    char[][] layout = getLayoutFromFile( args[0] );
    MazeRace maze = new MazeRace( layout );
    MazeRaceTextUI game = new MazeRaceTextUI( maze );
    game.startGame();
    else if ( args[1].toLowerCase().equals( "gui" ) ) {
    // Get the filename using a JFileChooser
    // read the layout from the file
    // starting the window-based maze game
    JFileChooser chooser = new JFileChooser("");
    int returnVal = chooser.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
    BufferedReader br =
    new BufferedReader(new FileReader(chooser.getSelectedFile()));
    String inputLine = br.readLine();
    while (inputLine != null) {
    System.out.println(inputLine);
    inputLine = br.readLine();
    char[][] layout = getLayoutFromFile( args[0] );
    MazeRace maze = new MazeRace( layout );
    MazeRaceWindow game = new MazeRaceWindow( maze );
    game.startGame();
    } else {
    System.out.println("Cancel was selected");
    } else {
    System.out.println( "Invalid interface for game." +
    " Please use either TEXT or GUI." );
    return;
    The following is the MazeRaceWindow class
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.io.*;
    * This class is responsible for displaying the maze race game. It should
    * set up the maze window when the game is started and update the display
    * with each move.
    public class MazeRaceWindow extends JFrame {
    private JLabel[][] mazeLabel;
    private JFrame mazeFrame;
    * Reference to the underlying MazeRace object which needs to be
    * updated when either player moves
    private MazeRace maze;
    * Class constructor for the GUI object
    * @param maze the underlying MazeRace object
    public MazeRaceWindow( MazeRace maze ) {
    this.maze = maze;
    System.out.println(maze);
    mazeFrame = new JFrame();
    mazeFrame.setSize(200,200);
    Container content = mazeFrame.getContentPane();
    System.out.println(content);
    content.setLayout(new GridLayout(.length, mazeLayout[0].Length));
    for (int i = 0; i < MazeRace.length; i++ ) {
    for (int j = 0; j < MazeRace[0].length; j++ ) {
    mazeLabel = new JLabel[MazeRace.rowLength][MazeRace.columnLength];
    content.add(mazeLabel[i][j]);
    System.out.println(mazeLabel[i][j]);
    mazeFrame.pack();
    mazeFrame.setVisible(true);
    //content.add(mazeLabel);
    //mazeFrame.addKeyListener(this);
    * A method to be called to get the game running.
    public void startGame() throws IOException {
    System.out.println();
    /* loop to continue to accept moves as long as there is at least one
    * player able to move and no one has won yet
    while ( !maze.isBlocked() && maze.hasWon() == 0 ) {
    // prints out current state of maze
    System.out.println( maze.toString() );
    System.out.println();
    // gets next move from players
    System.out.println("Next move?");
    System.out.print("> ");
    BufferedReader buffer =
    new BufferedReader( new InputStreamReader( System.in ) );
    String moveText = "";
    moveText = buffer.readLine();
    System.out.println();
    // note that even if a string of more than one character is entered,
    // only the first character is used
    if ( moveText.length() >= 1 ) {
    char move = moveText.charAt( 0 );
    boolean validMove = maze.move( move );
    // The game has finished, so we output the final state of the maze, and
    // a message describing the outcome.
    System.out.println( maze );
    int status = maze.hasWon();
    if ( status == 1 ) {
    System.out.println( "Congratulations Ada! You won the maze in "
    + maze.numAdaMoves() + " moves!" );
    } else if ( status == 2 ) {
    System.out.println( "Congratulations Charles! You won the maze in "
    + maze.numCharlesMoves() + " moves!" );
    } else {
    System.out.println( "Stalemate! Both players are stuck. "
    + "Better luck next time." );
    The following is the Listener class: MazeRaceListener
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    /** Listens for keystrokes from the GUI interface to the MazeRace game. */
    public class MazeRaceListener extends KeyAdapter {
    * Reference to the underlying MazeRace object which needs to be updated
    * when either player moves
    private MazeRace maze;
    * Reference to the MazeRaceWindow object that displays the state of
    * the game
    private MazeRaceWindow mazeWindow;
    * Class constructor for the key listener object
    * @param maze the underlying MazeRace object
    public MazeRaceListener( MazeRace maze ) {
    this.maze = maze;
    * A method that sets which JFrame will display the game and need to be
    * updated with each move.
    * @param window the JFrame object that displays the state of the game
    public void setMazeRaceWindow( MazeRaceWindow window ) {
    mazeWindow = window;
    * A method that will be called each time a key is pressed on the active
    * game display JFrame.
    * @param event contains the pertinent information about the keyboard
    * event
    public void keyTyped( KeyEvent event ) {
    char move = event.getKeyChar();
    // TODO: complete method so that the appropriate action is taken
    // in the game
    //mazeLabel.setText(String.valueOf(move).toUpperCase());
    }

    and listen to the keys (A,S,D,W & J,K,L,I) and make the move accordingly [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to Use Key Bindings

  • Painting in JPanels

    Hey guys, thanks for the help with the last question. Heres another for the same program!
    So this program generates a JFrame which is populated with JPanel's in a gridLayout() format. The grid is supposed to represent a maze which is navigated by clicking on the appropriate panels.
    The first problem I'm having is trying to get the starting square, the current square and the squares that have previously stepped on to change color. Also the current square should show a circle to indicate where you are.
    Instead of doing that the squares are just showing random graphics on them due to an arbitrary line of code i put in:
    Graphics g = getGraphics();If i take that out then nothing changes color/graphics.
    The second problem I'm having is when i load a new maze (or the same one) instead of replacing the displayed one it tries to squish them both in. Yet when i print out all the values like the number of columns in the gridLayout it they are all correct. I'm hoping this is just a display error and will be fixed with the first problem.
    The Maze.java class brings everything together and calls the Walls.java class which creates and adds the JPanel's which are GridPanel.java objects. The Move.java and Maze.java alters the GridPanel's to be current or not... Good Luck =) and thanks heaps as always! YOU GUYS ARE LIFESAVERS!!!
    //Ass2.java
    public class Assign2
         public static void main(String[] args)
              Maze theMaze = new Maze();
    //Maze.java
    import java.io.*;
    import java.util.Vector;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class Maze extends JFrame
         Vector<String> data = new Vector<String>();
         GridPanel[][] panel;
         private int[] endPoints = new int[4];
         private int[] size = new int[2];
         private int moveNum;
         private int theSize;
         private int cX;
         private int cY;
         private int pX;
         private int pY;
         public Maze()
              MazeApp s = new MazeApp(this);
              moveNum = 0;
              File f = new File("maze.txt");
              readMaze(f);
         public void readMaze(File fName)
              File fileName = fName;
              Read r = new Read();
              data.clear();
              size = r.readFile(endPoints, data, fileName);
              theSize = (size[1] * size[0]);
              cX = endPoints[0];
              cY = endPoints[1];
              GridLayout layout = new GridLayout();
              layout.setRows(size[1]);
              layout.setColumns(size[0]);
              this.setLayout(layout);
              System.out.println(data.size());
              makeMaze();
         public void makeMaze()
              panel = new GridPanel [size[1]][size[0]];
              Walls w = new Walls(data, size, this);
              w.drawWalls(panel);
              panel[endPoints[1]][endPoints[0]].setStart();
              panel[endPoints[3]][endPoints[2]].setEnd();
              this.setSize(size[0]*100, size[1]*100);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setVisible(true);
         public void checkMove(Point clicked, int w, int h, int wall)
              pY = (int)(clicked.getX())/w;
              pX = (int)(clicked.getY())/h;
              Move m = new Move(cX, cY, pX, pY, w, h, wall);
              if(m.check() == 1) //MOVE NORTH
                   if((panel[cX-1][cY].checkWall() != 2) && (panel[cX-1][cY].checkWall() != 3))
                   {setCurrent();}else{JOptionPane.showMessageDialog(this, "Invalid Move! Cannot move through walls!");}
              if(m.check() == 2) //MOVE SOUTH
                   if((panel[cX][cY].checkWall() != 2) && (panel[cX][cY].checkWall() != 3))
                   {setCurrent();}else{JOptionPane.showMessageDialog(this, "Invalid Move! Cannot move through walls!");}
              if(m.check() == 3) //MOVE WEST
                   if((panel[pX][pY].checkWall() != 1) && (panel[pX][pY].checkWall() != 3))
                   {setCurrent();}else{JOptionPane.showMessageDialog(this, "Invalid Move! Cannot move through walls!");}
              if(m.check() == 4) //MOVE EAST
                   if((panel[cX][cY].checkWall() != 1) && (panel[cX][cY].checkWall() != 3))
                   {setCurrent();}else{JOptionPane.showMessageDialog(this, "Invalid Move! Cannot move through walls!");}
              if(m.check() == 0 )
              {JOptionPane.showMessageDialog(this, "Invalid Move! Invalid square selected!\nPlease choose an adjacent square.");}
         public void setCurrent()
              panel[cX][cY].setUsed();
              panel[pX][pY].setCurrent();
              cX = pX;
              cY = pY;
              moveNum++;
              if(cY == endPoints[2] && cX == endPoints[3])
              {JOptionPane.showMessageDialog(this, "Congratulations!\nYou finished in" + moveNum + "moves!");}
    // MazeApp.java
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    public class MazeApp extends JFrame
           private Maze theMaze;
           public MazeApp(Maze m)
                   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   theMaze = m;
                   // create the menu bar to hold the menus...
                   JMenuBar menuBar = new JMenuBar();
                   // create the menus to hold the menu items...
                   JMenu menuFile = new JMenu("File");
                   JMenu menuOptions = new JMenu("Options");
                   JMenu menuHelp = new JMenu("Help");
                   // create file menu options:
                   JMenuItem itemLoad = new JMenuItem("Load");
                   JMenuItem itemSaveAs = new JMenuItem("Save As...");
                   JRadioButtonMenuItem itemModePlay = new JRadioButtonMenuItem("Play");
                   JRadioButtonMenuItem itemModeEdit = new JRadioButtonMenuItem("Edit");
                   JMenuItem itemExit = new JMenuItem("Exit");
                   //create options menu:
                   JRadioButtonMenuItem itemNoRats = new JRadioButtonMenuItem("No Rats");
                   JRadioButtonMenuItem itemOneRat = new JRadioButtonMenuItem("One Rat");
                   JRadioButtonMenuItem itemTwoRats = new JRadioButtonMenuItem("Two Rats");
                   //create help option:
                   JMenuItem itemHelp = new JMenuItem("Help");
                   JMenuItem itemAbout = new JMenuItem("About");
                   //set default options:
                   itemModePlay.setSelected(true);                    
                   itemNoRats.setSelected(true);
                   // add File options:
                   menuFile.add(itemLoad);
                   menuFile.add(itemSaveAs);
                   menuFile.addSeparator();
                   menuFile.add(itemModePlay);
                   menuFile.add(itemModeEdit);
                   menuFile.addSeparator();
                   menuFile.add(itemExit);
                   //add Options:
                   menuOptions.add(itemNoRats);
                   menuOptions.add(itemOneRat);
                   menuOptions.add(itemTwoRats);
                   //add Help options:
                   menuHelp.add(itemHelp);
                   menuHelp.add(itemAbout);
                   // add the menu to the menu bar...
                   menuBar.add(menuFile);
                   menuBar.add(menuOptions);
                   menuBar.add(menuHelp);
                   // finally add the menu bar to the app...
                   m.setJMenuBar(menuBar);
                   //listeners
                   itemExit.addActionListener(
                           new ActionListener()
                                   public void actionPerformed( ActionEvent event )
                                           System.exit( 0 );
                itemLoad.addActionListener(
                   new ActionListener()
                        public void actionPerformed( ActionEvent event )
                             final JFileChooser fc = new JFileChooser();
                             int returnVal = fc.showOpenDialog(MazeApp.this);
                          File fileName = fc.getSelectedFile();
                             if(fileName.exists())
                                  theMaze.readMaze(fileName);
                             else
                                  System.out.println("404. File not found");
                   itemAbout.addActionListener(
                           new ActionListener()
                                   public void actionPerformed( ActionEvent event )
                                           //do stuff
                                           JOptionPane.showMessageDialog(MazeApp.this, "Author: Pat Purcell\[email protected]", "About", JOptionPane.ERROR_MESSAGE);
    //Read.java
    import java.io.*;
    import java.util.Vector;
    public class Read
         private BufferedReader input;
         private String line;
         private String fileName;
         private String[] temp;
         private int[] size = new int[2];
         public int[] readFile(int[] endPoints, Vector<String> data, File fileName)
              try
                   data.clear();
                   FileReader fr = new FileReader(fileName);
                   input = new BufferedReader(fr);
                   line = input.readLine();
                   temp = line.split("\\s");
                   for(int i =0;i<2;i++)
                   {size[i] = Integer.parseInt(temp);}
                   line = input.readLine();
                   temp = line.split("\\s");
                   for(int i =0;i<4;i++)
                   {endPoints[i] = Integer.parseInt(temp[i]);}
                   line = input.readLine();
                   while (line != null)
                        String[] temp = line.split("\\s");
                        for(int i=0;i<size[0];i++)
                             data.addElement(temp[i]);
                        line = input.readLine();
                   input.close();
              catch (IOException e)
                   System.err.println(e);
              return size;
    }//Walls.java
    import java.util.Vector;
    import java.awt.GridLayout;
    import javax.swing.*;
    public class Walls extends JFrame
         private Vector<String> data = new Vector<String>();
         private int size;
         private Maze bm;
         private int row;
         private int column;
         public Walls(Vector<String> theData, int[] theSize, Maze m)
              data = theData;
              row = theSize[1];
              column = theSize[0];
              size = row*column;
              bm = m;
         public boolean testEast(int position)
              boolean exists;
              String temp = data.get(position);
              int eastData = ((int)temp.charAt(0) - (int)'0');
              if(1 == (eastData))
                   return true;
              return false;
         public boolean testSouth(int position)
              boolean exists;
              String temp = data.get(position);
              int southData = ((int)temp.charAt(1) - (int)'0');
              if(1 == (southData))
                   return true;
              return false;
         public boolean testBoth(int position)
              boolean exists;
              if((testEast(position) && testSouth(position)) == true)
                   return true;
              return false;
         public void drawWalls(GridPanel panel[][])
              int i = 0;
              for(int y=0;y<row;y++)
                   for(int x=0;x<column;x++, i++)
                   if (testBoth(i) == true)
                   {     GridPanel temp = new GridPanel(3, bm);
                        panel[y][x] = temp;
                                  bm.add(temp);}
                   else{
                        if (testEast(i) == true)
                        {     GridPanel temp = new GridPanel(1, bm);
                             panel[y][x] = temp;
                                  bm.add(temp);}
                        else{
                             if (testSouth(i) == true)
                             {     GridPanel temp = new GridPanel(2, bm);
                                  panel[y][x] = temp;
                                  bm.add(temp);}
                             else{
                                  GridPanel temp = new GridPanel(0, bm);
                                  panel[y][x] = temp;
                                  bm.add(temp);}
    }//GridPanel.java
    import javax.swing.JPanel;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    public class GridPanel extends JPanel implements MouseListener
    private int wall;
    private Maze bm;
    private Ellipse2D.Double circle = new Ellipse2D.Double();
    private Graphics gr;
    boolean current = false;
    boolean start = false;
    boolean finish = false;
    public GridPanel(int theWall, Maze m)
         wall = theWall;
         this.addMouseListener(this);
         bm = m;
         public void paintComponent(Graphics g)
              Graphics2D g2 = (Graphics2D)g;
              g2.setStroke(new BasicStroke(1));
              g2.draw(new Line2D.Double(this.getWidth()-1, 0, this.getWidth()-1, this.getHeight()-1));
              g2.draw(new Line2D.Double(0, this.getHeight()-1, this.getWidth()-1, this.getHeight()-1));
              g2.setStroke(new BasicStroke(4));
              if(wall == 0) //NO WALL
              if(wall == 1) //EAST WALL
                   g2.draw(new Line2D.Double(this.getWidth()-1, 0, this.getWidth()-1, this.getHeight()-1));
              if(wall == 2) //SOUTH WALL
                   g2.draw(new Line2D.Double(0, this.getHeight()-1, this.getWidth()-1, this.getHeight()-1));
              if(wall == 3) //BOTH WALLS
                   g2.draw(new Line2D.Double(0, this.getHeight()-1, this.getWidth()-1, this.getHeight()-1));
                   g2.draw(new Line2D.Double(this.getWidth()-1, 0, this.getWidth()-1, this.getHeight()-1));
              if(current == true)
                   setBackground(SystemColor.green);
                   circle = new Ellipse2D.Double();
                   circle.x = 0;
                   circle.y = 0;
                   circle.height = this.getHeight()-1; // -1 so it fits inside the panel.
                   circle.width = this.getWidth()-1;
                   g2.draw(circle);
                   repaint();
              if(start == true)
              {     setBackground(SystemColor.green);
                   g2.drawString("S", this.getWidth()/2, this.getHeight()/2);}
              if(finish == true)
              {     setBackground(SystemColor.green);
                   g2.drawString("F", this.getWidth()/2, this.getHeight()/2);}
         public int checkWall()
              return wall;
         public void setCurrent()
              Graphics g = getGraphics();
              repaint();
         public void setUsed()
              current = false;
              repaint();
         public void setStart()
              start = true;
              repaint();
         public void setEnd()
              finish = true;
              repaint();
         public void mouseClicked(MouseEvent e){bm.checkMove(this.getLocation(), this.getWidth(), this.getHeight(), wall);}
         public void mouseReleased (MouseEvent e) {}
         public void mouseEntered (MouseEvent e) {}
         public void mouseExited(MouseEvent e) {}
         public void mousePressed(MouseEvent e) {}
    }//Move.java
    import java.awt.*;
    public class Move
         private int pX;
         private int pY;
         private int cX;
         private int cY;
         private int w;
         private int h;
         private int wall;
         public Move(int x1, int y1, int x2, int y2, int theWidth, int theHeight, int wallCheck)
              pX = x2;
              pY = y2;
              cX = x1;
              cY = y1;
              w = theWidth;
              h = theHeight;
         public int check()
              //System.out.println(cX + " " + (pX + 1));
              if((cX == (pX + 1)) && (cY == pY)) //MOVE NORTH
              {return 1;}
              //System.out.println(cX + " " + (pX - 1));
              if((cX == (pX - 1)) && (cY == pY)) //MOVE SOUTH
              {return 2;}
              //System.out.println(cY + " " + (pY + 1));
              if((cY == (pY + 1)) && (cX == pX))//MOVE WEST
              {return 3;}
              //System.out.println(cY + " " + (pY - 1));
              if((cY == (pY - 1)) && (cX == pX))//MOVE EAST
              {return 4;}
              return 0;
    }This is the file the maze is read out of: Maze.txt6 5
    0 0 3 2
    10 00 01 01 01 10
    10 10 00 01 10 10
    10 10 01 11 10 10
    10 01 01 01 11 10
    01 01 01 01 01 11                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    -> Second proplem that still remains is the circle stays after you leave the square...
    Thats why I suggested you use a Border and not do custom painting. There is no such method as remove(...). You need to repaint the entire panel. If you use a Border you just use setBorder(...) to whatever. So you have two different Borders. One for when the component has focus and one for when the component doesn't.
    -> but the same two problems remain.
    Well, I don't know whats wrong and I am not about to debug your program since I have no idea what it is doing. So create a SSCCE to post.
    see http://homepage1.nifty.com/algafield/sscce.html,
    Basically all you need to do is create a JFrame. Create a "main" panel with a flow layout and add it to the content pane. Then create 3 or 4 panels with a default Border on a black line and add the panels to the "main" panel. Then add you MouseListeners and FocusListeners to the panels. The whole program should be 30 lines of code or so. Understand how that program works and then apply the same concepts to you real program.
    The point is when you attempt to do something new that you don't understand write a simple program so you can prove to yourself that it works. If you can't get it working then you have a simple SSCCE to post and then maybe someone will look at it.

  • Problem in running JAR file

    Creating a mobile game using J2ME. The JAR file created by Netbeans IDE when bein run on mobile gives an error: JAR and JAD file did not match.
    Manifest file:
    Manifest-Version: 1.0
    Ant-Version: Apache Ant 1.6.2
    Created-By: 1.5.0_06-b05 (Sun Microsystems Inc.)
    MIDlet-1: Maze, Maze.png, Maze
    MIDlet-Vendor: Unknown
    MIDlet-Name: Maze
    MIDlet-Version: 1.0
    MicroEdition-Configuration: CLDC-1.1
    MicroEdition-Profile: MIDP-2.0
    JAD file:
    MIDlet-1: Maze, Maze.png, Maze
    MIDlet-Jar-Size: 100
    MIDlet-Jar-URL: Maze.jar
    MIDlet-Name: Maze
    MIDlet-Vendor: Unknown
    MIDlet-Version: 1.0
    MicroEdition-Configuration: CLDC-1.1
    MicroEdition-Profile: MIDP-2.0
    Please consider the query..

    Hey I solved the problem in following order
    JLabel jbl = new JLabel(new ImageIcon(getClass().getResource("image/theme.GIF")));I have a tips to all who are absorving in this problem
    that you should check that whether the extension is in capitalletter or small letter in the jar. Follow the format in your coding
    thnx
    best regards
    tanvir

  • Could someone explain this output?

    my Maze class
    import java.util.Scanner;
    import java.io.*;
    public class MazeProblem{
         private char [][] maze;               //maze array of 0's and 1's
         private boolean [][] visit;          //visited/unvisited array
         private int height, width;          //height and width of array
         private int startx, starty;          //starting point
         private int exitx, exity;          //exit point
         private Scanner sc;                    //file reader
         private StringTokenizer st;          // to split the file.
         public MazeProblem(String file){
              try{
                   sc = new Scanner(new BufferedReader(new FileReader(file)));
                   while (sc.hasNextLine()){
                        height = sc.nextInt();
                        width = sc.nextInt();
                        System.out.println("no. of rows: " +height); // tester code
                        System.out.println("no. of cols: " +width);      //tester
                        maze = new char[height][width];
                        visit = new boolean [height][width];
                        for (int i = 0; i < height; i++){
                             for (int j = 0; j < width; j++){
                                  maze [j] = sc.next().toCharArray()[0];
                        System.out.println("");
                        startx = sc.nextInt();
                        System.out.println("startx = " + startx);
                        starty = sc.nextInt();
                        System.out.println("starty = " + starty);
                        exitx = sc.nextInt();
                        System.out.println("exitx = " + exitx);
                        exity = sc.nextInt();
                        System.out.println("exity = " + exity);
              catch(FileNotFoundException e){
                   System.out.println("File not found.");
                   System.exit(0);
              finally{
                   sc.close();
              for (int i = 0; i < height; i++){
                   for(int j = 0; j < width; j++){
                        System.out.print(" " + maze[i][j]);
              System.out.println("");     
         //find out if there is a path from start to finish
         public boolean isPath(){
              return isPath(startx, starty);     //call recursive method
         //recursive method that chekcs for the path from current location
         //to finish location.
         private boolean isPath(int x, int y){
              //base case current loc. outside of maze
              if (x < 0 || x >= height || y < 0 || y >= width)
                   return false;
              //base case current loc. is a wall
              else if (maze[x][y] == '1')
                   return false;
              //base case current loc already visited
              else if (visit[x][y] == true)
                   return false;
              //base case current loc is exit
              else if (x == exitx && y == exity)
                   return true;
              else{
                   visit[x][y] = true;               //mark current location as visited
                   //if there is a path from one of the neighbors then there
                   //is a path from current loc.
                   if (isPath(x-1, y) || isPath(x+1, y) || isPath(x, y-1)
                        || isPath(x, y+1)){
                        return true;
                   else                              //if there are no paths from neighbors
                        return false;               //then there is no path from current loc.
    }tester classimport java.util.Scanner;
    public class MazeTest{
         public static void main(String[] args){
              Scanner sc = new Scanner(System.in);
              System.out.print("enter your file name: ");
              String file = sc.nextLine();
              MazeProblem maze = new MazeProblem(file);
                   if (maze.isPath())
                        System.out.println("Path: " + maze.isPath());
                   else
                        System.out.println("No path present.");
    }when ran at command:
    no. of rows: 4
    no. of cols: 6
    startx = 2
    starty = 1
    exitx = 0
    exity = 4
    1 0 1 1 0 1
    0 0 1 0 0 0
    1 0 1 0 1 0
    0 0 0 0 1 1
    Path: false
    there is an obvious path.
    if I change my tester file to omit the if else portion the program works.
    But I would like to output if there isnt a path available, and can't seem to make that happen.
    the file looks like this:
    4 6
    1 0 1 1 0 1
    0 0 1 0 0 0
    1 0 1 0 1 0
    0 0 0 0 1 1
    2 1
    0 4                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    B_pnzk wrote:
    if (maze.isPath())
    System.out.println("Path: " + maze.isPath());
    else
    // etc
    This bit of the code caught my eye. Since you output is saying "Path: false" how does it ever get to that line given that the condition was if(maze.isPath())?
    It seems to me that you could change the MazeTest main() method so that this oddity doesn't occur. Or - with a little more effort - you could change the MazeProblem class so that it can't occur.

  • Move character through sequence

    Hi, I'm after abit of direction!
    I have a character which sits in a sequence of numbers ('0' and '1') called in from a text file. The character needs to move through the '0's and get on to the other side. The program so far displays the character in amidst the grid of numbers in the DOS window but i'm not sure what I need to do next. How do I get this character 'name' to check whats next to it in order to make a move?
    I just need to know what I need to do i.e. do I use an array or if statement? Do I need to specify something like North, East, South, West and get to do something like grid++ or something to check what comes next? Sorry this may sound a bit vague. I'll try and post the code if I can.
    Thanks.

    Hi,
    I havn't got very far yet but heres the code for the 3 classes I have so far;
    (Most of the maze class has already been written)
    (Please excuse the comments!)
    MAZE:
    import java.io.*;
    import java.util.*;
    import EasyIO.*;
    public class Maze {
    * int number of rows
    private int height;
    * int number of columns
    private int width;
    * enter row for maze. NOTE start counting at 0
    private int startRow;
    * char 2D array to hold the representation of the maze.
    * wall = '1'
    * free = '0'
    private char [][] grid;
    * Maze constructor which gets all the data from a text file.
    * File format:
    * 1st line : height width startRow
    * other lines : rows of maze
    public Maze(String filename)
    String line = "";
    StringTokenizer tokenizer;
    try
    FileReader fr = new FileReader(filename);
    BufferedReader br = new BufferedReader(fr);
    line = br.readLine();
    tokenizer = new StringTokenizer(line);
    height = Integer.parseInt(tokenizer.nextToken());
    width = Integer.parseInt(tokenizer.nextToken());
    startRow = Integer.parseInt(tokenizer.nextToken());
    grid = new char[height][width];
    line = br.readLine();
    int row = 0;
    while (line != null && row < height)
    for (int column = 0; column < line.length() && column < width; column++)
    grid[row][column] = line.charAt(column);
    row++;
    line = br.readLine();
    br.close();
    catch (FileNotFoundException e)
    System.out.println("The file "+filename+" was not found. The following error occurred: "+e);
    EasyIn.pause("Press <Enter> to continue");
    catch (IOException e)
    System.out.println("The file "+filename+" could not be read. The following error occurred: "+e);
    EasyIn.pause("Press <Enter> to continue");
    catch (NumberFormatException e) {
    System.out.println("Error in the first line of the file "+filename+": a number was expected.");
    EasyIn.pause("Press <Enter> to continue");
    public void showMaze()
    for (int i=0;i<grid.length; i++)
    for (int j=0; j<grid.length;j++)
    System.out.print(grid[i][j]);
    System.out.println();
    public void getStartRobot()
    grid[startRow][0]='R';
    public char gridChar(int r, int c)
    return grid[r][c];
    ROBOT:
    import EasyIO.*;
    public class Robot
         //**Attributes**
    private String r; //Enable user to enter name for robot
    private char robot; //Take first letter of the name for robot to use in maze
         private int rowPosition; //Get position in row robot is currently in
         private int columnPosition; //Get position in column the robot is currently in
         //**Methods**
         public Robot();
         String r = new String();
    System.out.println("Enter a name for your Robot:");
    r = EasyIn.getString();
    System.out.println("Hi " + r.toUpperCase());
    EasyIn.pause("Press <Enter>");
    System.out.println("You will now be known as " + r.charAt(0) + "!");
    robot = r.charAt(0);
         EasyIn.pause("Press <Enter> to quit");
              getPosition();
              getNewPosition();
              //not sure about coding below?!
              Right=++
              Left = --
              if (wall=1)     //If wall =1 then turn right
                                  //check if wall is 1 or 0 infront
              {                    //if 0 move forward, else turn right
                   Right;
              else if (wall=0)
    DRIVER:
    import EasyIO.*;
    // call in robot class
    public class Driver
    public static void main (String[]args)
    System.out.println("Enter a maze name: ");
    // String f ="Maze1.txt";
    String f = EasyIn.getString();
    System.out.println();
    System.out.println("This is the maze - ");
    Maze m = new Maze(f); //Code to display maze
    m.showMaze();
    m.getStartRobot();
    System.out.println();
    m.showMaze();
    int r,c;
    r=2;
    c=1;
    m.gridChar(r,c);
    System.out.println("Character at grid position " + r + ", " + c + " is " + m.gridChar(r,c));
    At the moment it reads in a text file which has the maze - the collection of 0 and 1. All it then does is display the maze. And then display again with an R in the first coloumn with first 0.
    Its not reading anything from the Robot class at the moment? It needs to read from this text file file, follow the 0's through to the other side of the maze and out!
    I really need to know What do I do next?!
    Thanks

  • I am being charged for mouse maze games that were supposed to be free, why an i getting billed? see below

    Billed To:
    KATHY ARENA
    USA
    Order Total: $50.70
    Billed To: Visa
    Item
    Seller
    Type
    Unit Price
    Mouse Maze Free Game - by Top Free Games - Best Apps, Dog
    Report a Problem
    Top Free Games
    In-App Purchase
    $6.99
    Mouse Maze Free Game - by Top Free Games - Best Apps, Two Freezing Potions
    Report a Problem
    Top Free Games
    In-App Purchase
    $0.99
    Mouse Maze Free Game - by Top Free Games - Best Apps, Five Nuclear Potions
    Report a Problem
    Top Free Games
    In-App Purchase
    $5.99
    Mouse Maze Free Game - by Top Free Games - Best Apps, Five Super Potions
    Report a Problem
    Top Free Games
    In-App Purchase
    $2.99
    Mouse Maze Free Game - by Top Free Games - Best Apps, Twenty Super Potions
    Report a Problem
    Top Free Games
    In-App Purchase
    $9.99
    Mouse Maze Free Game - by Top Free Games - Best Apps, Twenty Nuclear Potions
    Report a Problem
    Top Free Games
    In-App Purchase
    $19.99
    Subtotal:
    $46.94
    Tax:
    $3.76
    Order Total:
    $50.70
    Please retain for your records.
    Please See Below For Terms And Conditions Pertaining To This Order.
    Apple Inc.
    You can find the iTunes Store Terms of Sale and Sales Policies by launching your iTunes application and clicking on Terms of Sale or Sales Policies
    Answers to frequently asked questions regarding the iTunes Store can be found at http://www.apple.com/support/itunes/store/
    <Personal Information Edited by Host>

    You are getting charged for "In-App" purchases. And yes, those trinkets you purchase within the game are with real $$$$$
    Stedman

  • Win 8.1 taking ownership and making a maze of my system

      Hi,  I am running a surface Pro 3 with win 8.1 I have had to factory reset it once, but now it has these  problems.
    The System has taken ownership of my folders and sub-folders and has been creating a maze of folders. It is replacing files with a desktop.ini fle  and an otherwise empty folder. I am getting access denied pop-ups and false errorrepports.
    question- Now that I have taken ownership of one of thee user  folders, before I do anything else I need to know the answers to the following.
    What do I do about two unknown accounts? they only have traverse, read, and execute as permission. What do I do about inheriting? Should the system have permission to take ownership? And lastly, if I took control specifically with my main account and am
    an Admin, then Admins should be left as can take ownership? (otherwise, If I understand it correctly, it would trump the allow to take ownership permission for me as an admin?) 
    I know I could read up on it in your tutorials, but I  am a senior citizen. and have no patience left, nor the time to plow through all those tech pages and try to figure out what it all means. That is for the next generations. I am fortunate to understand
    as much as I do, and trouble shoot with success. 
    Thank you in advance for your help to whoever has the answers.
    Respectfully,
    sandy

    Hi,
    What kind of folders are you referring to? Different folders can have different owner for different purposes, some system files are access denied by default even you're admin, it is designed for security. It's normal, for example, the "User"
    folder you have mentioned above, the "System" account should be the owner of the folder and you don't need to change it, please see my snapshot below:
    Regarding to the unknown account, my guess is that it’s probably a user account from second OS or
    previous OS that has been removed or recently deleted because of the “format” action. Or if you doubt this, I recommend you run a virus scan incase some virus infection. Please also launch registry editor, then navigate to HKLM\Software\Microosft\Windows
    NT\CurrentVersion\ProfileList check if you can find user SID for the account.
    For inherited permissions, they are those that are propagated to an object from a parent object, I think the following can be more clear than I described
    https://technet.microsoft.com/en-in/library/cc726071.aspx?f=255&MSPPError=-2147217396
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact [email protected]

  • Help with maze program/importing  txt

    Hi everybody
    im having a very hard time figuring out how to program a problem given to me. Im fairly new to java (im more of a c++ kinda guy but we must do this in java.. unfortunately) and the problem states this
    Problem Description
    you will write an application that searches a maze in order to help a trapped mouse find the hidden cheese. The maze can be represented using 4 symbols as follows: 1 represents a wall 0 represents space m represents the initial mouse position c represents the cheese position
    The following is an example input maze:
    111111111111
    101000001001
    1c0000100001
    101111111111
    100111100001
    110111111001
    110000000m11
    111110111101
    111111111111
    Your application must search the maze, starting at the m position, and stops when it reaches the c position. Note that not all mazes have solutions. So, it must also stop if the maze has no solution.
    For simplicity, you may assume the following: the maze is surrounded by 1?s the cheese (c position) can be found anywhere in the maze, except at the border (surrounding 1?s)
    Programming
    Write an application that inputs the maze from the user (Do NOT hardcode the maze in your program), and searches for the c position, starting from the m position.
    Your application must print the updated maze, every time a new position is tried, until a solution is found, or the application discovers that a solution cannot be found.
    Now so far hopefully my logic is correct. We are allowed to input a txt file with any given maze inside the txt file. However, the maze must be a maximum of 100 x 100 but can be any size under that.
    Now first things first.. importing a txt
    heres what i have so far
    public static void main (String [] args){
    Scanner mazefile;
    try {
    Scanner mazefile = new Scanner (new File("maze.txt")); //maze.txt being the txt file with the maze inside it
    catch (FileNotFoundException e){
    System.out.println("Could not Open file");
    return;
    while (mazefile.hasNext());
    String x = inf.nextLine();
    System.out.print(x);
    mazefile.close();
    personally i think this is totally wrong...i cant seem to figure out where to put the bounded so that the maze is a max of 100 by 100 and what happens if the txt is like
    1111111111111
    111c111111111
    1110111111111
    111000m11111
    will the scanner import it into java so its like this?!

    Just use a 2D array of ints, no stack needed.
    int maze[][];
    int maze1[][]=new int[100][100];
    try{
    BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream("maze.txt")));
    String str="";
    int count=0,width=0;
    while((str=reader.readLine())!=null){
        if(str.length()>100)error();
        if(str.length()>width)width=str.length();
        for(int i=0;i<str.length();i++)maze1[count]=Integer.paseInt(""+str.charAt(i));
    count++;
    if(count>=100)error();
    maze=new int[count][max];
    for(int i=0;i<count;i++)for(int j=0;j<max;j++)maze[i][j]=maze1[i][j];
    } catch(Exception ex){}

  • Gerätesteuerung einer Sony MAZ

    Hallo,
    ich möchte gerne Digibetas über eine Sony MAZ und Premiere ingesten. Die MAZ ist via SDI mit dem Rechner verbunden und das läuft auch alles, nur kann ich die MAZ noch nicht vom Computer aus steuern (da eben ein Kabel fehlt). Jetzt wollte ich mal nachfragen, welches Kabel ich benötige.
    Meine bisherigen Ansätzen waren zum einen eine Kabelpeitsche von Blackmagic (sehr teuer) oder die Gerätesteuerung über einen USB-Port am Rechner zu realisieren (funktioniert angeblich am Avid), allerdings weiß ich bei beiden Möglichkeiten nicht ob das funktioniert und möchte auch ungern die teuren Kabel kaufe, um dann festzustellen, dass es nicht klappt. Deswegen wärs super, wenn ihr einen Tipp für mich habt
    Vielen Dank schon mal!
    Mein Setup:
    Mac Workstation
    Blackmagic Karte (Decklink HD Extreme 3)
    Sony DVW-M2000P
    Premiere CC 2014

    Frag einfach einen entsprechenden Technikverleiher und borg's dir erstmal. Die Kablepeitsche muss ja nicht von BMD sein, Hauptsache der richtige Stecker ist dran...
    Mylenium

  • Java 2D Robot Maze

    Can anyone provide some guidance or perhaps a working solution to this problem as I need this very urgently:
    Implement an animation program based on Java 2D which simulates the navigation of a tiled maze by a robot.
    The maze should be splitted into N x N cells (for example 100 x 100 tiles).
    The robot should find the shortest path from any given initial position to any given target position using the A* algorithm.
    The program should show the robot moving from cell to cell.
    I hope this is enough description based on the problem.
    Waiting for your replies...
    I haven't made a progress to start with this assignment so I can't really say anything about what's not working. I do understand what the brief outlines for the project but I can't get the grips on how and where to start and thats my major problem. I hope someone can enlighten me.
    I have looked at several sites that contain bits and pieces but none have the java2d source code.
    This is a great site that states A* Algorithm [pathfinding]:
    http://www.policyalmanac.org/games/aStarTutorial.htm
    This is exactly what I need to do for my assignment but using java2d environment [images clearly show what needs to be done in order to reach destination from the starting point without colliding with the obstacles]. I hope this any help.
    P.S It is very important as I dont have much time left.
    Kind regards

    Its not that I want others to do my work, as I already have some of the code but having to bring it together as a whole [classes] confuses me and it's really depressing me and I thought someone could help me out from this hell hole by guiding or perhaps lending me a hand or two from scratch...
    The site that I quoted earlier on this thread has all the screenshots. Perhaps checking it out will give you some insight of what I really need to do as part of my assignment.
    Kind regards

  • Beginner's frustration: Lost in a maze of boxes, frames, panels...

    Beginner's frustration: Lost in a maze of boxes, frames, panels...
    I was making some progress and feeling good after much frustration and then suddenly I got lost in this deep dark black hole in outerspace.
    1. I have managed to totally mess up all these boxes, frames, panels and cannot figure out how to get back to any resemblance of order. Totally lost in space. How to get back to earth?
    2. And, my video went from running smoothly, to a jerky motion after making various adjustments.
    3. And, somewhere, in the effects, color adjustments, I inserted a 1 second delay in the part that says something about smooth an image or something and I can't find where I was and I want to reset that back to zero. I wonder if that is causing this jerky delay? But, I also noticed it before.
    4. This is the most complicated program I've evern used. I wish they made a beginner's area where I could quickly get into it and make a quick video without getting so lost and frustrated in this massive program.
    Can anyone relate to beginner's frustration?

    Go to any clips with FX and remove them. Delete Key in FX Window)
    Sorry, my windows and everything are so messed up. i don't know where to find the FX window.
    On 2 clips,
    First clip has FX, Opacity:Opacity
    Audio clip with this has FX, Volume Level.
    2nd clip has on video portion, Brightness and Contrast: Contrast.
    On audio portion has Panner: Balance: Level.
    The clip is running rough, jerky.
    The fade in and fade out is rough, jerky.

Maybe you are looking for