!759 static S scriptID = "#1003305"; !include #1003380 // Chat static JTextArea thoughtArea; static Chat chat; static new L script; static int idx; // learned examples - >0 = move, <0 = stop static PersistentMap examples; p { examples = new PersistentMap("examples"); printStructure(examples); script = parsePoem(scriptID); chat = new Chat; thoughtArea = new JTextArea; JPanel buttons = hgrid( jbutton("Stop", "learnStop"), jbutton("Move", "learnMove")); showSideBySide(programTitle(), chat.swing(), withTitle("Thoughts", centerAndSouth(thoughtArea, buttons))); chat.requestFocus(); chat.onEnter_pre = runnable { if (eq(probableNextMove(), "move")) { ++idx; predict; } }; onUpdate(chat.chatField, "predict"); //swingEverySecond(thoughtArea, runnable { predict; }); predict; } svoid predict { new StringBuilder buf; try { buf.append(unparsePoem(subList(script, idx)) + "\n\n"); S move = probableNextMove(); buf.append("Probable next move: " + move + "\n\n"); } catch Throwable e { buf.append("\n\n" + getStackTrace(e)); } setText(thoughtArea, buf); } sS userInput { ret chat.chatField.getText(); } sS probableNextMove { S input = userInput(); // stop at end if (idx >= l(script)) ret "stop"; // move if correct input E e = get(script, idx); if (e.q != null && match(e.q, input)) ret "move"; // ask learning module S cmd = query(makeState()); if (nempty(cmd)) ret cmd; // anything ret "stop"; } sL makeState { ret litlist(idx, scriptID, userInput()); } svoid learnStop { learn(makeState(), -1); } svoid learnMove { learn(makeState(), 1); } svoid learn(O state, int value) { int count = toInt(examples.get(state)) + value; print("Learner: Updating " + structure(state) + " to " + count); examples.put(state, count); predict; } sS query(O state) { int count = toInt(examples.get(state)); print("Learner: Query " + structure(state) + " = " + count); ret count > 1 ? "move" : count < 0 ? "stop" : null; }