Monday, November 5, 2012

Vacuum cleaner Agent ( Java Code )

A Vacuum Cleaner Agent implementation was the project made by my group as a mini-project which was a part of out AI lab work.
Better explanations of  Agents and their types will be available on other sources online. This post is made by me in order to share the code with the view that it can be useful for other students and can be made better by people sitting out there.

Without wasting much time.... here is the code....



import java.lang.Math.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;

/**
 *
 * @author TS
 */
public class vcai extends JFrame implements ActionListener {

    JTextField[][] b = new JTextField[10][10];
    JButton bt;
    //int count;
    int face;//1 u;2 d; 3 l; 4 r
    int i;
    int j;
    int moves;

 
 
    void move() {
        Random rn = new Random();
        int n = 4;
        int nface = Math.abs(rn.nextInt() % n);
     
                    System.out.println(nface);
        switch (face) {
            case 0:
                if (moves%5==0 || i + 1 > 9 || b[i + 1][j].getText().equalsIgnoreCase("o")) {
                    face = nface;
                    System.out.println(nface);
                } else {
                    b[i + 1][j].setText("A");
                    b[i][j].setText("c");
                    i = i + 1;
                }
                    moves=moves+1;
                break;
            case 1:
                if (moves%5==0 || i - 1 < 0 || b[i - 1][j].getText().equalsIgnoreCase("o")) {
                    face = nface;
                    System.out.println(nface);
                } else {
                    b[i - 1][j].setText("A");
                    b[i][j].setText("c");
                    i = i - 1;
                }
                    moves=moves+1;
                break;
            case 2:
                if (moves%5==0 || j - 1 < 0 || b[i][j - 1].getText().equalsIgnoreCase("o")) {
                    face = nface;
                    System.out.println(nface);
                } else {
                    b[i][j - 1].setText("A");
                    b[i][j].setText("c");
                    j = j - 1;
                }
                    moves=moves+1;
                break;
            case 3:
                if (moves%5==0 || j + 1 > 9 || b[i][j + 1].getText().equalsIgnoreCase("o")) {
                    face = nface;
                    System.out.println(nface);
                } else {
                    b[i][j + 1].setText("A");
                    b[i][j].setText("c");
                    j = j + 1;
                }
                    moves=moves+1;
                break;
        }
        if(moves%70==0) {
            JOptionPane.showMessageDialog(this, "step");
        }
    }

    //GroupLayout layout = new GroupLayout(getContentPane());
    //GroupLayout.Group[] g=new GroupLayout.Group[10];
    public vcai() {
        super("vacuum cleaner agent");
        bt = new JButton("Start");
        Container content = this.getContentPane();
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(11, 10));
        for (int i = 0; i < 10; i++) {
            //g[i]=layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup());
            for (int j = 0; j < 10; j++) {
                b[i][j] = new JTextField();
                //b[i][j].setLocation((i*10)+10, (j*10)+10);
                panel.add(b[i][j], j);
            }
        }
        bt.addActionListener(this);
        content.add(new JLabel("A: Agent ; o: obstacle ; *: dirt"), BorderLayout.PAGE_END);
        content.add(bt, BorderLayout.AFTER_LINE_ENDS);
        content.add(panel);
        //getContentPane().setLayout(layout);
        //  pack();
        this.setSize(360, 400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    @Override
    public void actionPerformed(ActionEvent be) {
        if (be.getActionCommand().equals(bt.getLabel())) {
            //System.out.println("this");
            placeAgent();
            //slp(5000);
            face = 3;
            int l[] = new int[2];
            i = l[0];
            j = l[1];
            moves=1;
            while (true) {
                move();
            }
        }
    }

    void placeAgent() {
        outerloop:
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                if (b[i][j].getText().equalsIgnoreCase("")) {
                    b[i][j].setText("A");
                    break outerloop;
                }
            }
        }
    }


    int[] aloc() {
        int l[] = {0, 0};
        outerloop:
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                if (b[i][j].getText().equalsIgnoreCase("A")) {
                    l[0] = i;
                    l[1] = j;
                    break outerloop;
                }
            }
        }
        return l;
    }

    public static void main(String[] args) {
        new vcai().setVisible(true);
    }
}


The project was made using java swing. The screenshots are given below.



The main idea behind the agent is to make it traverse through the whole room. Better implementations may be available for solving situations like a "cave created by obstacles" and "linear arrangement of obstacles" , but the approach used here is fairly simple. 

APPROACH: A random direction is chosen every five moves. This will overcome the problem of the agent getting stuck in a corner inside the cave of obstacles. The "five" moves are selected because the room is 10*10. a halfway number generally gives better results. 
Other assumptions are that the "o" in the textbox is an obstacle, "*" is dirt, "A" is agent, "c" is the traversed area.

SHORTCOMINGS: The implementation does not show the stepwise movement of the agent. A messagebox is displayed  every 70 moves to see the area traversed in the interim. 
There is no better way of stopping the program, except for the "STOP" option in netbeans (yes... it is made in netbeans).

Above are a few of the many shortcomings of the implementation.

DO HELP IMPROVE THE CODE AND HAVE BETTER IMPLEMENTATIONS. 

I declare that you are free to use the code and make changes to it but, this should not be used in a commercial manner, ie to make profit.


12 comments:

  1. please I don't understand your work .. can you help me to understand it please :)

    ReplyDelete
    Replies
    1. Running the code once can give little clear picture of the working. I will be glad to help, if you can please point out at the part of code or working you don't understand.
      Note: the code keeps on running till you forcefully stop it. a little bit of laziness displayed there while coding. :P
      Anyways, Thanks for the reply :)

      Delete
  2. why the code keeps running without stop!
    it doesn't give a result , I know that vacuum program should stop to give me the movements that vacuum made during cleaning
    thank you very much for replying

    ReplyDelete
    Replies
    1. in the move function change
      if(moves%70==0) {
      JOptionPane.showMessageDialog(this, "step");
      }
      to
      if(moves%1==0) {
      JOptionPane.showMessageDialog(this, "step");
      }

      doing that will allow you to watch the movement at each step. here the no. after '%' symbol is the no. of steps taken by the agent after which a message box will appear. the whole intention behind adding this is to get the area traversed by the agent during these steps.

      the reason why the code wont stop running is bad coding :P ... actually my project had very basic requirements and so, i did not feel the need to add a button or function that would 'stop' the Agent. I ran the code in Netbeans IDE and used the stop button available on the left of the output window. You can make changes to it and maybe add a stop button or function.
      hope the answer is helpful.. you can always write back and i will be happy to reply :)

      Delete
    2. #java hi all #Help for the Question below : Simple Cognitive Agent Consider a squared room (n*n squares grid) and a cognitive agent, which has to collect all the objects from the room. In the room there are at most n2/3 objects and at most n obstacles. The agent can perform the same actions as the agent from the previous exercise. As opposed to the agent from the previous exercise, now the agent has memory. At each step of the environment’s (discreet) time, the agent can perform one of the following actions: move forward, move left, move right, and pick an object. The agent has sensors and can perceive if any of the adjacent cells is an obstacle. The agent can perceive if the current cell has an object to be picked. The agent is notified by the environment when there are no more objects in the room. The agent has a compass, so it knows its orientation. The agent has a means of storage for information, of theoretically unlimited size, but the quantity of information stored affects the points system. The quantity of information is measured by the agent in integers (ints). Points system: One operation consumes 1 point. The reward for picking an object is 10 points. The usage of one int per time step consumes 0.1 points. Note: It is mandatory that the agent has a means to correctly measure the quantity of useful information that it holds, regardless of the data structure that it uses to store it. Implement the cognitive agent that can solve the problem and have a maximum number of points at the end. Implement a means of visualization of the grid and of the agent’s position and orientation. A JFrame/JPanel window is preferred. thanks for all.

      Delete
  3. It is unlawful to lend your vacuum cleaner to your next-door neighbor; It is illegal to mistreat rats; You may not drive a black car on Sundays. vacuum101

    ReplyDelete
  4. I'd like your help please on the topic, I already approached you on Twitter! Please respond to me as soon as you can.
    Thank you!

    ReplyDelete
  5. #java hi all #Help for the Question below : Simple Cognitive Agent Consider a squared room (n*n squares grid) and a cognitive agent, which has to collect all the objects from the room. In the room there are at most n2/3 objects and at most n obstacles. The agent can perform the same actions as the agent from the previous exercise. As opposed to the agent from the previous exercise, now the agent has memory. At each step of the environment’s (discreet) time, the agent can perform one of the following actions: move forward, move left, move right, and pick an object. The agent has sensors and can perceive if any of the adjacent cells is an obstacle. The agent can perceive if the current cell has an object to be picked. The agent is notified by the environment when there are no more objects in the room. The agent has a compass, so it knows its orientation. The agent has a means of storage for information, of theoretically unlimited size, but the quantity of information stored affects the points system. The quantity of information is measured by the agent in integers (ints). Points system: One operation consumes 1 point. The reward for picking an object is 10 points. The usage of one int per time step consumes 0.1 points. Note: It is mandatory that the agent has a means to correctly measure the quantity of useful information that it holds, regardless of the data structure that it uses to store it. Implement the cognitive agent that can solve the problem and have a maximum number of points at the end. Implement a means of visualization of the grid and of the agent’s position and orientation. A JFrame/JPanel window is preferred. thanks for all.

    ReplyDelete
  6. import java.lang.reflect.Array;
    import java.util.ArrayList;
    import java.util.List;

    /*
    * To change this license header, choose License Headers in Project Properties.
    * To change this template file, choose Tools | Templates
    * and open the template in the editor.
    */

    /**
    *
    * @author
    */
    public class NewClass {
    java.util.List row = new ArrayList();
    java.util.List column = new ArrayList();
    //int pos[][] ;
    int r;
    int c;
    //List> pos = new ArrayList>();
    public boolean finder(int ObsticleX, int ObsticleY )

    {


    row.add(6);
    row.add(3);
    column.add(5);
    column.add(7);
    boolean first= false;
    boolean second = false;

    boolean found = false;

    for (int r = 0; r<row.size();r++)
    {
    if (row.get(r) ==3 && column.get(r)==7)
    {//System.out.println(row.get(r)+" "+column.get(c));
    first= true;
    second = true;}else{ first = false;System.out.println("First = "+first);}
    // for(int c = 0; c<column.size();c++)
    // {
    // if ( column.get(r)==ObsticleY)
    // {//System.out.println(row.get(r)+" "+column.get(c));
    // second=true;}else {second = false;System.out.println("Second = "+second);}
    // }

    }

    if (first && second )
    {
    found = true;
    System.out.println("found point "+row.get(r)+", "+column.get(r));
    }else{ found = false;
    System.out.println("found"+row.get(r)+" "+column.get(c));
    }


    System.out.println(found);
    return found;
    }}//}

    ReplyDelete