Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 27, 2023 06:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/ea8ed37c3e47ca76883c6a98f9041dcb to your computer and use it in GitHub Desktop.
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/2c28d2cdaaff53856cbdb4d43be9a20ed0236e06
// 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.3.0"
//> 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