Skip to content

Instantly share code, notes, and snippets.

Created Aug 24, 2021
What would you like to do?
Tic-Tac-Toe Grid GUI Prototype (clojure, quil)
(ns hello-quil.grid
(:require [quil.core :as q]
[quil.middleware :as m]))
(defn hovering? [{:keys [x y width mark] :as cell}]
(let [x2 (+ x width)
y2 (+ y width)
mx (q/mouse-x)
my (q/mouse-y)]
(and (nil? mark)
(> mx x)
(> my y)
(< mx x2)
(< my y2))))
(defn selected? [cell]
(and (q/mouse-pressed?)
(hovering? cell)))
(defn update-cell [mark cell]
(cond (selected? cell) (assoc cell :hover? false :mark mark)
(hovering? cell) (assoc cell :hover? true)
:else,,,,,,,,,,, (assoc cell :hover? false)))
(defn grid-update [{:keys [cells mark] :as state}]
(let [selected (first (filter selected? cells))]
(assoc state :cells (map #(update-cell mark %) cells)
:mark (if (nil? selected) mark (if (= mark :X) :O :X)))))
(defn draw-x [x y size]
(let [offset (/ size 2)
x1 (- x offset)
y1 (- y offset)
x2 (+ x offset)
y2 (+ y offset)]
(q/stroke-weight 10)
(q/line x1 y1 x2 y2)
(q/line x2 y1 x1 y2)))
(defn draw-o [x y size]
(q/stroke-weight 10)
(q/fill 255)
(q/ellipse x y size size))
(defn grid-draw [state]
(doseq [{:keys [x y width mark hover?] :as cell} (:cells state)]
(if hover?
(q/fill 100)
(q/fill 240))
(q/stroke-weight 5)
(q/rect x y width width)
(when (not (nil? mark))
(do (q/fill 42)
(if (= mark :X)
(draw-x (+ x (/ width 2)) (+ y (/ width 2)) (- width (/ width 4)))
(draw-o (+ x (/ width 2)) (+ y (/ width 2)) (- width (/ width 4))))))))
(defn grid-setup []
(q/frame-rate 30)
(q/background 240)
{:width 3
:mark :X
:cells [{:x 0,, :y 0,, :width 100 :mark nil :hover? false}
{:x 100 :y 0,, :width 100 :mark nil :hover? false}
{:x 200 :y 0,, :width 100 :mark nil :hover? false}
{:x 0,, :y 100 :width 100 :mark nil :hover? false}
{:x 100 :y 100 :width 100 :mark nil :hover? false}
{:x 200 :y 100 :width 100 :mark nil :hover? false}
{:x 0,, :y 200 :width 100 :mark nil :hover? false}
{:x 100 :y 200 :width 100 :mark nil :hover? false}
{:x 200 :y 200 :width 100 :mark nil :hover? false}]})
(def transitions
{:choose-grid :player1
:player1 :player2
:player2 :in-play
:in-play :game-over
:game-over :choose-grid})
(def updates
{:choose-grid nil
:player1 nil
:player2 nil
:in-play grid-update
:game-over nil})
(def drawings
{:choose-grid nil
:player1 nil
:player2 nil
:in-play grid-draw
:game-over nil})
(defn update-root [state]
(updates (:current-screen state)))
(defn draw-root [state]
(drawings (:current-screen state)))
:host "grid"
:size [300 300]
:setup #'grid-setup
:update #'grid-update
:draw #'grid-draw
:middleware [m/fun-mode])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment