Skip to content

Instantly share code, notes, and snippets.

@TheSeamau5
Last active December 29, 2015 21:52
Show Gist options
  • Save TheSeamau5/a7fe4d52fec92d8fe5cb to your computer and use it in GitHub Desktop.
Save TheSeamau5/a7fe4d52fec92d8fe5cb to your computer and use it in GitHub Desktop.
How to make a simple isometric 2D Board in Elm
------------------------------------------------
-- 2D Point Type
type Point = {
x : Float,
y : Float
}
-- Convert Point to a tuple of floats
toTuple : Point -> (Float, Float)
toTuple point = (point.x, point.y)
-- Convert a point from isometric projection to cartesian
toCartesian : Point -> Point
toCartesian isometricPoint =
let i = isometricPoint
in Point ((2 * i.y + i.x) / 2) ((2 * i.y - i.x) / 2)
-- Convert a point from cartesian projection to isometric
toIsometric : Point -> Point
toIsometric cartesianPoint =
let c = cartesianPoint
in Point (c.x - c.y) ((c.x + c.y) / 2)
------------------------------------------
-- Tile Type is an alias for a list of points
-- In this case, a list of 4 points
type Tile = [Point]
-- Function to construct a tile
-- size : size of the tile (assumed square)
-- center : center of the tile (a Point type)
tile : Float -> Point -> Tile
tile size center =
let hs = size / 2
c = center
in [Point (c.x - hs) (c.y - hs),
Point (c.x + hs) (c.y - hs),
Point (c.x + hs) (c.y + hs),
Point (c.x - hs) (c.y + hs)]
------------------------------------------
-- Function to draw a tile on the screen
-- uses Graphics.Collage
drawTile tile =
outlined defaultLine (polygon <| map toTuple tile)
--------------------------------------------
-- Board Type is an alias for a 2D list of tiles
type Board = [[Tile]]
-- helper function to construct a row of tiles
-- columns : number of columns
-- size : size of each tile
-- start : center position of first (or leftmost) tile
row : Float -> Float -> Point -> [Tile]
row columns size start =
if columns <= 0
then []
else (tile size start) :: row (columns - 1) size (Point (start.x + size) start.y)
-- Function to construct a board
-- rows : number of rows
-- columns : number of columns
-- size : size of each tile
-- start : center position of first (or topleftmost) tile
board : Float -> Float -> Float -> Point -> Board
board rows columns size start =
if rows <= 0
then []
else (row columns size start) :: board (rows - 1) columns size (Point start.x (start.y + size))
--------------------------------------------
-- TEST CODE
-- make a board
testBoard = board 6 10 20 (Point -100 -100)
-- convert it to isometric
test = map (map (map toIsometric)) testBoard
-- make a scene (canvas)
scene = collage 400 400
-- Ze main function. Program starts here
-- Change test to testBoard below to see the difference
main = scene <| concatMap (map drawTile) test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment