Banner

Fachhochschule Wiesbaden
Fachbereich Informatik

KI


Sven Eric Panitz

Startseite zurück Inhaltsverzeichnis


Kapitel 1 Programme

A.1 Listenhilfsfunktionen

Box.scala
package name.panitz.eliza
case class Box[a](var x:a){}

Util.scala
package name.panitz.eliza;
object Util{
  def rotate[a](xs:Box[List[a]])
   =xs.x=(xs.x.tail ::: (List(xs.x.head)))

  def isPrefix[a](xs:List[a],ys:List[a]):Boolean
   = if (xs.isEmpty) true 
     else if (ys.isEmpty) false
     else xs.head==ys.head && isPrefix(xs.tail,ys.tail)

  def unwords[a](xs:List[a]):String
   = if (xs.isEmpty) ""
     else if (xs.tail.isEmpty) xs.head.toString()
     else xs.head.toString()+" "+unwords(xs.tail)

  def tails[a](xs:List[a]):List[List[a]]
   =if (xs.isEmpty) List(xs) else tails(xs.tail).::(xs)

  def  words (s:String):List[String]={
    var s1 = s.trim()
    var i = s1.indexOf(' ')
    if (i<0) List(s1)
    else words(s1.substring(i)) .:: (s1.substring(0,i))
  } 
 
 def stripPunctuation(s:String): String={
    var result="";
    for (val i<-Iterator.range(0,s.length())){
      if (PUNCTUATIONS.indexOf(s.charAt(i))<0){
        result=result+s.charAt(i);
      }else{}      
    }
    result
  }
  val PUNCTUATIONS =".,;:!"

  def trace[a](s :String,x:a):a={Console.print(s+": ");Console.println(x);x}
}

A.2 Eliza

Data.scala
package name.panitz.eliza;
import scala.collection.mutable.{_}
class Data {
  type Answers=Box[Words]
  type Words=List[String]

  val CONJUGATES:Map[String,String]  = new HashMap()
  CONJUGATES.update("ME","you")
  CONJUGATES.update("ARE","am")
  CONJUGATES.update("WERE","was")
  CONJUGATES.update("YOU","I")
  CONJUGATES.update("YOUR","my")
  CONJUGATES.update("I'VE","you've")
  CONJUGATES.update("I'M","you're")
  CONJUGATES.update("AM","are")
  CONJUGATES.update("WAS","were")
  CONJUGATES.update("I","you")
  CONJUGATES.update("MY","your")
  CONJUGATES.update("YOU'VE","I've")
  CONJUGATES.update("YOU'RE","I'm")

  val repeatMsgs :Answers    
    =Box(
      List( "Why did you repeat yourself?"
          , "Do you expect a different answer by repeating yourself?"
          , "Come, come, elucidate your thoughts."
          , "Please don't repeat yourself!" ))
  val nokeyMsgs
   =Box(
      List( "I'm not sure I understand you fully."
          , "What does that suggest to you?"
          , "I see."
          , "Can you elaborate on that?"
          , "Say, do you have any psychological problems?") )
  val canYou
   =Box(
      List( "?Don't you believe that I can"
          , "?Perhaps you would like to be able to"
          , "?You want me to be able to" ))
  val canI
    =Box(
      List( "?Perhaps you don't want to"
          ,"?Do you want to be able to" ))
  val youAre
    =Box(
      List( "?What makes you think I am"
          , "?Does it please you to believe I am"
          , "?Perhaps you would like to be"
          , "?Do you sometimes wish you were"))
  val iDont
    =Box(
      List( "?Don't you really"
          , "?Why don't you"
          , "?Do you wish to be able to"
          , "Does that trouble you?"))
  val iFeel	   
    =Box(
      List( "Tell me more about such feelings."
          , "?Do you often feel"
          , "?Do you enjoy feeling"))
  val whyDont  
    =Box(
      List( "?Do you really believe I don't"
          , ".Perhaps in good time I will"
          , "?Do you want me to"))
  val whyCant
    =Box(
      List( "?Do you think you should be able to"
          , "?Why can't you"))
  val areYou
    =Box(
      List( "?Why are you interested in whether or not I am"
          , "?Would you prefer if I were not"
          , "?Perhaps in your fantasies I am"))
  val iCant
    =Box(
      List( "?How do you know you can't"
          , "Have you tried?"
          , "?Perhaps you can now"))
  val iAm	    
    =Box(
      List( "?Did you come to me because you are"
          , "?How long have you been"
          , "?Do you believe it is normal to be"
          , "?Do you enjoy being"))
  val you	     
    =Box(
      List( "We were discussing you --not me."
          , "?Oh,"
          , "You're not really talking about me, are you?" ))
  val yes
    =Box(
      List( "You seem quite positive."
          , "Are you Sure?"
          , "I see."
          , "I understand."))
  val no
    =Box(
      List( "Are you saying no just to be negative?"
          , "You are being a bit negative."
          , "Why not?"
          , "Are you sure?"
          , "Why no?"))
  val computer
    =Box(
      List( "Do computers worry you?"
          , "Are you talking about me in particular?"
          , "Are you frightened by machines?"
          , "Why do you mention computers?"
          , "What do you think machines have to do with your problems?"
          , "Don't you think computers can help people?"
          , "What is it about machines that worries you?" ))
  val problem
    =Box(
      List( "Is this really a poblem?"
          , "Don't you see any solution to this?"
          , "Is this your only problem?"
          , "Has this always been a problem?"))
  val iWant
    =Box(
      List( "?Why do you want"
          , "?What would it mean to you if you got"
          , "?Suppose you got"
          , "?What if you never got"
          , ".I sometimes also want"))
  val question
    =Box(
      List( "Why do you ask?"
          , "Does that question interest you?"
          , "What answer would please you the most?"
          , "What do you think?"
          , "Are such questions on your mind often?"
          , "What is it that you really want to know?"
          , "Have you asked anyone else?"
          , "Have you asked such questions before?"
          , "What else comes to mind when you ask that?" ))
  val name
    =Box(
      List( "Names don't interest me."
          , "I don't care about names --please go on."))
  val because
    =Box(
       List( "Is that the real reason?"
           , "Don't any other reasons come to mind?"
           , "Does that reason explain anything else?"
           , "What other reasons might there be?" ))
  val sorry	
    =Box(
      List( "Please don't apologise!"
          , "Apologies are not necessary."
          , "What feelings do you have when you apologise?"
          , "Don't be so defensive!" ))
  val dream
    =Box(
      List( "What does that dream suggest to you?"
          , "Do you dream often?"
          , "What persons appear in your dreams?"
          , "Are you disturbed by your dreams?" ))
  val hello
    =Box( List( "How do you...please state your problem."))

  val maybe
    = Box(List( "You don't seem quite certain."
          , "Why the uncertain tone?"
          , "Can't you be more positive?"
          , "You aren't sure?"
          , "Don't you know?" ))
  val your
    = Box(
       List( "?Why are you concerned about my"
          , "?What about your own"))
  val always
    =Box(
      List( "Can you think of a specific example?"
          , "When?"
          , "What are you thinking of?"
          , "Really, always?"))
  val think
    =Box(
      List( "Do you really think so?"
          , "?But you are not sure you"
          , "?Do you doubt you"))
  val alike
    =Box(
      List( "In what way?"
          , "What resemblence do you see?"
          , "What does the similarity suggest to you?"
          , "What other connections do you see?"
          , "Cound there really be some connection?"
          , "How?" ))
  val friend
    =Box(
      List( "Why do you bring up the topic of friends?"
          , "Do your friends worry you?"
          , "Do your friends pick on you?"
          , "Are you sure you have any friends?"
          , "Do you impose on your friends?"
          , "Perhaps your love for friends worries you."))

 val responses:List[Pair[Words,Answers]]
  = List[Pair[Words,Answers]](
       Pair(List("CAN","YOU"),          canYou)
      ,Pair(List("CAN","I"),		canI)
      ,Pair(List("YOU","ARE"),		youAre)
      ,Pair(List("YOU'RE"),		youAre)
      ,Pair(List("I","DON'T"),		iDont)
      ,Pair(List("I", "DON", "NOT"),	iDont)
      ,Pair(List("I", "FEEL"),		iFeel)
      ,Pair(List("WHY", "DON'T", "YOU"),whyDont)
      ,Pair(List("WHY", "CAN'T", "I"),	whyCant)
      ,Pair(List("ARE", "YOU"),		areYou) 
      ,Pair(List("I", "CAN'T"),		iCant)
      ,Pair(List("I", "CANNOT"),	iCant)
      ,Pair(List("I", "AM"),		iAm)
      ,Pair(List("I'M"),		iAm)
      ,Pair(List("YOU"), 		you)
      ,Pair(List("YES"),		yes)
      ,Pair(List("NO"),			no)
      ,Pair(List("I", "HAVE", "A", "PROBLEM"),	problem)
      ,Pair(List("I'VE", "A", "PROBLEM"),	problem)
      ,Pair(List("PROBLEM"),    	problem)
      ,Pair(List("COMPUTER"),		computer)
      ,Pair(List("COMPUTERS"),		computer)
      ,Pair(List("I", "WANT"),		iWant)
      ,Pair(List("WHAT"),		question)
      ,Pair(List("HOW"),		question)
      ,Pair(List("WHO"),		question)
      ,Pair(List("WHERE"),		question)
      ,Pair(List("WHEN"),		question)
      ,Pair(List("WHY"),		question)
      ,Pair(List("NAME"),		name)
      ,Pair(List("BECAUSE"),		because)
      ,Pair(List("CAUSE"),		because)
      ,Pair(List("SORRY"),		sorry)
      ,Pair(List("DREAM"),		dream)
      ,Pair(List("DREAMS"),		dream)
      ,Pair(List("HI"),			hello)
      ,Pair(List("HELLO"),		hello)
      ,Pair(List("MAYBE"),		maybe)
      ,Pair(List("YOUR"),		your)
      ,Pair(List("ALWAYS"),		always)
      ,Pair(List("THINK"),		think)
      ,Pair(List("ALIKE"),		alike)
      ,Pair(List("FRIEND"),		friend)
      ,Pair(List("FRIENDS"),		friend)
      ,Pair(List(),			nokeyMsgs))
}

A.3 GUI für Schiebepuzzle

SlidePanel.scala
package name.panitz.ki
import javax.swing.{_}
class SlidePanel(p:InformedSlide) extends JPanel{
  var puzzle=p
  val chipSize=50

  addMouseListener(new Mousy())
  add (new BoardPanel())

  val button=new JButton("depth search")
  add(button)

  import java.awt.event.{_}
  button.addActionListener(new ActionListener(){
    override def actionPerformed(ev:ActionEvent)=
      performMoves (()=>puzzle depthSearch 10)
  })

  val button2=new JButton("breadth search")
  add(button2)
  button2.addActionListener(new ActionListener(){
    override def actionPerformed(ev:ActionEvent)=
      performMoves (puzzle.breadthFirst)
  })

  val button3=new JButton("deepening")
  add(button3)
  button3.addActionListener(new ActionListener(){
    override def actionPerformed(ev:ActionEvent)=
      performMoves (puzzle.deepening)
  })

  val button4=new JButton("A*")
  add(button4)
  button4.addActionListener(new ActionListener(){
    override def actionPerformed(ev:ActionEvent)=
      performMoves (puzzle.aStar)
  })

  def performMoves(ms:()=>List[Direction.Value])={
    import name.panitz.swing.SwingWorker
    val worker = new SwingWorker() {
     override def construct():Object= { 
      for (val m<-ms()) {
        Thread.sleep(500);puzzle=puzzle.move(m);repaint()
      }
      puzzle
     }
    }
    worker.start()
  }

  class BoardPanel extends JPanel{
   override def getPreferredSize():java.awt.Dimension
    =new java.awt.Dimension(chipSize*puzzle.SIZE,chipSize*puzzle.SIZE)

   override def  paintComponent(g:java.awt.Graphics)={
    import java.awt.Color.{_}
    super.paintComponent( g)
    for (val r<-Iterator.range(0,puzzle.SIZE)){      
      for (val c<-Iterator.range(0,puzzle.SIZE)){
	if (puzzle.field(c)(r)==0){
          g setColor WHITE
          g.fillRect(r*chipSize,c*chipSize,chipSize,chipSize)
	}else{
          g setColor RED
          g.fillRect(r*chipSize,c*chipSize,chipSize,chipSize)
          g setColor BLACK
          g.drawString(puzzle.field(c)(r).toString
                      ,r*chipSize+chipSize/2,c*chipSize+chipSize/2)
	}
      }
    }
    g setColor DARK_GRAY
    for (val r<-Iterator.range(0,puzzle.SIZE+1))
      g.fillRect(0,r*chipSize-5/2,chipSize*puzzle.SIZE,5)
    for (val c<-Iterator.range(0,puzzle.SIZE+1))
      g.fillRect(c*chipSize-5/2,0,5,chipSize*puzzle.SIZE)
   }
  }

  class Mousy extends MouseAdapter{
    override def mouseClicked(ev:MouseEvent)={
      val x = ev.getX()/chipSize
      val y = ev.getY()/chipSize

      if (x>0&& ((puzzle.field(y)(x-1))==0))
        puzzle=puzzle.move(Direction.Left)
      else if (x<puzzle.SIZE-1&&puzzle.field(y)(x+1)==0) {
        puzzle=puzzle.move(Direction.Right)
      }
      else if (y>0&&puzzle.field(y-1)(x)==0)
        puzzle=puzzle.move(Direction.Up)
      else if (y<puzzle.SIZE-1&&puzzle.field(y+1)(x)==0)
        puzzle=puzzle.move(Direction.Down)
      repaint()
    }
  }
}

SlideGUI.scala
package name.panitz.ki
object SlideGUI extends Application{
  val board=new SlidePanel(new InformedSlide(3))
  val frame=new javax.swing.JFrame()
  frame.add(board)
  frame.pack()
  frame.setVisible(true)
}

A.4 Sudoku Gui

SudokuPanel.scala
package name.panitz.ki
import javax.swing.{_}
class SudokuPanel extends JPanel{
  setLayout(new java.awt.GridLayout(9,9)) 
  val grids = new Array[Array[JSpinner]](9)
  for (val r<-Iterator.range(0,9))
    grids(r)= new Array[JSpinner](9)

  for (val r<-Iterator.range(0,9);val c<-Iterator.range(0,9)){
    grids(r)(c)=new JSpinner(new SpinnerNumberModel(0,0,9,1)) 
    add(grids(r)(c))
  }
}

PlaySudoku.scala
package name.panitz.ki
object PlaySudoku extends Application {
  import javax.swing.{_}
  import java.awt.event.{_}
  val f=new JFrame()
  val pp=new JPanel()
  val p=new SudokuPanel()
  f add pp
  val b=new JButton("solution")
  val rb=new JButton("reset")
  pp add b
  pp add p
  b.addActionListener(
    new ActionListener(){
      def actionPerformed(ev:ActionEvent)={
        var sud=new Sudoku()
        for (val r<-Iterator.range(0,9);val c<-Iterator.range(0,9)){
          sud=sud.move(Tuple(r,c
               ,p.grids(r)(c).getValue.asInstanceOf[java.lang.Integer].intValue))
        }
        val solution=sud.depthSearch
        for (val s<-solution) sud=sud move s
	for (val r<-Iterator.range(0,9);val c<-Iterator.range(0,9)){
          p.grids(r)(c).setValue(new java.lang.Integer(sud.field(r)(c)))
        }
        f.repaint}})
  rb.addActionListener(
    new ActionListener(){
      def actionPerformed(ev:ActionEvent)={
	for (val r<-Iterator.range(0,9);val c<-Iterator.range(0,9)){
          p.grids(r)(c).setValue(new java.lang.Integer(0))
        }
        f.repaint}})
  pp add rb
  f.pack
  f setVisible true
}

A.5 Swing Worker

SwingWorker.java
package name.panitz.swing;
import javax.swing.SwingUtilities;

/**
 * This is the 3rd version of SwingWorker (also known as
 * SwingWorker 3), an abstract class that you subclass to
 * perform GUI-related work in a dedicated thread.  For
 * instructions on using this class, see:
 * 
 * http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
 *
 * Note that the API changed slightly in the 3rd version:
 * You must now invoke start() on the SwingWorker after
 * creating it.
 */
public abstract class SwingWorker {
    private Object value;  // see getValue(), setValue()
    private Thread thread;

    /** 
     * Class to maintain reference to current worker thread
     * under separate synchronization control.
     */
    private static class ThreadVar {
        private Thread thread;
        ThreadVar(Thread t) { thread = t; }
        synchronized Thread get() { return thread; }
        synchronized void clear() { thread = null; }
    }

    private ThreadVar threadVar;

    /** 
     * Get the value produced by the worker thread, or null if it 
     * hasn't been constructed yet.
     */
    protected synchronized Object getValue() { 
        return value; 
    }

    /** 
     * Set the value produced by worker thread 
     */
    private synchronized void setValue(Object x) { 
        value = x; 
    }

    /** 
     * Compute the value to be returned by the <code>get</code> method. 
     */
    public abstract Object construct();

    /**
     * Called on the event dispatching thread (not on the worker thread)
     * after the <code>construct</code> method has returned.
     */
    public void finished() {
    }

    /**
     * A new method that interrupts the worker thread.  Call this method
     * to force the worker to stop what it's doing.
     */
    public void interrupt() {
        Thread t = threadVar.get();
        if (t != null) {
            t.interrupt();
        }
        threadVar.clear();
    }

    /**
     * Return the value created by the <code>construct</code> method.  
     * Returns null if either the constructing thread or the current
     * thread was interrupted before a value was produced.
     * 
     * @return the value created by the <code>construct</code> method
     */
    public Object get() {
        while (true) {  
            Thread t = threadVar.get();
            if (t == null) {
                return getValue();
            }
            try {
                t.join();
            }
            catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // propagate
                return null;
            }
        }
    }


    /**
     * Start a thread that will call the <code>construct</code> method
     * and then exit.
     */
    public SwingWorker() {
        final Runnable doFinished = new Runnable() {
           public void run() { finished(); }
        };

        Runnable doConstruct = new Runnable() { 
            public void run() {
                try {
                    setValue(construct());
                }
                finally {
                    threadVar.clear();
                }

                SwingUtilities.invokeLater(doFinished);
            }
        };

        Thread t = new Thread(doConstruct);
        threadVar = new ThreadVar(t);
    }

    /**
     * Start the worker thread.
     */
    public void start() {
        Thread t = threadVar.get();
        if (t != null) {
            t.start();
        }
    }
}