201311011245


    Java programming is mostly about writing classes [1].

Kavas katsetada Alice3 ning Alice2Netbeans plugin (alice.org), ning algajate kool: plokk, funktsioon, objekt. Ülejärgmisel korral algajate kooli raamides alustame teemat "flow control" Raptori [2] abil.


Funktsioone pole
----------------

Sõnal funktsioon on programmeerimises erakorraline tähtsus: Bobby programmeerib LISP keeles (funksionaalkeel) ning arvab, et ei midagi tähtsamat polegi olemas. Java programmeerija Alice peab lugu veel muutujatest, mida Bob põlglikult nimetab "side effects". 

Toas, kus elab Alice on erinev mööbel -- laud, tool, kaks kappi, diivan, raamaturiiul. Bob elab tühjas toas, kus võib magada põrandal madratsil lahti riietamata. Tõstame kõik Alice'i asjad mööblist välja ning viime nad Bobby tuppa. See on nagu kood, kus pole ühtegi funktsiooni.


Ma tahan ka niimoodi
--------------------

Kõik, mis elab, õpib jäljendades. Peale selle inimene oskab analüüsida (lahata), sünteesida (panna kokku juppidest), konserveerida teadmisi (kirjatöödes), ning palju muud.

Ülesannete kogu (taskbook), kus kõik ülesanded on lahendatud ning lahendused pandud kirja, nimetatakse spikriks. Kui me ei taha, et selline raamat eksisteeriks, ülesandeid peab olema väga palju, ning igaüks nendest ei tohi olla robotile arusaadav [3]. 


Harjutused
----------

Lisades toodud harjutused on mõeldud eelkõige selleks, et selgeks teha greenfoot projekti koostamise ning kompileerimise faas. Lisada oma kood tuleb // vvv ning // ^^^ ridade vahele, mis teeb projektid mugavaks aluseks algajale õppimiseks.


Plays (Scenarios)
-----------------

Zeppelin-game  Appendix A.
Puppet-show interpreter.
Expression Generator.
Expression Solver [4].
HexViewer [5].


Links
-----

[1]. http://env3d.org/beta/node/25
[2]. http://raptor.martincarlisle.com/
[3]. http://www.3dnews.ru/773026
[4]. http://udojava.com/2012/12/16/java-expression-parser-evaluator/
[5]. http://www.gubatron.com/blog/2009/04/18/how-to-make-your-own-quick-dirty-hex-file-viewer-in-java/
[6]. http://www.greenfoot.org/scenarios/7435

------------------------------------------------------------------------

Appendix A. Zeppelin Game.

Fundamentals

    Do it the hard way -- predict the future beeing inside feedback loop.
    
One may take the path "from simple to complicated":

  atoms -- molecules -- ... proteins -- ... functioning human brain

We'll never rich the right side of this list, i promise, it's too long to go alone*. We'll sink instead. Because the way on the surface is the shortest, diving is needed only to satisfy our curiosity.. or to get the magic crystal of ready-to-use-knowledge in case nobody was left it into teleport-cabine*. A reasonable degree of risk can be achieved by using robots (intelligent probe) for certain type of adventures.

*) Game Scenario

Fortunately, in case of programming this way is magic -- it's easy to split the whole way apart. It's water there, so first we need to learn how to swim. Each piece can't be passed without a crystal, and we have only one crystal on the left coast. New crystal may be found on the bottom of the sea -- in this case it have to be left to the teleport-cabine otherwise it dissapears on the next piece of the path. Diving takes usually significant part of the lifetime, so we may not reach the right coast (starting from the left one) before our life ends.

Code: Greenfoot

  Pig

  import greenfoot.*;

  public class Pig extends Actor {
      public void act() {
          if ( canMove()) move();
      }
      
      public void move()  {
          if ( !canMove()) return;
          setLocation(getX() + 1, getY());
      }

      public boolean canMove() {
          World myWorld = getWorld();
          int x = getX();
          int y = getY();
          int w = myWorld.getWidth();
          int h = myWorld.getHeight();
          x++;
          if ( x >= w / 2) setImage("fish.png");
          if (x >= w || y >= h) return false;
          else if (x < 0 || y < 0) return false;
          return true;
      }
  }


  Crystal

  import greenfoot.*;

  public class Crystal extends Actor {
      public void act() {
      }    
  }

------------------------------------------------------------------------

Appendix B. Hello World

import greenfoot.*;

public class SevenWorld extends World {
  public static final int COLS7 = 17;
  public static final int ROWS7 = 7;
  
  public static final int X7INIT = 50;
  public static final int X7STEP = 55;
  public static final int Y7INIT = 75;
  public static final int Y7STEP = 105;
    
  public int x = 0;
  public int y = 0;

  public SevenWorld() {    
      super(1024, 768, 1);
  // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
      print7("Hello World " +
             "0123456789 " + 
             "ABCDEFGHIJKLMNOPQRSTUVWXYZ " + 
             "abcdefghijklmnopqrstuvwxyz" + 
             "The quick brown fox jumps over the lazy dog");
  // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
  
  public void print7(String as) {
      int total = as.length() > COLS7 * ROWS7 ?  COLS7 * ROWS7 : as.length();
      for (int i=0; i<total; i++) {
          addObject( new SevenSeg(as.charAt(i)), X7INIT + X7STEP * x, Y7INIT + Y7STEP * y);
          x = (x >= COLS7 - 1) ? 0 : x + 1; y = (x == 0) ? y + 1 : y;
      }
  }
}


SevenSeg.java

import greenfoot.*;
import java.awt.Color;

public class SevenSeg extends Actor
{
  //    00       -- 
  //   5  1     |  |
  //    66       --
  //   4  2     |  |
  //    33       -- 
  // 
  //    00       --       22       33       --       55       66       77      
  //   0  0     |  1     |  2     |  3     4  4     5  |     6  |     |  7     
  //    --       --       22       33       44       55       66       --      
  //   0  0     |  1     2  |     |  3     |  4     |  5     6  6     |  7     
  //    00       --       22       33       --       55       66       --      
  //  
  // 01111110 00001100 10110110 10011110 11001100 11011010 11111010 00001110
  // 7e       0c       b6       9e       cc       da       fa       0e      
  // 
  //    88       99       AA       --       cc       --       EE       FF   
  //   8  8     9  9     A  A     b  |     c  |     |  d     E  |     F  |  
  //    88       99       AA       bb       --       dd       EE       FF   
  //   8  8     |  9     A  A     b  b     c  |     d  d     E  |     F  |  
  //    88       99       --       bb       cc       dd       EE       --   
  //                                                                        
  // 11111110 11011110 11101110 11111000 01110010 10111100 11110010 11100010 
  // fe       de       ee       f8       72       bc       f2       e2     
  // 
  //    GG       --       ii       jj       --       --       --       --   
  //   G  |     h  |     |  |     |  |     K  K     l  |     M  M     |  |  
  //    --       hh       --       --       KK       --       --       nn   
  //   G  G     h  h     i  |     |  j     K  K     l  |     M  M     n  n  
  //    GG       --       ii       jj       --       ll       --       --   
  //                                                                        
  // 01111010 11101000 00110010 00011010 11101100 01110000 01101100 10101000 
  // 7a       e8       32       1a       ec       70       6c       a8     
  // 
  //    --       pp       qq       --       --       --       --       --   
  //   |  |     p  p     q  q     |  |     s  |     t  |     u  u     |  |  
  //    oo       pp       qq       rr       ss       tt       --       --   
  //   o  o     p  |     |  q     r  |     |  s     t  |     u  u     v  v  
  //    oo       --       --       --       ss       tt       uu       vv   
  //                                                                        
  // 10111000 11100110 11001110 10100000 11011000 11110000 01111100 00111000 
  // b8       e6       ce       a0       d8       f0       7c       38     
  // 
  //    --       --       --       zz       --       --       --   
  //   w  w     |  |     y  y     |  |     |  |     |  |     |  |  
  //    ww       --       yy       zz       --       --       ==   
  //   w  w     x  x     |  y     |  |     |  |     |  |     |  |  
  //    ww       --       yy       zz       --       ..       --   
  //                                                               
  // 11111100 00101000 11011100 10010010 00000000 00010000 10000000
  // fc       28       dc       f8       00       10       80

  int[] i2c = { 0x7e, 0x0c, 0xb6, 0x9e, 0xcc, 0xda, 0xfa, 0x0e, 
                0xfe, 0xde, 0xee, 0xf8, 0x72, 0xbc, 0xf2, 0xe2,
                0x7a, 0xe8, 0x32, 0x1a, 0xec, 0x70, 0x6c, 0xa8,
                0xb8, 0xe6, 0xce, 0xa0, 0xd8, 0xf0, 0x7c, 0x38,
                0xfc, 0x28, 0xdc, 0x92, 0x00, 0x10, 0x80 };

  int count = 0;
  GreenfootImage img;
  
  public SevenSeg() {
      // img = new GreenfootImage( 50, 100 );
      // setImage( img); // ONLY IF NO STATIC IMAGE IS SET IN GUI
  }
  
  public SevenSeg( char a) {
      img = new GreenfootImage( 50, 100 );
      Pa( char2seg( a));
  }
  
  public int char2seg( char a) {
      int ch = 36;
      int c = (int) a;
      if ((int)'0' <= c && c <= (int)'9') ch = c - (int)'0';
      if ((int)'a' <= c && c <= (int)'z') ch = c -(int)'a' + 10;
      if ((int)'A' <= c && c <= (int)'Z') ch = c - (int)'A' + 10;
      if (a == '.') ch = 37;
      if (a == '-') ch = 38;
      return i2c[ ch];
  }
  
  public void Pa(int acount) {
      setImage( img);

      img.clear();
      img.setColor( new Color( 0, 0, 0));
      img.fill();
      img.setColor( Color.GREEN);

      if ((acount & 0x02) != 0) {
          int[] x7 = {6, 16, 35, 45};
          int[] y7 = {5, 15, 15, 5};
          img.fillPolygon( x7, y7, 4);
      }

      if ((acount & 0x04) != 0) {
          int[] x6 = {37, 47, 47, 37};
          int[] y6 = {17, 7, 48, 39};
          img.fillPolygon( x6, y6, 4);
      }
      
      if ((acount & 0x08) != 0) {
          int[] x5 = {37, 47, 47, 37};
          int[] y5 = {61, 51, 93, 83};
          img.fillPolygon( x5, y5, 4);
      }

      if ((acount & 0x10) != 0) {
          int[] x4 = {6, 16, 35, 45};
          int[] y4 = {95, 85, 85, 95};
          img.fillPolygon( x4, y4, 4);
      }
      
      if ((acount & 0x20) != 0) {
          int[] x3 = {4, 14, 14, 4};
          int[] y3 = {52, 61, 83, 93};
          img.fillPolygon( x3, y3, 4);
      }
      
      if ((acount & 0x40) != 0) {
          int[] x2 = {4, 14, 14, 4};
          int[] y2 = {7, 17, 38, 48};
          img.fillPolygon( x2, y2, 4);
      }

      if ((acount & 0x80) != 0) {
          int[] x1 = {7, 13, 37, 43, 37, 13};
          int[] y1 = {50, 44, 44, 50, 56, 56};
          img.fillPolygon( x1, y1, 6);
      }

  }
  
  public void act() 
  {
  }
}

------------------------------------------------------------------------

Appendix C. Clickable Ball


SevenWorld.java

Replace print7() call in SevenWorld constructor with following:

    addObject( new Button(), 990, 735);


Button.java

Add new actor Ball, set image to golden-ball.png

  import greenfoot.*;

  public class Button extends Actor {
      public int co = 0;
      public int x = 0;
      public int y = 0;
      public void act() {
          if ( Greenfoot.mousePressed(this)) setImage("ball.png"); else setImage("gold-ball.png");
          if ( Greenfoot.mouseClicked(this)) {
              getWorld().addObject( new SevenSeg((char)((int)'0' + co++)), 50 + 55 * x, 75 + 105 * y);
              x = (x > 15) ? 0 : x + 1; y = (x == 0) ? y + 1 : y;
          }
      }    
  }

SevenSeg.java

  As in appendix B.

------------------------------------------------------------------------

Appendix D. EditBox

  7 * 8 <ENTER> displays 56. Exceptions still not handled yet.

TextField class [6] taken from:

  http://www.greenfoot.org/scenarios/7435
  
Expression class [4] have to extend class Actor with no Act() method:

  http://udojava.com/2012/12/16/java-expression-parser-evaluator/

Project classes:

  World
    SevenWorld
      TextWorld
  Actor
    Expression
    SevenSeg
    TextField
      MyTextField


TextWorld.java
--------------

import greenfoot.*;

public class TextWorld extends SevenWorld {
  public TextWorld() {    
      super(640, 480, 1);
      addObject(new MyTextField(""), 320, 50);
  }
}


SevenWorld.java
---------------

import greenfoot.*;

public class SevenWorld extends World {
  public int COLS7 = 1;
  public int ROWS7 = 1;
  
  public int X7INIT = 45;
  public int X7STEP = 55;
  public int Y7INIT = 75;
  public int Y7STEP = 105;
    
  public SevenWorld(int ax, int ay, int acell) {
      super( ax, ay, acell);
      COLS7 = ax / 55;
      ROWS7 = ( ay - 150) / 105;
  }
  
  public void print7at(int ay, String as) {
      int x = 0;
      int y = 0;
      int total = as.length() > COLS7 * ROWS7 ? COLS7 * ROWS7 : as.length();
      for (int i=0; i<total; i++) {
          addObject( new SevenSeg( as.charAt(i)), X7INIT + X7STEP * x, ay + Y7INIT + Y7STEP * y);
          x = (x >= COLS7 - 1) ? 0 : x + 1; y = (x == 0) ? y + 1 : y;
      }
  }
}


MyTextfield.java
----------------

import greenfoot.*;
import java.util.List;

public class MyTextField extends TextField {
    public MyTextField(String as) {
        super( as);
    }
    
    public void onEnter(String as) {
        TextWorld tw = (TextWorld) getWorld();
        int total = as.length();
        if (total > tw.getWidth() / 55) total = 10;
        List remove = tw.getObjects( SevenSeg.class ); 
        for (Object objects : remove) 
            tw.removeObject( (Actor)objects);
    // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
        String s = new Expression( as).eval().toString();
        tw.print7at( 100, s);
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    }
}

Textfield.java [6] 
------------------

Modify

    ...
    else if (input == "enter") {
        onEnter( getText());
    ...
    
    public void onEnter(String as) {
    }


Expression.java [4]
-------------------

import greenfoot.*;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;

public class Expression extends Actor{
...


