1 16 package org.apache.cocoon.components.flow.apples.samples; 17 18 import java.util.HashMap ; 19 import java.util.Map ; 20 import java.util.Stack ; 21 22 import org.apache.avalon.framework.logger.AbstractLogEnabled; 23 import org.apache.cocoon.ProcessingException; 24 import org.apache.cocoon.components.flow.apples.AppleController; 25 import org.apache.cocoon.components.flow.apples.AppleRequest; 26 import org.apache.cocoon.components.flow.apples.AppleResponse; 27 28 31 public class HanoiApple extends AbstractLogEnabled implements AppleController { 32 33 public static final int NONE = -1; 34 public static final int SRC = 0; 35 public static final int AUX = 1; 36 public static final int DST = 2; 37 38 public Stack [] stacks; 40 public Object floatingDisk = null; 41 public int moves = 0; 42 public int puzzleSize = 0; 43 44 45 public String toString() { 46 return "HanoiApple[ stacks=" + this.stacks + " | floatingDisk=" + this.floatingDisk 47 + " | moves = " + this.moves + "]"; 48 } 49 50 51 public void process(AppleRequest req, AppleResponse res) throws ProcessingException { 52 53 if (stacks == null) { 55 String requestSize = req.getCocoonRequest().getParameter("size"); 56 if (requestSize != null) { 57 try { 58 int size = Integer.parseInt(requestSize); 59 intializeStacks(size); 60 } catch (NumberFormatException ignore) { 61 } 62 } 63 } else { 64 String requestStack = req.getCocoonRequest().getParameter("stack"); 66 if (requestStack != null) { 67 try { 68 int stackNdx = Integer.parseInt(requestStack); 69 if (this.floatingDisk != null) { 70 if ( this.stacks[stackNdx].size() == 0 72 || ((Integer )this.floatingDisk).intValue() < ((Integer )this.stacks[stackNdx].peek()).intValue()) { 73 74 this.stacks[stackNdx].push(this.floatingDisk); 75 this.floatingDisk = null; 76 this.moves++; 77 } 78 } else { 79 if (this.stacks[stackNdx].size() != 0) { 80 this.floatingDisk = this.stacks[stackNdx].pop(); 81 } 82 } 83 } catch (RuntimeException ignore) { 84 } 87 } 88 } 89 90 getLogger().debug(toString()); 91 92 if (stacks == null) { 94 res.sendPage("hanoi/intro.jx", null); 95 } else { 96 Map bizdata = new HashMap (); 97 bizdata.put("stacks" , this.stacks); 98 bizdata.put("moves" , "" + this.moves); 99 bizdata.put("floatingDisk", this.floatingDisk); 100 bizdata.put("nextMove" , this.floatingDisk==null ? "Lift it!" : "Drop it!"); 101 bizdata.put("puzzleSize" , "" + this.puzzleSize); 102 103 res.sendPage("hanoi/hanoi.jx", bizdata); 104 } 105 106 } 107 108 109 private void intializeStacks(int size) { 110 if (size > 2) { 111 this.stacks = new Stack [3]; 112 for (int i = 0; i < 3; i++) { 113 this.stacks[i] = new Stack (); 114 } 115 for (int i = size; i > 0; i--) { 116 this.stacks[0].push(new Integer (i)); 117 } 118 this.puzzleSize = size; 119 } 120 } 121 122 } 123 | Popular Tags |