Skip to content

Instantly share code, notes, and snippets.

@TheSeamau5
Last active February 8, 2016 22:05
Show Gist options
  • Save TheSeamau5/3972c7ff473e5717bffb to your computer and use it in GitHub Desktop.
Save TheSeamau5/3972c7ff473e5717bffb to your computer and use it in GitHub Desktop.
Simple way to create a hexagonal grid in Elm
import List (..)
import Text (asText)
import Graphics.Collage (..)
import Graphics.Element (..)
import Color (..)
--Based on http://www.redblobgames.com/grids/hexagons/
type alias Point = {
x : Int,
y : Int
}
-- WE STORE A GRID AS A LIST OF POINTS
type alias Grid = List Point
-- CREATE A HEX GRID WITH A GIVEN NUMBER OF LEVELS
hexGrid : Int -> Grid
hexGrid levels =
let fullColumn x = map (Point x) [(-levels)..levels]
makeColumn x =
if | x < 0 -> drop (abs x) (fullColumn x)
| x > 0 -> reverse (drop (abs x) (reverse (fullColumn x)))
| otherwise -> fullColumn x
in
concatMap makeColumn [(-levels)..levels]
---CODE TO RENDER A HEX GRID----
-------
--Play with these values to see what they do
hexSize = 10
hexColor = red
hexLevels = 9
--------
hexagon = ngon 6 hexSize
-- Formula to convert axial coordinates (pointy-top) to
-- screen coordinates
toScreen hex = {
x = hexSize * (sqrt 3) * ((toFloat hex.x) + (toFloat hex.y) / 2),
y = hexSize * 3 / 2 * (toFloat hex.y)}
-- Render the grid
renderGrid : Grid -> List Form
renderGrid grid =
let renderHex hex =
let screenHex = toScreen hex
in move (screenHex.x, screenHex.y) <|
rotate (degrees 30) <|
filled hexColor <|
hexagon
in
map renderHex grid
grid = hexGrid hexLevels
render = collage 400 400
main = render <| renderGrid grid
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment