Last active
May 25, 2024 08:39
-
-
Save dacr/ea8ed37c3e47ca76883c6a98f9041dcb to your computer and use it in GitHub Desktop.
hexagons and grids coordinates conversions / published by https://github.com/dacr/code-examples-manager #5b018fd2-9875-4826-977d-8e9dd61876c7/f28445e2db66a9d0417837102458c579be3c687b
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// summary : hexagons and grids coordinates conversions | |
// keywords : scala, coordinates, hexagons, conversions, @testable | |
// publish : gist | |
// authors : David Crosson | |
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// id : 5b018fd2-9875-4826-977d-8e9dd61876c7 | |
// created-on : 2020-12-30T08:59:43Z | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : scala-cli $file | |
// --------------------- | |
//> using scala "3.4.2" | |
//> using dep "org.scalatest::scalatest:3.2.16" | |
//> using objectWrapper | |
// --------------------- | |
import org.scalatest._, flatspec._, matchers._ | |
import scala.math._ | |
trait HexaCoords { | |
type Direction=String | |
case class OffsetCoord(q:Int, r:Int) | |
case class CubeCoord(x:Int, y:Int, z:Int) { | |
def add(that:CubeCoord):CubeCoord = CubeCoord(x+that.x, y+that.y, z+that.z) | |
} | |
val moves:Map[Direction,CubeCoord] = Map( | |
"n" -> CubeCoord(+0,+0,-1), | |
"s" -> CubeCoord(+0,+0,+1), | |
"e" -> CubeCoord(+1,-1,+0), | |
"w" -> CubeCoord(-1,+1,+0), | |
"nw" -> CubeCoord(+0,+1,+0), | |
"se" -> CubeCoord(+0,-1,+0), | |
"ne" -> CubeCoord(+1,+0,+0), | |
"sw" -> CubeCoord(-1,+0,+0), | |
) | |
// convert odd-r offset to cube | |
implicit def offset2cube(o:OffsetCoord):CubeCoord = { | |
val x = o.q-(o.r - (o.r&1))/2 | |
val z = o.r | |
val y = -x-z | |
CubeCoord(x, y, z) | |
} | |
// convert cube to odd-r offset | |
implicit def cube2offset(c:CubeCoord):OffsetCoord = { | |
val q = c.x + (c.z-(c.z&1)) / 2 | |
val r = c.z | |
OffsetCoord(q,r) | |
} | |
def distance(a:CubeCoord, b:CubeCoord):Int = { | |
(abs(a.x - b.x) + abs(a.y - b.y) + abs(a.z - b.z)) / 2 | |
} | |
} | |
class HexaCoordsTest extends AnyFlatSpec with should.Matchers with HexaCoords { | |
override def suiteName: String = "TranscodingTest" | |
"Encoding" should "encode x,y coordinate into single int value" in { | |
} | |
} | |
org.scalatest.tools.Runner.main(Array("-oDF", "-s", classOf[HexaCoordsTest].getName)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment