Hickymcmicky
Hickymcmicky

Reputation: 21

Methods that create a die game

I am trying to create a die game that gets results from a single die that is rolled twice

I made the die

(defn roll [] (+ (rand-int 5) 1))

I need the outcome from this game, a win state where i roll a seven from rolling the die twice and a method that counts how many times the dice was rolled.

I tried creating a game method that has one parameter called count that keeps track of how often the dice is rolled which my failed attempt looks like -

(defn game [count] (if (roll) (+ count 1)))

I also would need my if statement, if the dice total is 7, return count and a statement that you won or else do a recursive call of the method and pass count+1.

But i was told that it would be easy to create three vars using a let function which i will call die1, die2, and total. But i would not know how to begin those vars and without them i can't begin my if statement let alone my game method.

I would really appreciate it if i would get help for my large problem, sorry if this is a lot but I'm fairly new to Clojure and have been trying to get some help, thank you.

Upvotes: 0

Views: 142

Answers (1)

Alan Thompson
Alan Thompson

Reputation: 29986

You could do something like this to get started:

(defn roll []
  (inc (rand-int 6))) ; rand-int is [0..N)

(defn game []
  (let [roll1 (roll)
        roll2 (roll)
        total (+ roll1 roll2)
        result (if (= 7 total)
                 :win
                 :lose)]
    (println {:roll1 roll1 :roll2 roll2 :total total :result result})))


; play some games
(dotimes [i 22]
  (game))

with results like

{:roll1 4, :roll2 5, :total 9, :result :lose}
{:roll1 4, :roll2 3, :total 7, :result :win}
{:roll1 3, :roll2 4, :total 7, :result :win}
{:roll1 5, :roll2 3, :total 8, :result :lose}
{:roll1 1, :roll2 5, :total 6, :result :lose}
{:roll1 3, :roll2 6, :total 9, :result :lose}
{:roll1 2, :roll2 3, :total 5, :result :lose}
{:roll1 1, :roll2 6, :total 7, :result :win}
{:roll1 2, :roll2 5, :total 7, :result :win}
{:roll1 3, :roll2 4, :total 7, :result :win}
{:roll1 1, :roll2 4, :total 5, :result :lose}
{:roll1 3, :roll2 4, :total 7, :result :win}
{:roll1 2, :roll2 1, :total 3, :result :lose}
{:roll1 4, :roll2 6, :total 10, :result :lose}
{:roll1 5, :roll2 2, :total 7, :result :win}
{:roll1 1, :roll2 5, :total 6, :result :lose}
{:roll1 1, :roll2 6, :total 7, :result :win}
{:roll1 1, :roll2 2, :total 3, :result :lose}
{:roll1 5, :roll2 2, :total 7, :result :win}
{:roll1 1, :roll2 2, :total 3, :result :lose}
{:roll1 4, :roll2 4, :total 8, :result :lose}
{:roll1 1, :roll2 1, :total 2, :result :lose}

Please see this list of documentation, especially the Clojure CheatSheet and the book "Getting Clojure".

Upvotes: 2

Related Questions