Floyd Hightower / Mar 26 2022 / Published
Simplex (part 1)
(def :const starting-marbles 1)
(defn get-move []
(rand-int (+ starting-marbles 1)))
(defn find-winner [a-move b-move]
(if (> a-move b-move)
:a
(if (< a-move b-move)
:b
:tie)))
(defn play []
(let [a-move (get-move)
b-move (get-move)]
(println (format "player a move: %d\nplayer b move: %d" a-move b-move))
(find-winner a-move b-move)))
(play)
0.3s
Lessons Learned
As I'm trying to learn and improve my Clojure skills, here are some lessons I learned while writing this code:
Constants can be created by adding `^:const` as [metadata](https://clojure.org/reference/reader#_metadata) to a variable definition
Update: I subsequently found that using `^:const` is [not recommended](https://github.com/bbatsov/clojure-style-guide#naming-constants), but also noticed that it (speeds execution (slightly)). Thus, I'm keeping this metadata for now as documentation.
Appendix
I originally wrote the code for this game in Python:
from typing import Optional, Tuple
starting_marbles = 10
def calculate_payout(player_a_move, player_b_move) -> Tuple[int]:
money = ((starting_marbles - player_a_move), (starting_marbles - player_b_move))
if player_a_move > player_b_move:
return (money[0] + 100, money[1])
elif player_a_move < player_b_move:
return (money[0], money[1] + 100)
else:
return (money[0] + 50, money[1] + 50)
def get_marbles_to_place() -> int:
"""Determine how many numbers to play."""
# these values are just demonstrative... we'll update them later
player_a_marbles = 9
player_b_marbles = 10
return player_a_marbles, player_b_marbles
def play():
player_a_move, player_b_move = get_marbles_to_place()
return calculate_payout(player_a_move, player_b_move)
play()
0.0s