CM148 Assignment 5

Base code for Tracery story grammar

HTML

<script src="https://cdn.rawgit.com/galaxykate/tracery/master/js/tracery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.0.0/codemirror.min.js"></script>

<div class="col-lg-12">
    
    <h3>Tiny Tales<br />
        <small>A story grammar ripped off from Kate Compton's <a href="http://www.crystalcodepalace.com/traceryTut.html" target="_blank">Tracery Tutorial</a></small>
    </h3>
    
<!-- Put your tracery grammar inside this #source textarea!-->    
<textarea id="source">
{
    "name": ["Cheri","Fox","Morgana","Jedoo","Brick","Shadow","Krox","Urga","Zelph"],    
    "story": ["#hero.capitalize# was a great #occupation#, and this song tells of #heroTheir# adventure. #hero.capitalize# #didStuff#, then #heroThey# #didStuff#, then #heroThey# went home to read a book."],
    "monster": ["dragon","ogre","witch","wizard","goblin","golem","giant","sphinx","warlord"],
    "setPronouns": ["[heroThey:they][heroThem:them][heroTheir:their][heroTheirs:theirs]","[heroThey:she][heroThem:her][heroTheir:her][heroTheirs:hers]","[heroThey:he][heroThem:him][heroTheir:his][heroTheirs:his]"],
    "setOccupation": ["[occupation:baker][didStuff:baked bread,decorated cupcakes,folded dough,made croissants,iced a cake]","[occupation:warrior][didStuff:fought #monster.a#,saved a village from #monster.a#,battled #monster.a#,defeated #monster.a#]"],
    "origin": ["#[#setPronouns#][#setOccupation#][hero:#name#]story#"]
}
</textarea>
    
    <br />
    <h4>
        <div class="btn btn-default" id="generate">
            Generate Expansion 
            <span class="glyphicon glyphicon-repeat" aria-hidden="true"></span>
        </div>
    </h4>
    
    <div class="well" id="example">... loading tracery ...</div>
    
</div>

CSS

@import url("https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.0.0/codemirror.min.css");

.CodeMirror {
    border: 1px solid #888;
    height: auto;
}

JavaScript

var editor = CodeMirror.fromTextArea($('#source')[0], {
    lineNumbers: true,
    mode: {
        name: "javascript",
        json: true
    }
});

// tracery in action
function generate() {
    var source_text = editor.getValue();
    var grammar = tracery.createGrammar(JSON.parse(source_text));
    var example = grammar.flatten('#origin#');
    $('#example').text(example);
}

// when text changes, generate expansion
editor.on('change', generate);

// when button clicked, generate expansion
$("#generate").on('click', generate);

// Tracery takes some time to load. Wait a second, then try to generate
setTimeout(generate, 1000);