Q: Clojure - Codeexamples to show off software transactional memory I created some exercises to show the capabilties and funcionality of the clojure stm. Are they good enough, or are there better ways to show the benefits of stm?
My work:
Item transfer


*

*Define the three characters as follows:
(def smaug (ref {:life 500, :atk 50, :def 25, :alive true, :items (set(range 100))))
(def bilbo (ref {:life 250, :atk 35, :def 12, :alive true, :items ()}))
(def gandalf (ref {:life 300, :atk 27, :def 8, :mana 50, :alive true, :items ()}))  

Now implement an appropriate function to transfer one of a character's :items to one of the other characters.


*Now that you can easily transfer :items from one character to another, start two threads, one for bilbo and one for gandalf, and let both threads transfer :items from smaug to bilbo and gandalf until smaug has no :items left.

*Why does the following transaction throw an exception?
(dosync
    @(future (dosync 
        (alter bilbo update-in [:items] conj (first (get @smaug :items))) 
            (alter smaug update-in [:items] disj (first (get @smaug :items))))) 
(alter gandalf update-in [:items] conj (first (get @smaug :items)))
(alter smaug update-in [:items] disj (first (get @smaug :items)))) 

Battle system


*

*Start over with three characters from the beginning. Now implement a function which simulates a battle between two characters. Therefore the :atk value of the attacker minus the :def value of the defender is subtracted from the :life value of the defender. Per battle there is only one attacker and one defender.
Now let one of the characters fight against smaug and if one defeats smaug, he gets all of his :items. Keep in mind that the :life value shall never be smaller than 0!!!
If the :life value of a character is 0, the character is dead. Therefore the :alive value is set to false.

*As you might have noticed can no character defeat smaug by his own. Lucky, gandalf can heal other characters. But first you have to implement a function, which lets gandalf heal bilbo. Therefore the :life value is increased. Simultanously healing decreases gandalf's :mana. If his :mana reaches 0 he can;t heal. Now let gandalf heal bilbo after every battle. Now that both characters are involved in the battle, both shall receive :items from smaug. Keep in mind that the :mana value should never be smaller than 0. Bilbos :life value should never be smaller than 0 too!!!

*Now we want to make the game more dynamic. We want to make the :atk value of bilbo and gandalf depending of the day time.
Now implement day cycle. To represent the day time define an integer value as a ref. This value should be updated every second in a seperate thread. Therefore attle and day cycle are executed by seperated threads. Every update increments the day time by 1. The maximum value is 23.
If it is day (6 – 17),  bilbo und gandalf get a bonus of 1/3 of their :atk value. At night (18 - 5) they get a negative bonus of 1/3.

